index.php
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="photo" />
<input type="submit" name="submit" value="Upload Image" />
</form>
<?php
$file_dir = "uploads";
/* Check if folder not exists, then create it */
if (!file_exists($file_dir)) {
mkdir($file_dir, 0777, true);
}
if (isset($_POST["submit"])) {
$file_name = $_FILES['photo']['name'];
$file_size = $_FILES['photo']['size'];
$file_tmp = $_FILES['photo']['tmp_name'];
$file_error = $_FILES['photo']['error'];
$file_type = $_FILES['photo']['type'];
/* check if files error = 0 [there are file uploaded] */
if ($file_error === UPLOAD_ERR_OK) {
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
$file_secure = array('image/gif', 'image/pgif', 'image/png', 'image/ppng', 'image/jpeg', 'image/pjpeg', 'image/jpg');
$errors = [];
/* Check if file already exists */
if (file_exists($file_target)) {
$errors[] = "Sorry, <strong>{$file_name}</strong> already exists.";
}
/* Check file size */
if ($file_size == 0) {
$errors[] = "Sorry, <strong>{$file_name}</strong> = {$file_size}";
}
/* Check current file formats with file secure */
if (in_array($file_type, $file_secure) === false) {
$errors[] = "Sorry, <strong>{$file_current}</strong> type not allowed";
}
/* Check if image file is a actual image or fake image ['mime'] */
if (getimagesize($file_tmp) == false) {
$errors[] = "Sorry, <strong>{$file_name}</strong> is not an image.";
}
/* Check for Error */
if (!empty($errors)) {
/* Check errors and display them */
foreach ($errors as $key => $value) {
echo "$key = $value <br />";
}
echo "<br />";
echo "<strong>{$file_name}</strong> could not uploaded. <hr />";
/* if everything is ok, try to upload file */
} else {
if (move_uploaded_file($file_tmp, $file_target)) {
echo "<strong>{$file_name}</strong> successfully copied.";
/* update file_target into database */
$query = "UPDATE {$tbl_name} SET photo={$file_target} WHERE ID={$ID} ";
if (!mysql_query($query)) {
die('Error: ' . mysql_error());
mysql_close();
} else {
echo "<strong>{$file_name}</strong> has been save into database.";
}
} else {
echo "Sorry, <strong>{$file_name}</strong> UNsuccessfully copied.";
}
}
/* check if files error = 4 [there are NOT file uploaded] */
} else { /* UPLOAD_ERR_NO_FILE */
echo "No file was uploaded";
}
}
?>