Upload filesExample
First build a form <code><span><<span>html</span>></span><span><<span>body</span>></span><span><<span>form</span><span>action</span>=<span>"upload.php"</span><span>method</span>=<span>"post"</span><span>enctype</span>=<span>"multipart/form-data"</span>></span><span><<span>input</span><span>type</span>=<span>"file"</span><span>name</span>=<span>"file"</span>/></span><span><<span>input</span><span>type</span>=<span>"submit"</span><span>value</span>=<span>"submit"</span><span>name</span>=<span>"submit"</span>></span><span></<span>form</span>></span><span></<span>body</span>></span><span></<span>html</span>></span></code>
. In the form, after submission, it will be handed over to upload.php
for processing. Let’s write the simplest upload handler:
<code><span><?php</span> var_dump(<span>$_POST</span>); var_dump(<span>$_FILES</span>); <span>$uploadPath</span> = <span>'./upload/'</span>; <span>$tempFileName</span> = <span>$_FILES</span>[<span>'file'</span>][<span>'tmp_name'</span>]; <span>$uploadFileName</span> = <span>$uploadPath</span>.<span>$_FILES</span>[<span>'file'</span>][<span>'name'</span>]; <span>if</span>(move_uploaded_file(<span>$tempFileName</span>,<span>$uploadFileName</span>)){ <span>echo</span><span>'upload success'</span>; }<span>else</span>{ <span>echo</span><span>'upload fail'</span>; }</code>
Visit the submission page and submit the form. You can see the following output:
<code><span>array</span> (size=<span>1</span>) <span>'submit'</span> => string <span>'submit'</span> (length=<span>6</span>) <span>array</span> (size=<span>1</span>) <span>'file'</span> => <span>array</span> (size=<span>5</span>) <span>'name'</span> => string <span>'laravel-quickstart-welcome.png'</span> (length=<span>30</span>) <span>'type'</span> => string <span>'image/png'</span> (length=<span>9</span>) <span>'tmp_name'</span> => string <span>'/tmp/phpYKQKaY'</span> (length=<span>14</span>) <span>'error'</span> => int <span>0</span><span>'size'</span> => int <span>91148</span> upload success</span></code>
The output illustrates two points: The content submitted by the input type=file will appear in the
$_FILES field as its
index in the
$_FILESarray. The content submitted by input with
type=file will continue to appear in the $_POST
type
tmp_name, it will be stored in the temporary directory first. tmp_name displays the path of the temporary file
error
size, in bytes
So PHP $_FILES array. You can verify the file as needed (such as the suffix name), and then use the move_uploaded_file function to copy the temporary file Go to your upload directory. Notes
from form must set the
enctype="multipart/form-data"
The folder in the upload path must exist, otherwise an error will be reported<code>failed to open stream: No such file or directory </code>
If necessary, you can use
If the file corresponding to the path of the second parameter of
move_uploaded_file
Reference: PHP file upload