code for upload image in php – How to Upload Files on Server in PHP?

code for upload image in php – How to Upload Image into Database and Display it using PHP?

code for upload image in php

PHP file upload Script :: code for upload image in php, online picture upload & Check the file if it is allowed for upload or not. We can check for file size, file extension, file name etc.

Step 1: Creating an HTML form to upload the file

[php]




File Upload Form

Upload File



Note: Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.



[/php]

Don’t Miss : how to fetch image from database in php?

Step 2: Processing the uploaded file

complete code of our “do_upload_file.php” file.
[php]
“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.”);

$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die(“Error: File size is larger than the allowed limit.”);

if(in_array($filetype, $allowed)){
if(file_exists(“upload/” . $filename)){
echo $filename . ” is already exists.”;
} else{
move_uploaded_file($_FILES[“photo”][“tmp_name”], “upload/” . $filename);
echo “Your file was uploaded successfully.”;
}
} else{
echo “Error: There was a problem uploading your file. Please try again.”;
}
} else{
echo “Error: ” . $_FILES[“photo”][“error”];
}
}
?>
[/php]

Leave a Comment