Tuesday, August 19, 2008

Simple file upload in PHP

File Upload In Php

One of the important aspects in php is file upload. File upload in php is very simple, but you need to be careful while doing it, because allowing users to upload file to server means possibly providing whole can of worms.

To upload file create one simple html form .
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
Choose a file to upload: <input name=" file" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>

Note the attributes of the form here.
enctype = "multipart/form-data". It specifies which content-type to use when submitting information back to server. Without these requirements, your file upload will not work.
Action = php script path, which will have php code to upload the file to desired path
Method = “POST”

Here, another thing to notice is the hidden form field named MAX_FILE_SIZE. Some web browsers actually pick up on this field and will not allow the user to upload a file bigger than this number (in bytes).
You can also set this value in php.ini. Also make sure that file_uploads inside your php.ini file is set to On.

Now it’s time to create upload.php; which has been referenced in form tag.


//Сheck if file is present
if((!empty($_FILES[“file”])) && ($_FILES[“file”][“error”] == 0)) {
//Check if the file is JPEG image and it”s size is less than 350Kb
$filename = basename($_FILES[“file”][“name”]);
$ext = strtolower(substr($filename, strrpos($filename, “.”) + 1));
if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") &&
($_FILES["file"]["size"] < 350000)) {
//Determine the path to which we want to save this file
$newname =”upload/”.$filename;
//Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it”s new place
if ((move_uploaded_file($_FILES[“file”][“tmp_name”],$newname))) {
echo "It”s done! The file has been saved as: ".$newname; } else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
?>

Note: Be sure that PHP has permission to read and write to the directory in which temporary files are saved and the location in which you're trying to copy the file.

Guys, there you are. This script will upload image files with validations.
You can even add the validations by checking the header of uploading file upto first 100 bytes and make sure that file being uploaded is image file.

This example is simple way to upload file. If you re beginner in php, this should help you. In case any questions / feedback, please mail me at ninad.blog@gmail.com

No comments: