PHP Image Upload


INDEX.PHP
<html>








UPLOAD.PHP
<?php
$image_dir = "/img/";
$filename = basename($_FILES['file']['name']);
$filesize = $_FILES['file']['size'];
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
$dir = getcwd();
$target_dir = $dir . $image_dir;
$target_file = $target_dir . $filename;
$upload = 1;
if (isset($_POST['submit'])) {
$check = getimagesize($_FILES['file']['tmp_name']);
if ($check != false) {
echo "File is an image - " . $check['mime'] . ".";
$upload = 1;
} else {
echo "File is not an image";
$upload = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, File exist already.";
$upload = 0;
}
if ($filesize > 500000) {
echo "Sorry, your Uploaded File is too large - " . $filesize . "byte.";
$upload = 0;
}
if ($filetype != "jpg" && $filetype != "gif" && $filetype != "png" && $filetype != "jpeg") {
echo "Sorry, only JPG, JPEG, GIF and PNG files are allowed";
$upload = 0;
}
if ($upload != 1) {
echo "<br />";
echo "Sorry, your file cannot be uploaded";
} else {
echo "<br />";
echo "Your Upload can still be accomplished";
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
echo "<br />";
echo "File has been uploaded into the image folder successfully";
} else {
echo "<br />";
echo "Upload Failed";
}
}
?>
These are the sample scripts used in the Video Above. I hope this starts your journey into having fun with image uploads with PHP.

Our Next Tutorial will bring you more updates we can do to this script and how we can actually use them in the real world.