WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 File Upload

With PHP, you can upload files to the server.

The examples in this chapter are completed under the test project, and the directory structure is:

test
|-----upload             # File upload directory
|-----form.html          # Form file
|-----upload_file.php    # php Upload code

Create a file upload form

It is very useful to allow users to upload files from a form.

Look at this HTML form for uploading a file:

<html>
<head>
<meta charset="utf-8">
<title>welookups Tutorial(welookups.com)</title>
</head>
<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
    <label for="file">file name:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="submit">
</form>

</body>
</html>

Save the above code in a form.html file.

Here are some notes about the above HTML form:

  • <form> The enctype attribute of the tag specifies which content type to use when submitting the form. When the form requires binary data, such as file content, use "multipart/form-data"。
  • <input> The type = "file" attribute of the tag specifies that the input should be processed as a file. For example, when previewing in a browser, you will see a browse button next to the input box.

Note: Allowing users to upload files is a huge security risk. Only allow trusted users to perform file uploads.


Create upload script

The "upload_file.php" file contains code for uploading files:

<?php
if ($_FILES["file"]["error"] > 0)
{
    echo "error:" . $_FILES["file"]["error"] . "<br>";
}
else
{
    echo "Upload file name: " . $_FILES["file"]["name"] . "<br>";
    echo "file type: " . $_FILES["file"]["type"] . "<br>";
    echo "File size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Where the files are temporarily stored: " . $_FILES["file"]["tmp_name"];
}
?>

Using PHP's global array $ _FILES, you can upload files from a client computer to a remote server.

The first parameter is the input name of the form, and the second subscript can be "name", "type", "size", "tmp_name", or "error". It looks like this:

  • $ _ FILES ["file"] ["name"]-the name of the uploaded file
  • $ _ FILES ["file"] ["type"]-Type of uploaded file
  • $ _ FILES ["file"] ["size"]-The size of the uploaded file in bytes
  • $ _ FILES ["file"] ["tmp_name"]-the name of the temporary copy of the file stored on the server
  • $ _ FILES ["file"] ["error"]-Error codes caused by file uploads

This is a very simple way to upload files. For security reasons, you should increase restrictions on which users are allowed to upload files.


Upload restrictions

In this script, we have increased restrictions on file uploads. Users can only upload .gif, .jpeg, .jpg, .png files, and the file size must be less than200 kB:

<?php
//Allowed image suffixes to be uploaded 
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);        //Get file suffix name
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 204800)    //Less than200 kb
&& in_array($extension, $allowedExts))
{
    if ($_FILES["file"]["error"] > 0)
    {
        echo "error:: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        echo "Upload file name: " . $_FILES["file"]["name"] . "<br>";
        echo "file type: " . $_FILES["file"]["type"] . "<br>";
        echo "File size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Where the files are temporarily stored: " . $_FILES["file"]["tmp_name"];
    }
}
else
{
    echo "Illegal file format";
}
?>


Save uploaded file

The above example creates a temporary copy of the uploaded file in the server's PHP temporary folder.

This temporary copy file will disappear at the end of the script. To save the uploaded file, we need to copy it to another location:

<?php
//Allowed image suffixes to be uploaded
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
echo $_FILES["file"]["size"];
$extension = end($temp);     //Get file suffix name
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 204800)   //Less than200 kb
&& in_array($extension, $allowedExts))
{
    if ($_FILES["file"]["error"] > 0)
    {
        echo "error:: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        echo "Upload file name: " . $_FILES["file"]["name"] . "<br>";
        echo "file type: " . $_FILES["file"]["type"] . "<br>";
        echo "File size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Where the files are temporarily stored: " . $_FILES["file"]["tmp_name"] . "<br>";
        
        //Determine if the file exists in the upload directory under the current directory
        //If there is no upload directory, you need to create it. The upload directory permissions are 777
        if (file_exists("upload/" . $_FILES["file"]["name"]))
        {
            echo $_FILES["file"]["name"] . " The file already exists。 ";
        }
        else
        {
            //If the file does not exist in the upload directory, upload the file to the upload directory
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
            echo "File stored in: " . "upload/" . $_FILES["file"]["name"];
        }
    }
}
else
{
    echo "Illegal file format";
}
?>

The above script checks whether the file already exists. If it does not exist, it copies the file to a directory named "upload".

The file upload demo operation is as follows: