Hey guys i was just wondering, how do you use PHP to upload a file directly to your website?
for example:
Person uses a browse button to look for file to upload, then once selected file directory comes up in a textbox and when they click and "upload" button it uploads to a directory on the website named "uploads".
Could someone tell me how to do this and maybe explain a little about or link me to a resource which will help me?
Thanks.
Everything is explained in the Handling file uploads section in the PHP manual.
I'd recommend to avoid using the MAX_FILE_SIZE hidden field since it's not part of any standard, there is no known browsers support and it's easy to modify it's value to affect PHP behavior on the server side.
You should use an HTML form with
enctype
set tomultipart/form-data
like:Then in PHP you can check
$_FILES['thefile']
to get the information you want. The file will be in$_FILES['thefile']['tmpname']
and you can move it from there to your uploaded file to the correct folder usingmove_uploaded_file()
:Of course you'll want to do additional sanity checks to make sure that you're not overwriting an exisiing file and the file was uploaded successfully without error.
Have a form and put an file input in it:
Then in
my_php_script.php
, handle the file upload just like any other POST request. See this page for details on the backend: http://www.tizag.com/phpT/fileupload.phpThe
$_FILES
array holds data pertaining to the uploaded file.$_FILES['uploadedfile']['name']
- the original path of the user uploaded file.$_FILES['uploadedfile']['tmp_name']
- the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.You should move the file from the temporary directory to more permanent storage (like an
uploads/
folder). You can do this using themove_uploaded_file()
function like so:Make sure you specify
multipart/form-data
in the form element, then include file fields. You'll need to do some additional work on the receiving end to get the file data and store it with an appropriate name, instead of a default/temporary directory on the server.