Thursday, November 10, 2011

Php Upload a file

HTML Upload form


<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>

  • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded
  • The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload
------------------------------------------------------

/*Check for the file type to upload gif/jpeg/pjpeg and size less than 20 MB */
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
/*check for errors finding the file or read permissions*/
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 />";
    /*check if the file already exists in the upload directory*/    if (file_exists("upload/" . $_FILES["file"]["name"]))
    {
        echo $_FILES["file"]["name"] . " already exists. ";
    
    else    {         /*move the uploaded file to upload directory*/
        move_uploaded_file($_FILES["file"]["tmp_name"],"upload/". $_FILES["file"]["name"]);
        echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

    }
    }
}
else
{
echo "Invalid file";
}
?>

No comments:

Post a Comment