Uploading Files In PHP

PHP upload file

Some of the web applications need functionality to upload files on the server. This post tells you the problem and their solutions while uploading files on the server using the PHP upload file.

Simple code to upload file in PHP

HTML Form

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select file to upload:
  <input type="file" name="file1" id="file1">
  <input type="submit" value="Upload File" name="submit">
</form>

PHP code – (upload.php)

<?php
define('SYSTEM_PATH',str_replace('upload.php', '', __FILE__));
define('FILE_PATH', SYSTEM_PATH."uploads/");

$filename = $_FILES['file1']['name'];
$filepath = FILE_PATH.$filename;
if(move_uploaded_file($_FILES['file1']['tmp_name'], $filepath)) 
{
   echo "Uploaded";
} 
else
{
   echo "Failed";
}

?>

__FILE__ is a magic constant in PHP. I am using it to get the absolute path of file upload.php i.e./home/public_html/myapp/upload.php. After removing “upload.php”, i got a absolute path of a directory.

To get and set the absolute path of the “uploads” directory on the server SYSTEM_PATH’ and ‘FILE_PATH’ constant is used. SYSTEM_PATH returns the path of the folder where the upload.php script is running. If the script running in /var/www/upload.php then it will be /var/www/. and FILE_PATH set the upload directory by concatenating the SYSTEM_PATH i.e. /var/www/uploads/.

When u run the script file will be uploaded in “uploads” directory.

Handling errors

While uploading files, you need to handle errors generated by the server. In PHP with $_FILES[‘file1’][‘error’] variable return the error code. Return zero if there is no error else return a positive value which indicates an error.

if(isset($_FILES['file1'])) {
	$error = $_FILES['file1']['error'];
	switch($error)  // error in uploading
	{				
		case 1: $errormsg = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break;
		case 2: $errormsg = "The uploaded file exceeds the MAX_FILE_SIZE directive"; break;
		case 3: $errormsg = "The uploaded file was only partially uploaded"; break;
		case 4: $errormsg = "No file was uploaded"; break;
		case 6: $errormsg = "Missing a temporary folder"; break;
		case 7: $errormsg = "Failed to write file to disk" ; break;
		case 8: $errormsg = "A PHP extension stopped the file upload."; break;
	}
	if($error != 0) 
	{ 
		echo "Error " . $errormsg
	}
}