PHP File Upload

PHP provides file upload variable, $_FILES associative array, to permit file upload to an web server. To upload a file to the server, an HTML form must be composed to allow a user to select a file from local filesystem to upload.

HTML Form: Create a HTML file with the following content, and call it form.html.

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" >
Filename: <input type="file" name="upfile"><br>
<input type="submit" value="Upload">
</form>

The description of important tag parameters are as follows:

action="upload.php" - The name of PHP script that will do the file upload (shown below).
method="POST" - (must be) POST method.
enctype="multipart/form-data" - (must be) added to the form parameter.
input type="hidden" name="MAX_FILE_SIZE" - Maximum allowable file size, in bytes.
input type="file" name="upfile" - Provides "Browse" button for local file search.

The HTML from is displayed on the browser as follows:


Filename:

When user clicks the "Upload" button, the data will be posted to the server and upload.php script will process the form data. When the script is executed, the uploaded file is stored in a temporary location on the server. It is the PHP (action) script that will process or save the file in a safe location by using the $_FILES associative array. Upon completion of the script execution, the temporary file is destroyed.

There are two elements of the $_FILES array that are important.
upfile - The name of the HTML input element used to upload a file.
$_FILES['upfile']['name'] - The name of the original file path of the uploaded file.
$_FILES['upfile']['tmp_name'] - The temporary file (path) that resides on the server.

The PHP (action) script that moves a uploaded file to a new location looks like this:

$target_path = "uploads/" . basename( $_FILES['upfile']['name']); 
if (move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) {
    echo "Upload successful.";
}

The PHP (action) script that processes the uploaded file looks like this:

$lines = file( $_FILES['upfile']['tmp_name']);
foreach ($lines as $line) {
    // Process the file contents.
}
Tags: 

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.