Uploading a file to the server using JavaScript and the jQuery library. Uploading files with PHP How to upload a php file
This feature allows you to upload both text and binary files. With PHP's authentication and file functions, you have full control over who is allowed to upload files and what to do with the file after it has been uploaded.
PHP is capable of receiving downloaded files from any RFC-1867 compliant browser.
Also note that PHP supports uploading files using the PUT method used by the Netscape Composer and W3C Amaya clients. For more detailed documentation, see PUT method support.
Example #1 File upload form
The page for uploading files can be implemented using a special form that looks something like this:
In the example above __URL__ should be replaced with a PHP script reference.
hidden field MAX_FILE_SIZE(value must be specified in bytes) must precede the file selection field, and its value is the maximum allowed file size in PHP. It is recommended that you always use this variable, as it prevents users from anxiously waiting when transferring huge files, only to find out that the file is too large and the transfer did not actually take place. Keep in mind that it's fairly easy to bypass this limitation on the browser side, so you shouldn't rely on this feature to block all larger files. This is mostly a convenience feature for users of the client side of your application. However PHP settings(on the server) regarding the maximum size cannot be bypassed.
Comment:
You should also make sure that the upload form has the attribute enctype="multipart/form data", otherwise the files will not be uploaded to the server.
original name file on the client's computer.
$_FILES["userfile"]["type"]The mime type of the file, in case the browser provided such information. An example is "image/gif". This mime type is not checked on the PHP side, so don't rely on its value without checking.
$_FILES["userfile"]["size"]The size in bytes of the received file.
$_FILES["userfile"]["tmp_name"]temporary name with which received file was saved on the server.
$_FILES["userfile"]["error"]At the end of the script, if the downloaded file has not been renamed or moved, it will be automatically deleted from the temporary folder.
foreach ($_FILES [ "pictures" ][ "error" ] as $key => $error ) (
if ($error == UPLOAD_ERR_OK ) (
$tmp_name = $_FILES [ "pictures" ][ "tmp_name" ][ $key ];
// basename() can save you from filesystem attacks;
// additional check/cleanup of the filename may be needed
$name = basename ($_FILES [ "pictures" ][ "name" ][ $key ]);
move_uploaded_file ($tmp_name , "data/ $name " );
}
}
?>
A file upload progress bar can be implemented using "tracking file upload progress using sessions".
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 ) (
);
}
$file -> moveTo("/path/to/new/file");
?>
10 years ago
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
=> array
=> facepalm.jpg
=> image/jpeg
=> /tmp/phpn3FmFr
=> 0
=> 15476
)
=> array
=>
=>
=>
=> 4
=>
)
and not this
array
=> array
=> facepalm.jpg
=>
)
=> array
=> image/jpeg
=>
)
=> array
=> /tmp/phpn3FmFr
=>
)
=> array
=> 0
=> 4
)
=> array
=> 15476
=> 0
)
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" ;
}
?>
3 years ago
The documentation doesn't have any details about how the HTML array feature formats the $_FILES array.
Example $_FILES array:
For single file-
array
=> array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
Multi-files with HTML array feature -
array
=> array
=> array
=> sample-file.doc
=> sample-file.doc
)
=> array
=> application/msword
=> application/msword
)
=> array
=> /tmp/path/phpVGCDAJ
=> /tmp/path/phpVGCDAJ
)
=> array
=> 0
=> 0
)
=> array
=> 0
=> 0
)
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 = ) (
$normalized_array = ;
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 ]
];
}
Return $normalized_array ;
?>
The following is the output from the above method.
array
=> array
=> array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
=> array
=> array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
=> array
=> sample-file.doc
=> application/msword
=> /tmp/path/phpVGCDAJ
=> 0
=> 0
)
4 years ago
For clarity; the reason you would NOT want to replace the example script with
$uploaddir = "./";
is because if you have no coded file constraints a nerd could upload a php script with the same name of one of your scripts in the scripts directory.
Given the right settings and permissions php-cgi is capable of replacing even php files.
Imagine if it replaced the upload post processor file itself. The next "upload" could lead to some easy exploits.
Even when replacements are not possible; uploading an .htaccess file could cause some problems, especially if it is sent after the nerd throws in a devious script to use htaccess to redirect to his upload.
There are probably more ways of exploiting it. Don't let the nerds get you.
More sensible to use a fresh directory for uploads with some form of unique naming algorithm; maybe even a cron job for sanitizing the directory so older files do not linger for too long.
10 years ago
Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients" side. You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client.This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).
2 years ago
I have found it useful to re-order the multidimensional $_FILES array into a more intuitive format, as proposed by many other developers already.
Unfortunately, most of the proposed functions are not able to re-order the $_FILES array when it has more than 1 additional dimension.
Therefore, I would like to contribute the function below, which is capable of meeting the aforementioned requirement:
function get_fixed_files()(
$function = function($files , $fixed_files = array(), $path = array()) use (& $function ) (
foreach ($files as $key => $value ) (
$temp = $path ;
$temp = $key ;
If (is_array ($value )) (
$fixed_files = $function ($value , $fixed_files , $temp );
) else (
$next = array_splice ($temp , 1 , 1 );
$temp = array_merge($temp , $next );
$new = & $fixed_files ;
Foreach ( $temp as $key ) (
$new = & $new [ $key ];
}
$new = $value ;
}
}
Return $fixed_files ;
};
Return $function($_FILES);
}
?>
Side note: the unnamed function within the function is used to avoid confusion regarding the arguments necessary for the recursion within the function, for example when viewing the function in an IDE.
The application for uploading files to the server is an HTML form (upload.html) and the upload.php script for processing it.
Comment: You can download the industrial version of the file upload system to the server from the section. The system will allow you not only to upload the file to the server, but also to change its size, background, etc.
Form code (upload.html)
File upload form