Consider the following PHP script that processes a file upload. What will be the output if a file named example.txt of size 1024 bytes is uploaded successfully?
<?php if ($_FILES['upload']['error'] === UPLOAD_ERR_OK) { echo "File name: " . $_FILES['upload']['name'] . "\n"; echo "File size: " . $_FILES['upload']['size'] . " bytes\n"; } else { echo "Upload failed with error code: " . $_FILES['upload']['error']; } ?>
Check the error value in $_FILES to confirm if the upload was successful.
If the file uploads without errors, $_FILES['upload']['error'] equals UPLOAD_ERR_OK (0). Then the script prints the file name and size.
When a file is uploaded via a form in PHP, which key in the $_FILES array contains the temporary file path on the server?
The temporary file path is where PHP stores the uploaded file before you move it.
The tmp_name key holds the temporary filename of the file stored on the server during upload.
Examine the code below. It tries to move an uploaded file but fails. What is the cause?
<?php if (move_uploaded_file($_FILES['file']['name'], '/uploads/' . $_FILES['file']['name'])) { echo "Upload successful."; } else { echo "Upload failed."; } ?>
Check the first argument of move_uploaded_file. It must be the temporary file path.
The first argument to move_uploaded_file must be the temporary file path stored in tmp_name, not the original file name.
Consider this PHP snippet:
<?php $file = $_FILES['upload']; echo $file['name']; echo $file['tmpname']; ?>
What error will this code produce?
Check the spelling of the keys in the $_FILES array.
The key tmpname is incorrect; the correct key is tmp_name. This causes a notice about undefined index.
Given the following HTML and PHP code, how many files will be processed in the PHP script?
<form method="post" enctype="multipart/form-data">
<input type="file" name="photos[]" multiple>
<input type="submit">
</form>
<?php
if (!empty($_FILES['photos'])) {
echo count($_FILES['photos']['name']);
} else {
echo 0;
}
?>Check how multiple file inputs are handled in $_FILES.
When using name="photos[]" with multiple, $_FILES['photos']['name'] is an array of all selected file names. The count reflects how many files were selected.