Php saving uploaded file
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:
Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
Anyways, here is a fuller example than the sparce one in the documentation above:
foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;
$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);
if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>
Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.
The following example form breaks their codes:
As the solution, you should use PSR-7 based zendframework/zend-diactoros.
use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;
$request = ServerRequestFactory :: fromGlobals ();
if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>
$uploaded_files = $request -> getUploadedFiles ();
if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>
$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];
if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>
$file -> moveTo ( ‘/path/to/new/file’ );
The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.
Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
Multi-files with HTML array feature —
Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.
function normalize_files_array ( $files = [])
foreach( $files as $index => $file )
if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>
foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>
?>
The following is the output from the above method.
Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
Php saving uploaded file
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 .
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:
Upload File Using PHP and Save in Directory
Uploading file is one of the most common feature which we normally use in our daily life, we do upload pictures on Facebook, Twitter and other websites. So today I will share a tutorial about how to upload file using PHP and save/store that file in your web server directory.
HTML Form
We will need a form with one input field with file type. The action tag of form should point to the URL of PHP script file which actually perform the uploading task. It is also important to add enctype=”multipart/form-data” property in your form to upload file otherwise your file will not be uploaded.
PHP Script
As you can see above I tried to use the variable name as its function so that you can easily understand what I am doing, I just check that if file already exist it will print the error otherwise file will be uploaded.
This tutorial is only for the basic learning purpose, if you want to implement it on your website so it is better to use more validation before uploading file.
//you can easily get the following information about file: $_FILES['file_name']['name'] $_FILES['file_name']['tmp_name'] $_FILES['file_name']['size'] $_FILES['file_name']['type']
Validation such as file type (extension) or file size can also be check on the client side I also wrote tutorial Check File Size & Extension Before Uploading Using jQuery.
If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.