PHP Image Upload and MySQL
From w3cyberlearnings
Requirement
- MySQL Database
- Up and Running Web Server
- PHP 5
- MySQLi driver
Goal
- Upload image using HTML form
- Store image on the server
- Store image information to the MySQL database
- Display image when successful upload
- Check image size and image type
Setup
- Make sure the directory that the image is going to upload is read-writable able (chmod 755 upload_directory)
Create Database Table
CREATE TABLE my_image ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(200), size INT, type VARCHAR(200), file_path VARCHAR(200) );
upload HTML page myImage.html
<html> <head> <title>Upload File To MySQL Database</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> .myc { font-size: 12px; border: 1px solid #000000; } </style> </head> <body> <form action="upload.php" enctype="multipart/form-data" name="uploadform" method="post" > <table width="350" border="0" cellpadding="1" cellspacing="1" class="box"> <tr> <td> <input type="hidden" name="MAX_FILE_SIZE" value="2000000"> <input name="userfile" type="file" id="userfile"/> <input name="upload" type="submit" class="myc" id="upload" value="Upload"/> </td> </tr> </table> </form> </body> </html>
Upload path, file size, and image type
- Upload path need to be the full path in your server
- Display path is just the URL path, and it does not need to be a full path
- Defined the image size:2000000
- Image extension: jpeg, pjpeg, png, and gif
define('UPLOAD_PATH', $_SERVER['DOCUMENT_ROOT'] . '/eshop_images/'); define('DISPLAY_PATH', '/eshop_images/'); define('MAX_FILE_SIZE', 2000000); $permitted = array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif');
Rename file randomly
- Get the image extension
- Generate a random name
// get the file extension $ext = substr(strrchr($fileName, "."), 1); // generate the random file name $randName = md5(rand() * time()); // image name with extension $myfile = $randName . '.' . $ext;
check image information
- Check for valid image type.
- Check file size.
if (in_array($fileType, $permitted) && $fileSize > 0 && $fileSize <= MAX_FILE_SIZE) { }
upload image to the server
- Upload image to the server
- If upload is failed, exit and display error.
- $tmpName is the temporary file
- $path is the full path of the file (MUST be full path).
$result = move_uploaded_file($tmpName, $path); if (!$result) { echo "Error uploading image file"; exit; }
Connect to the MySQL server using mysqli
- Connect to the MySQL Database.
- Check if the connection is failed than the display error message.
$db = new mysqli("localhost", "root", "caojiang", "upload_db"); if (mysqli_connect_errno()) { printf("Connect failed: %s<br/>", mysqli_connect_error()); }
Insert image information into the MySQL database
$query = "INSERT INTO my_image(name, size, type, file_path) VALUES(?,?,?,?)"; $conn = $db->prepare($query); if ($conn == TRUE) { $conn->bind_param("siss", $myfile, $fileSize, $fileType, $path); if (!$conn->execute()) { echo 'error insert'; } else { echo 'Success!<br/>'; echo '<img src="' . DISPLAY_PATH . $myfile . '"/>'; } } else { die("Error preparing Statement"); }
upload.php
<?php define('UPLOAD_PATH', $_SERVER['DOCUMENT_ROOT'] . '/eshop_images/'); define('DISPLAY_PATH', '/eshop_images/'); define('MAX_FILE_SIZE', 2000000); $permitted = array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'); if (isset($_POST['upload'])) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; // get the file extension $ext = substr(strrchr($fileName, "."), 1); // generate the random file name $randName = md5(rand() * time()); // image name with extension $myfile = $randName . '.' . $ext; // save image path $path = UPLOAD_PATH . $myfile; if (in_array($fileType, $permitted) && $fileSize > 0 && $fileSize <= MAX_FILE_SIZE) { //store image to the upload directory $result = move_uploaded_file($tmpName, $path); if (!$result) { echo "Error uploading image file"; exit; } else { $db = new mysqli("localhost", "root", "caojiang", "upload_db"); if (mysqli_connect_errno()) { printf("Connect failed: %s<br/>", mysqli_connect_error()); } $query = "INSERT INTO my_image(name, size, type, file_path) VALUES(?,?,?,?)"; $conn = $db->prepare($query); if ($conn == TRUE) { $conn->bind_param("siss", $myfile, $fileSize, $fileType, $path); if (!$conn->execute()) { echo 'error insert'; } else { echo 'Success!<br/>'; echo '<img src="' . DISPLAY_PATH . $myfile . '"/>'; } } else { die("Error preparing Statement"); } } } else { echo 'error upload file'; } } else { echo 'error'; } ?>
Related Links
HTML Form
- PHP Login Form
- PHP Feedback Form
- PHP Register Form
- PHP Search Form
- PHP Image Upload and MySQL
- PHP Multiple Forms
- PHP Generate Form by Ajax