File Upload
File Upload
• $fileName = $_FILES["fileUpload"]["name"];
• Description: This retrieves the original name of the
file that the user uploaded from their computer.
• Example: If the user uploads a file named
document.pdf, then $fileName will contain the
value "document.pdf".
• Use Case: You can use this to show the original file
name to the user or store it in a database for
reference.
$fileTmpName = $_FILES["fileUpload"]
["tmp_name"];
• Description: This gets the temporary file name
and path that the server uses to store the
uploaded file before you move it to a
permanent location.
• Example: The value might look something like
"/tmp/phpYzdqkD", which is a temporary path
where the file is stored.
• Use Case: You will typically use this with
move_uploaded_file() to move
$fileSize = $_FILES["fileUpload"]["size"];
• Description: This gives the size of the
uploaded file in bytes.
• Example: If a file is 2MB, then $fileSize might
have the value 2097152 (because 2MB = 2 *
1024 * 1024 bytes).
• Use Case: You can use this to check if the
uploaded file exceeds a certain size limit and
reject it if it's too large
$fileType = $_FILES["fileUpload"]["type"];
</body>
</html>
Upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
• You will need to create a new directory called
"uploads" in the directory where "upload.php"
file resides. The uploaded files will be saved
there.
Check if File Already Exist
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
• Limit File Size
$target_dir = "uploads/";
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
$uploadOk = 1;
} else {
•
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}