Processing uploaded files php

Processing uploaded files php

Now let’s say we find that the error code given by the PHP engine is UPLOAD_ERR_OK and we want to save the uploaded file on the file system without concerning what the uploaded file contains. We can use the move_uploaded_file() function to move the temporary file to the location we wanted. For example:

If everything works fine, the temporary file is moved to «/upload_files/myFile.txt» and the move_uploaded_file() function returns true . PHP will overwrite the original «myFile.txt» file if it exists.

Before moving a file, the move_uploaded_file() function checks if the file is really a file uploaded from the client-side using HTTP POST so as to prevent your PHP script from moving password and system files that are not supposed to be moved. If the file does not pass the check or any other errors occur, the file is not moved and the move_uploaded_file() function returns false .

3.5. Processing Contents of Uploaded Files with PHP

If you do not want to save the uploaded file directly but to process it, the PHP functions file_get_contents() and fread() can help you. The file_get_contents() function returns a string that contains all data of the uploaded file:

if (is_uploaded_file($_FILES[‘myFile’][‘tmp_name’]))
$fileData = file_get_contents($_FILES[‘myFile’][‘tmp_name’]);

The is_uploaded_file() function helps us check if a file is really a file uploaded from the client-side using HTTP POST. If yes, the is_uploaded_file() function returns true , otherwise it returns false .

Читайте также:  Php mysql utf8 connect

Make sure the file you are going to process passes the check of the is_uploaded_file() function. This is to prevent your PHP script from processing files (such as password files and system files) that are not supposed to be processed.

If everything works fine, the $fileData variable will contain the data of the uploaded file. (Otherwise it will contain the Boolean value false .) You can then perform what you like to do with the data. For example, to replace all occurrences of the «A» character in the data with the «B» character, you can write something like this:

$fileData = str_replace(«A», «B», $fileData);

If the uploaded file is large in size, you will not want to load the whole file into memory with the file_get_contents() function. The fread() function can help you in this case. It reads a number of bytes from a stream. fread() is used together with PHP functions such as fopen() , feof() , fclose() , etc. Here is an example PHP script:

if (is_uploaded_file($_FILES[‘myFile’][‘tmp_name’])) $filePointer = fopen($_FILES[‘myFile’][‘tmp_name’], «rb»);

if ($filePointer!=false) while (!feof($filePointer)) $fileData = fread($filePointer, 4096);

// Process the contents of the uploaded file here.

Before we can read the contents of the uploaded file with fread() , we have to open a stream on the file first. This is achieved using the PHP function fopen() . The fopen() function takes two parameters — a file name and a flag that controls the type of access. In the above PHP script, we specify «rb» as the flag. The «r» letter states that we want to open the uploaded file for reading and the «b» letter states that we want to open the file in binary mode. If the uploaded file is opened successfully, fopen() returns a file pointer (or it can be called a file handle), otherwise it returns false .

The PHP function feof() is used to check whether the file pointer has reached the EOF (end-of-file) character. If yes, the feof() function returns true , otherwise it returns false . In the above PHP script, we use a while loop to repeatedly check whether the end of the file has been reached. If the end of the file has not been reached, we will read the file data with fread() , otherwise we will close the file.

The PHP function fread() is used to read a certain number of bytes. It takes two parameters — a file pointer and an integer specifying the number of bytes to read. In the above PHP script, we read at most 4096 bytes of data each time. For example, if the size of the uploaded file is 5000 bytes, fread() reads 4096 bytes of data when it is called the first time and 904 bytes of data when it is called the second time. If fread() fails, it returns false .

The PHP function fclose() is used to close the file stream.

For more information, please refer to PHP’s documentation on filesystem functions.

3.6. Retrieving Values of Ordinary Form Fields with PHP

If your HTML/XHTML form contains ordinary input fields like besides , you can use the $_POST array to retrieve the form field values. The format is like this:

In the above line, value_of_name_attribute represents the name attribute value of the element. For example, we will use the PHP code below:

to retrieve the value of the input field:

Источник

Processing uploaded files php

PHP Tutorials — Herong’s Tutorial Examples — v5.17, by Herong Yang

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:

  • $_FILES[$field_name] = $file_info[] — The hash key, $field_name, is the name given the field of the web form.
  • $file_info[‘name’] — Stores the original name of the uploaded file on the client machine.
  • $file_info[‘type’] — The mime type of the uploaded file, if the browser provided this information. An example would be «image/gif». This mime type is however not checked on the PHP side and therefore don’t take its value for granted.
  • $file_info[‘size’] — The size, in bytes, of the uploaded file.
  • $file_info[‘tmp_name’] — The temporary filename of the file in which the uploaded file was stored on the server.
  • $file_info[‘error’] — The error code associated with this file upload.

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.

\n"; dumpFileInfo(); processFiles(); dumpRequest(); print "

\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.

Источник

Оцените статью