<!DOCTYPE html>
<html>
<head>
<title>PHP File Upload</title>
<style type="text/css">
.cus_form{ padding:4px 10px; border-radius:2px; border:1px solid #0099da;}
.lable{ color:#000; font-size:16px; font-weight:bold; font-style:italic;}
.cus_btn{ background:#0099da; padding:6px 15px; margin:10px 70px; color:#FFF; }
.cus_btn:hover{ background:#069;}
</style>
</head>
<body>
<form action="php_upload_file.php" method="post" enctype="multipart/form-data">
<h3>PHP File Upload</h3>
<p><span style="color:#F00;"><strong>Note :</strong></span> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
<label class="lable">Filename:</label>
<input type="file" name="photo" id="fileSelect" class="cus_form"><br />
<input type="submit" name="submit" class="cus_btn" value="UPLOAD">
</form>
</body>
</html>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: Your File size is too large");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: Your uploading your file is problem. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
Once the form is submitted information about the uploaded file can be accessed via PHP superglobal array called $_FILES
. For example, our upload form contains a file select field called photo (i.e. name="photo"
), if any user uploaded a file using this field, we can obtains its details like the name, type, size, temporary name or any error occurred while attempting the upload via the $_FILES["photo"]
associative array, like this:
$_FILES['photo']['name']
: It returns file name.$_FILES['photo']['type']
: It returns MIME type of the file.$_FILES['photo']['size']
: It returns size of the file (in bytes).$_FILES['photo']['tmp_name']
: It returns temporary file name of the file which was stored on the server.$_FILES['photo']['error']
: It returns error code associated with this file.