Tuesday, December 9, 2014

Get Detail of Uploading Files to the Server Using PHP

Here, is the upload script. In this method, we won't save the file in the database. We will only store the file information, but the original file is stored in the file server. There is a need of some modification to the upload table. Instead of using BLOB data type we just use VARCHAR to store the file path.

Uploading Files to the Server Using PHP

 CREATE TABLE upload2 (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
path VARCHAR(60) NOT NULL,
PRIMARY KEY(id)
);

The HTML form has no difference with the previous one since the real changes will take place in the code of PHP.  

<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>

Now, Let's move to the upload process. First of all, we need to specify the directory to store the uploaded files. We store the directory name in $uploadDir. Make sure that PHP must have to write access to $uploadDir otherwise the upload would get fail. There is a need to set the permission for the upload directory to 777, if you are web host using a Linux server.

<?php
$uploadDir = 'C:/webroot/upload/';

if(isset($_POST['upload']))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$filePath = $uploadDir . $fileName;

$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}

include '../library/config.php';
include '../library/opendb.php';

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}

$query = "INSERT INTO upload2 (name, size, type, path ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$filePath')";

mysql_query($query) or die('Error, query failed : ' . mysql_error());

include '../library/closedb.php';

echo "<br>Files uploaded<br>";

}
?>

Here, the key is the move_uploaded_file() function. The function will move to the uploaded files from the temporary upload directory. For any reason, if the function cannot move the file, it will return false, and we exit the script because there is no usage of continuing the script.

Reference :- http://www.php-mysql-tutorial.com/wikis/php-tutorial/uploading-files-to-the-server-using-php.aspx

0 comments:

Post a Comment