Entry
How can I let a user upload a file to the server in PHP?
Jun 6th, 2002 12:39
Brandon Tallent, PJ, Heiko Schneider, Nathan Wallace, Onno Benschop,
The temporary file created by the upload only lasts until the script has
ended, so you need to copy the file somewhere.
if ($userfile<>"none") {
if(!copy($userfile,"/choose/your/path/$userfile_name")) {
print "File failed to upload";
}
else {
print "File uploaded";
}
}
You can also access the uploaded file through $HTTP_POST_FILES/$_FILES
array when track_vars is enabled in php.ini. For PHP 4.1.0 or later,
$_FILES may be used instead of $HTTP_POST_FILES.
if (!empty($_FILES['userfile']['name'])) {
if(!move_uploaded_file($_FILES['userfile']
['tmp_name'],"/choose/your/path/$_FILES['userfile']['name']")) {
print "File failed to upload";
}
else {
print "File uploaded";
}
}
The ENCTYPE parameter is required in your HTML to have the files
actually upload.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000"> (2MByte)
Upload:<br>
<input type="file" name="userfile"><br>
<input type="submit">
</form>
Also when you upload a file, other variables associated with
the uploaded file name are created automagically:
$something = File Name of temp-file (none=file not uploaded!)
$something_name = Original File Name
$something_size = Original File Size
$something_type = Original File Type (MIME-Type, like .zip, .doc, ...)
Additionally, with PHP 4.1.0 and later, the above variables are also
available in these variables:
$_FILE['something']['name'] = Original File Name
$_FILE['something']['tmp_name'] = File Name of temp-file
$_FILE['something']['size'] = Original File Size
$_FILE['something']['type'] = Original File Type