Saturday, December 18, 2010

PHP Uploading File

For build an upload application, you need two files. One for upload interface, and one another for processing the file. Firstly, make upload.html:

<form action="temp3.php" method="post" enctype="multipart/form-data">
File: <input type="file" name="file"/>
<input type="submit" value="Upload"/>
Then make your php file for processing the file:

    "./".$_FILES["file"]["name"])){   // save in same folder
    echo "Success Upload";
    echo "Fail For Upload";


With two files above, you must have upload application.

To get the file name, use:
echo $_FILES["file"]["name"];

To get the file size, use:
echo $_FILES["file"]["size"];    // in bytes. divide by 1024 
                                 // to get kB

To get the file type, use:
echo $_FILES["file"]["type"];

To get the the error code, use:
echo $_FILES["file"]["error"];     // if 0, it is success

To get just some specified file type, use:
if(($_FILES["file"]["type"] == "image/gif") || 
   ($_FILES["file"]["type"]=="image/jpg") || 
    // process file
    echo "Upload Failed";

To limit the size, for example just for 2 kB, use:
if ($_FILES['file"]["size"] < 2000) {
    // process files
    echo "Failed to upload";

To place the file in the same folder of upload.php, use:
$target = "./".$_FILES["file"]["name"];

To place it in the root of file system, use:
$target = "/".$_FILES["file"]["name"];

To pace it in the upload folder that same level to htdocs (assume upload.php in htdocs), use:
$target = "../upload/".$_FILES["file"]["name"];

No comments:

Post a Comment