Simple File Uploading using PHP

This is my first post for PHP, a server-side scripting language widely used for web development. As I’m new to this language, the techniques may sounds naive. 🙂

To receive file uploaded through http, you can use the PHP script below (let’s call it receive.php),

<?php

    ini_set('display_errors', 'On');

    error_reporting(E_ALL);

    $target_path = "./upload/";

    $target_path = $target_path . basename( $_FILES['myfile']['name']); 

    echo $target_path;

    if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {

        echo "The file ".  basename( $_FILES['myfile']['name']). 

        " has been uploaded";

    } else{

        echo "There was an error uploading the file, please try again!";

    }

?>

PHP does a lot of things for you and keep the interface simple. For file uploading, it will save the received the file data to a temporary file. The temporary file is going to be removed at the end of execution of the script. To get the file, one needs to use move_uploaded_file.

move_uploaded_file method takes two parameters, the temporary file and the destination. The temporary file name can be retrieved using $_FILES[‘myfile’][‘tmp_name’], where myfile is the name of of the name of the file input type you defined in your html page. The code above construct the target_path as the upload folder + the uploaded file name.

The first two lines enable the error reporting. It’s convenient for debugging.
To test the code, one can use the following html page (let’s call it test.html),

<html>

<body>

<form action="receive.php" method="post"

enctype="multipart/form-data">

<input type="file" name="myfile"><br>

<br />

<input type="submit" name="submit" value="Submit" />

</form>

</body>

</html>

The html page declares an input of file type with name “myfile”. It uses html post message to upload the file, and the file data is encrypted using multipart. We indicates receive.php to handle the post message.

If you have your testing web server set up with php configured properly. You can place the receive.php and test.html files into the web directory. Create a upload folder with proper permission. And open up test.html page in a browser as shown below,

Figure 1. Upload Test Page Interface

You can browse for a file and click submit, then the file upload will be handled by receive.php.

Figure 2. Upload Result Page

Note that the html page and php scripts are for illustration and study only. The actually production script should consider a lot of other stuff, like error handling, security etc.