Skip to content

Instantly share code, notes, and snippets.

@Longwater1234
Last active February 14, 2021 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Longwater1234/c5d278633409e0aa317b93d82b02618c to your computer and use it in GitHub Desktop.
Save Longwater1234/c5d278633409e0aa317b93d82b02618c to your computer and use it in GitHub Desktop.
PHP IMAGE file upload using MYSQLi
<?php
//this simple example uses MYSQLi to upload an PHOTO file to an SQL database.
//modify the HTML part as you wish to make it prettier OR ADD MORE inputs fields.
/* USE this for PHOTO uploads ONLY. WON'T work with PDF, DOC etc. */
// ALSO, do not ignore escaping strings or using PREpared statements for security.
mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$conn = mysqli_connect( $HOSTNAME, $DB_USERNAME, $DB_PASSWORD, "_YOUR_DB_NAME_HERE" );
if ( mysqli_connect_errno() ) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UPLOAD Page</title>
</head>
<body>
<h1> Add New Product</h1>
<!-- assume we have simple form to collect image uploads from Admin -->
<form action="" method="post" enctype="multipart/form-data">
<div align="center">
<label>Product Title</label>
<input type="text" name="productname" size="30" required/>
<br>
<label>Image (max file size: 2 MB) </label>
<input type=hidden name=MAX_FILE_SIZE value=2000000 >
<!--this line ^ above is useful in setting UPLOAD size LIMIT. Edit value (in bytes) as you wish.-->
<input type="file" name="product_image" accept=".jpg, .jpeg, .png" required>
</div>
<div align="center">
<button name="insert" type="submit">INSERT PRODUCT</button>
</div>
</form>
</body>
</html>
<?php
global $conn;
if (isset($_POST['insert'])) {
$productname = mysqli_real_escape_string($conn, $_POST['productname']);
$productname = htmlspecialchars(stripslashes(trim($productname)));
/*---------FROM here below BEGIN image upload code-------*/
$fileName = $_FILES['product_image']['name'];
$filetype = $_FILES['product_image']['type'];
$fileTemp = $_FILES['product_image']['tmp_name'];
$fileSize = $_FILES['product_image']['size'];
$uploadError = $_FILES['product_image']['error'];
// here above we have declared some necessary variables.
if ($uploadError != 0) {
if ($uploadError == 2) echo ("Sorry, your file size exceeds limit. \n");
exit("Upload failed.");
}
// Check if file is an actual image/photo file. VERY INTELLIGENT & ACCURATE.
/* USE this for PHOTO uploads ONLY. WON'T work with PDF, DOC etc. */
if (exif_imagetype($fileTemp) != IMAGETYPE_JPEG && exif_imagetype($fileTemp) != IMAGETYPE_PNG) {
exit("Invalid file type. Upload failed.");
}
//CHECKS file type by simply reading the file extension. QUICK, BUT NOT RECOMMENDED.
// This Can be fooled easily if User modifies file extension before upload.
if ($filetype != "image/jpeg" && $filetype != "image/png") {
exit("Invalid file type. Upload failed.");
}
// folder where images will be saved (on your server.)
$target_dir = "../uploads/";
$target_file = $target_dir . basename($fileName);
//check if file exists
if (file_exists($target_file)) {
exit("Sorry, File already exists. Upload failed.");
}
// check file size
if ($fileSize > 2000000) {
// In bytes. Adjust the amount as you wish
exit("Sorry, file size is over 2MB. Upload failed");
} else {
// everything is OK. Can now proceed to save + upload the file.
// FIRST, remove all special chars and spaces in fileName using REGEX
$pattern = "/[^a-zA-Z0-9_]+/";
$newFileName = preg_replace($pattern, "", basename(strtolower(($fileName))));
// THEN, move file to final destination (in your server)
move_uploaded_file($fileTemp, "../uploads/$newFileName") or die("Upload failed");
/*--------------^^^ END of image upload code here above-----------*/
// FINALLY INSERT everything you got into your database:
// PLEASE USE PREPARED STATEMENTS FOR EXTRA SAFETY
// (MODIFY THIS QUERY to accordingly)
$insert_product = "INSERT INTO `products`(`productname`, `product_image`) VALUES ( ?, ?)";
//proceed with prepared statements...
if (mysqli_query($conn, $insert_product)) {
echo "<script>alert('Product added successfully!')</script>";
echo "<script>window.open('uploadfile.php','_self')</script>";
} else
echo "Database Error: \n " . mysqli_error($conn);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment