Nevertheless, it has been decided to keep this tutorial available until such time as it has been either updated or re-written. In the meantime, if you wish to take the tutorial, then it is recommended that you change the mysql-extension code to use mysqli or PDO. (If you do this successfully then perhaps you might consider submitting a revised tutorial, contributing to dream.in.code and earning some Kudos!)
There have been a lot of posts in the PHP forum regarding how to upload files to a server and put them into a database. A lot of people were trying to put the entire binary file into the database, which was the incorrect way to do things. This tutorial is an attempt to explain how to properly upload images to your website, and store their records in the database using PHP and MySQL.
Please note that this tutorial has a lot of code. The code is well commented and will explain much of what we're trying to do. I'll give an overview in the tutorial, but you need to dig into the code to really understand how things work. Also, please note that this tutorial assumes you know some basics of PHP and MySQL and dont' have any problems writing and reading to and from a database.
The first thing we'll do is build a database. I have created a simple database named 'people', which will hold first and last names of people, as well as a picture of them. You can copy and paste this SQL statement into phpMyAdmin to build your table.
CREATE TABLE `people` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `fname` VARCHAR( 30 ) NOT NULL , `lname` VARCHAR( 40 ) NOT NULL , `filename` VARCHAR( 50 ) NOT NULL ) ENGINE = MYISAM ;
Next, we will build our directory structure. We have our root folder which will hold all our directories, as well as our PHP files. Within this root directory we have a directory named 'images' and another named 'includes'. When we finish we will have a structure that looks like this
root-directory/images.php root-directory/index.php root-directory/upload.php root-directory/images/ root-directory/includes/conn.php
Within the includes/conn.php file, you should paste this code:
<?php
// Input your information for the database here
// Host name
$host = "localhost";
// Database username
$username = "username";
// Database password
$password = "password";
// Name of database
$database = "db_name";
$conn = mysql_connect($host, $username, $password) or die ("Could not connect");
$db = mysql_select_db($database, $conn) or die ("Could not select DB");
?>
On any page that connects to the database, you will require() this file. Be sure to save that file as conn.php within the includes folder.
Next we build our index file. For us, this will just be a form with three fields. One will be 'fname', one will be 'lname', and the next will be a file upload named 'image'. Please note I did some basic CSS styling, but if you don't want to style it that's fine.
<?php
// Start a session for displaying any form errors
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dream in code tutorial</title>
<style type="text/css">
label
{
float: left;
text-align: right;
margin-right: 10px;
width: 100px;
color: black;
}
#submit
{
float: left;
margin-top: 5px;
position: relative;
left: 110px;
}
#error
{
color: red;
font-weight: bold;
font-size: 16pt;
}
</style>
</head>
<body>
<div>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>First Name</label>
<input type="text" name="fname" /><br />
<label>Last Name</label>
<input type="text" name="lname" /><br />
<label>Upload Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
</form>
</div>
</body>
</html>
Make sure you notice that we are starting a session at the very top of the page. This will be handy for reporting any errors we have with the form. In addition, we have some code before the form to display any errors that are encountered. After displaying the error message we unset the error session variable.
Another thing to note is the MAX_FILE_SIZE. This can be used to ensure that the filesize of the file uploaded is less than that variable. I've left you on your own to write that portion of the script, but I promise you it is not hard.
Save that file as index.html in your root directory.
Now comes the important part. Here is the entire source file with comments. I will briefly go over how it works, but the details are within the source code:
<?php
// Start a session for error reporting
session_start();
// Call our connection file
require("includes/conn.php");
// Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
// Just a short function that prints out the contents of an array in a manner that's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
// Set some constants
// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "images/";
// Get our POSTed variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$image = $_FILES['image'];
// Sanitize our inputs
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname);
$image['name'] = mysql_real_escape_string($image['name']);
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH .= $image['name'];
// Make sure all the fields from the form have inputs
if ( $fname == "" || $lname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (fname, lname, filename) values ('$fname', '$lname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: images.php");
exit;
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: index.php");
exit;
}
?>
Alright, so we start out by starting a session and requiring our conn.php file. Nothing new there.
Next, we have a function that checks to see if the upload file is of a valid type. This function helps deter people from uploading exe files, as well as other potentially harmful stuff you don't want on your server. We have a variable that holds all the valid MIME types. That list is by no means exhaustive, but it works for our purposes. For a full list of MIME types check out the Webmaster Tookit's list
The next function is just something I use for debugging. This prints the contents of an array so that it's readable.
We create a constant variable that will hold our target path. I didn't use the define() function, but I could have.
Next block of code checks to make sure none of the fields were blank. This is just very basic form validation and can be adjusted for what you see fit.
The next block makes a call to the is_valid_type function and checks to make sure that the file is valid.
The next block of code checks to see if a file of that name already exists, in an effort to keep people from overwriting files. A good way to ensure a unique filename is to parse out the name part of the file name before the period, append a timestamp, and then hash it. After hashing it, add the extension back on. I'm attempting to keep this tutorial simple, so I did not show that, but you should be able to figure that out. Just use substrings.
Finally, we attempt to move the uploaded file to the new directory. Make sure the new directory has proper write permissions, or your script won't be able to save.
If moving the file was successful, we input the information into the database. Make sure you notice that we do not input the binary file into the database. What we have done is moved the file to a directory where we can access it, and then stored the images file name into the database. Whenever we want to print out the image we get its file name from the database and then build the img tag.
Lastly, we have our images.php page, which will display all those great images you've uploaded.
<?php
// Get our database connector
require("includes/conn.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dream in code tutorial - List of Images</title>
</head>
<body>
<div>
<?php
// Grab the data from our people table
$sql = "select * from people";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<div class=\"picture\">";
echo "<p>";
// Note that we are building our src string using the filename from the database
echo "<img src=\"images/" . $row['filename'] . "\" alt=\"\" /><br />";
echo $row['fname'] . " " . $row['lname'] . "<br />";
echo "</p>";
echo "</div>";
}
?>
</div>
</body>
</html>
There's really nothing there that you shouldn't be able to understand.
Well, that's all I have for you! Now you know how to properly upload images to a website and store their references into the database. You get two thumbs up
If you've found this tutorial useful, or if you have any comments let me know! Good luck!
This post has been edited by andrewsw: 01 February 2015 - 05:16 AM

New Topic/Question
This topic is locked




MultiQuote






|