Thursday, 25 July 2013

Store a file in MySQL database

Firstly, create a table in database. We use longblob as the data type to store the content of the file.

mysql> CREATE TABLE IF NOT EXISTS `Files` (
    ->   `ID` int(25) NOT NULL auto_increment,
    ->   `Title` varchar(250) NOT NULL default '',
    ->   `File_Name` varchar(250) NOT NULL default '',
    ->   `File_Type` varchar(15) NOT NULL default '',
    ->   `File_Size` varchar(45) NOT NULL default '',
    ->   `File_Content` longblob NOT NULL,
    ->   `File_Extension` varchar(10) NOT NULL default '',
    ->   PRIMARY KEY  (`ID`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
Query OK, 0 rows affected (0.76 sec)

The html form to call the php script. The enctype of the form must be multipart/form-data.

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

The php script to read the file, store it into the database, and copy it to upload folder of the web server.

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png", "txt");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "text/html")
|| ($_FILES["file"]["type"] == "text/plain"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }

 // store in SQL
 $user_name = "root";
      $password = "root";
      $database = "test";
      $server = "localhost";

 $fileName = $_FILES['file']['name'];
      $tmpName  = $_FILES['file']['tmp_name'];
      $fileSize = $_FILES['file']['size'];
      $fileType = $_FILES['file']['type'];

 // Slurp the content of the file into a variable            
      $fp = fopen($tmpName, 'r');
      $content = fread($fp, filesize($tmpName));
      $content = addslashes($content);
      fclose($fp);
      if(!get_magic_quotes_gpc()){
          $fileName = addslashes($fileName);
      }
 $file_info = pathinfo($_FILES['file']['name']);

      // Connect to the database
      $dbh = mysql_connect($server,$user_name,$password) or die("There was a problem with the database connection.");
      $dbs = mysql_select_db($database, $dbh) or die("There was a problem selecting the categories.");
 $sql = "INSERT INTO Files SET
                Title = 'Title',
                File_Name = '".$fileName."',
                File_Type = '".$fileType."',
                File_Size = '".$fileSize."',
                File_Content = '".$content."',
                File_Extension = '".$file_info['extension']."'";
      //print $sql;        
             
      $result = mysql_query($sql);
 if(!$result){
        echo "Could not add this file.";  
      }
      else{
        echo  "New file successfully added.";
      }
 mysql_close($dbh);
    }
  }
else
  {
  echo "Invalid file";
  }
?>

No comments:

Post a Comment