Uploading a file to MySQL is a two step process. First you need to upload the file to the server then read the file and insert it to MySQL.
For uploading a file we need a form for the user to enter the file name or browse their computer and select a file. The input type="file" is used for that purpose.
Example : upload.php
An upload form must have encytype="multipart/form-data" otherwise it won't work at all. Of course the form method also need to be set to method="post". Also remember to put a hidden input MAX_FILE_SIZE before the file input. It's to restrict the size of files. After the form is submitted the we need to read the autoglobal $_FILES. In the example above the input name for the file is userfile so the content of $_FILES are like this : $_FILES['userfile']['name']
$_FILES['userfile']['type']
$_FILES['userfile']['size']
$_FILES['userfile']['tmp_name']
$_FILES['userfile']['error']
|
Example : upload.php
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
include 'library/config.php';
include 'library/opendb.php';
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
include 'library/closedb.php';
echo "
File $fileName uploaded
";
}
?>
PHP saves the uploaded file with a temporary name and save the name in $_FILES['userfile']['tmp_name']. Our next job is to read the content of this file and insert the content to database. Always make sure that you use addslashes() to escape the content. Using addslashes() to the file name is also recommended because you never know what the file name would be.
That's it now you can upload your files to MySQL. Now it's time to write the script to download those files.
Enjoy ubuntu... :)
Tq http://www.php-mysql-tutorial.com/
No comments:
Post a Comment