PHP Tutorials - Herong's Tutorial Examples - v5.17, by Herong Yang
File Upload PHP Script
This section provides a tutorial example on how to write PHP script to process uploaded files on the Web server. $_FILES[] built-in hash table has infomation of all uploaded files prepared for you by the PHP engine.
After the user selecting files and submitting the upload form, the Web browser will send selected files to the Web server to process. If the Web server passes this job to a PHP script, the PHP engine will parse those uploaded files and provide the following interface functionalities to the PHP script:
1. File Size Validation - If any file is larger than the specified MAX_FILE_SIZE value, it will be rejected.
2. Populting $_FILES[] - Each uploaded file will be stored in temporary directory on the Web server with a temporary name. A new entry will be added to the built-in hash table $_FILES[] with the following information:
3. Providing move_uploaded_file() Function - A nice tool to move the uploaded file to a more permanent location.
4. Providing is_uploaded_file() Function - A nice tool to ensure the uploaded file was indeed uploaded from a HTTP POST request. This is needed to preventing some upload attacks that play tricks on upload file names.
5. Providing getallheaders() Function - A tool to access HTTP request headers just in case you want know more about the client.
6. No functionality to access the HTTP POST request body raw data, since it is encoded as "multipart/form-data", a requirement for uploading files. The 2 options of access POST body raw data: php://input and $HTTP_RAW_POST_DATA are both not available with enctype="multipart/form-data".
Here is an example of a PHP script, file-upload-handler.php, to process uploaded files.
<?php # file-upload-handler.php # Copyright (c) 2009 HerongYang.com. All Rights Reserved. # print "<html><body><pre>\n"; dumpFileInfo(); processFiles(); dumpRequest(); print "</pre></body></html>\n"; function dumpFileInfo() { print "\nDumping \$_FILES[] - ".count($_FILES)." entries:\n"; foreach ($_FILES as $input_name => $file_info) { print " Field name = ".$input_name."\n"; print " Error code = ".$file_info['error']."\n"; print " Temp name = ".$file_info['tmp_name']."\n"; print " File name = ".$file_info['name']."\n"; print " File size = ".$file_info['size']."\n"; print " File type = ".$file_info['type']."\n"; } } function processFiles() { print "\nProcessing uploaded files - ".count($_FILES)." entries:\n"; foreach ($_FILES as $input_name => $file_info) { print " Field name = ".$input_name."\n"; $errorCode = $file_info['error']; if ($errCode==UPLOAD_ERR_OK) { $fileName = $file_info['name']; $tempName = $file_info['tmp_name']; print " File $fileName uploaded successfully.\n"; if (is_uploaded_file($tempName)) { # remove potential risk path like: "../../*" $fileName = basename($fileName); move_uploaded_file($tempName, "/tmp/$fileName"); } else { print " Upload attack: $tempName.\n"; } } else { print " Upload failed with error code = $errorCode.\n"; } } } function dumpRequest() { print "\nDumping HTTP request:\n"; print " Request headers:\n"; foreach (getallheaders() as $name => $value) { print " $name: $value\n"; } print " \$_POST[] entries:\n"; foreach ($_POST as $name => $value) { print " $name: $value\n"; } print " Request body:\n"; $fh = fopen("php://input", "r"); rewind($fh); $req = fread($fh, 4096); fclose($fh); print "$req\n"; } ?>
Put the PHP script file, file-upload-handler.php, to the Apache Web server in the same place as file-upload-form.html. Then open the form again with a Web browser using http://localhost/file-upload-form.html.
Click "Choose File" buttons to select two different files, Hello.php and dot.gif.
Click "Upload" button to submit the form. The file-upload-handler.php script will be called to process uploaded files and display the following:
Dumping $_FILES[] - 2 entries: Field name = file_one Error code = 0 Temp name = /private/var/tmp/phpHfgiwZ File name = Hello.php File size = 29 File type = text/php Field name = file_two Error code = 0 Temp name = /private/var/tmp/phpSXU4AT File name = dot.gif File size = 43 File type = image/gif Processing uploaded files - 2 entries: Field name = file_one File Hello.php uploaded successfully. Field name = file_two File dot.gif uploaded successfully. Dumping HTTP request: Request headers: Host: localhost Content-Type: multipart/form-data; boundary=----WebKitFormBoundary... Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip, deflate Connection: keep-alive Upgrade-Insecure-Requests: 1 Origin: http://localhost User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) ... Referer: http://localhost/local/file-upload-form.html Content-Length: 496 Accept-Language: en-us $_POST[] entries: submit: Upload Request body:
If you really want to see how the HTTP POST request body looks like, you can open the browser's developer console and open the request body on the "Network" tab.
------WebKitFormBoundary3nhoB7aVAMQTQVI7 Content-Disposition: form-data; name="file_one"; filename="Hello.php" Content-Type: text/php ------WebKitFormBoundary3nhoB7aVAMQTQVI7 Content-Disposition: form-data; name="file_two"; filename="dot.gif" Content-Type: image/gif ------WebKitFormBoundary3nhoB7aVAMQTQVI7 Content-Disposition: form-data; name="submit" Upload ------WebKitFormBoundary3nhoB7aVAMQTQVI7--
For some reason, the actually content of each uploaded file is still not included in the Safari browser.
Table of Contents
Introduction and Installation of PHP
PHP Data Types and Data Literals
Variables, References, and Constants
Expressions, Operations and Type Conversions
Conditional Statements - "if" and "switch"
Loop Statements - "while", "for", and "do ... while"
Function Declaration, Arguments, and Return Values
Interface with Operating System
Introduction of Class and Object
Integrating PHP with Apache Web Server
Retrieving Information from HTTP Requests
Creating and Managing Sessions in PHP Scripts
Sending and Receiving Cookies in PHP Scripts
Controlling HTTP Response Header Lines in PHP Scripts
MySQL Server Connection and Access Functions
Functions to Manage Directories, Files and Images
SOAP Extension Function and Calling Web Services
SOAP Server Functions and Examples
Localization Overview of Web Applications
Using Non-ASCII Characters in HTML Documents
Using Non-ASCII Characters as PHP Script String Literals
Receiving Non-ASCII Characters from Input Forms
"mbstring" Extension and Non-ASCII Encoding Management
Managing Non-ASCII Character Strings with MySQL Servers
Parsing and Managing HTML Documents
Configuring and Sending Out Emails
Managing PHP Engine and Modules on macOS