• (3 Pages)
  • +
  • 1
  • 2
  • 3

Uploading Images with PHP Build the next Flickr! (DICr???) Rate Topic: ***** 7 Votes

#1 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Post icon  Posted 10 December 2008 - 12:41 PM

*
POPULAR

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!

Is This A Good Question/Topic? 12
  • +

Replies To: Uploading Images with PHP

#2 Moonbat  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 36
  • View blog
  • Posts: 424
  • Joined: 30-June 08

Posted 16 December 2008 - 07:12 PM

I'm glad you brought up the whole "references" thing. I can't beleive how many people have thought of trying to store the image itself in the DB. This'll be a great help for newbies (hey, it was for me! :D)
Was This Post Helpful? 0
  • +
  • -

#3 Robsphp  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 10-January 09

Posted 10 January 2009 - 05:13 PM

akozlik

THANK YOU, I am trying to add to my members database an option to have there own avi file then grab it out of the database and display it.

Would I use the same idea (upload the avi's into a directory then reference them in the users table) ?

regards

Rob
Was This Post Helpful? 0
  • +
  • -

#4 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 10 January 2009 - 06:56 PM

View PostRobsphp, on 10 Jan, 2009 - 07:13 PM, said:

akozlik

THANK YOU, I am trying to add to my members database an option to have there own avi file then grab it out of the database and display it.

Would I use the same idea (upload the avi's into a directory then reference them in the users table) ?

regards

Rob



Yeah the idea's the same. I'm not sure how to best handle partially streamed videos or anything like that, but you can get the party started by using the same idea.

Hope that helps.
Was This Post Helpful? 0
  • +
  • -

#5 Robsphp  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 10-January 09

Posted 11 January 2009 - 02:07 PM

Akozlik

I get the following error ?

Warning: Cannot modify header information - headers already sent by (output started at /public_html/test/includes/conn.php:10) in /public_html/test/upload.php on line 81

When i try the images.php it seems to have worked but I get that error when upload.php is used ????

Rob
Was This Post Helpful? 0
  • +
  • -

#6 teampoop  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 140
  • Joined: 19-June 08

Posted 11 January 2009 - 10:49 PM

You have to have your header() calls before you do any output to the browser. So if your code has an echo (or print) before your header call, you will get an error. This is probably why there was a session variable set, to pass the information to the redirected page.

ex:
<?php
echo "checking for stuff";
header("Location: index.php"); // ERROR ensues
?>



Hope this helps.

View PostRobsphp, on 11 Jan, 2009 - 01:07 PM, said:

Akozlik

I get the following error ?

Warning: Cannot modify header information - headers already sent by (output started at /public_html/test/includes/conn.php:10) in /public_html/test/upload.php on line 81

When i try the images.php it seems to have worked but I get that error when upload.php is used ????

Rob

Was This Post Helpful? 0
  • +
  • -

#7 Robsphp  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 10-January 09

Posted 12 January 2009 - 03:01 AM

Still not working ?

So does the session variable have to be cleared ?

Is the code wrong ?

regards

Rob





View Postteampoop, on 11 Jan, 2009 - 09:49 PM, said:

You have to have your header() calls before you do any output to the browser. So if your code has an echo (or print) before your header call, you will get an error. This is probably why there was a session variable set, to pass the information to the redirected page.

ex:
<?php
echo "checking for stuff";
header("Location: index.php"); // ERROR ensues
?>



Hope this helps.

View PostRobsphp, on 11 Jan, 2009 - 01:07 PM, said:

Akozlik

I get the following error ?

Warning: Cannot modify header information - headers already sent by (output started at /public_html/test/includes/conn.php:10) in /public_html/test/upload.php on line 81

When i try the images.php it seems to have worked but I get that error when upload.php is used ????

Rob

Was This Post Helpful? 0
  • +
  • -

#8 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 12 January 2009 - 12:16 PM

The session variable does not need to be cleared.

Are you printing anything before you redirect? That includes any html tags, spaces, whatever. If you send anything to the browser, your header won't be sent.

If you start a thread in the PHP Forum and post your code, we can take a look. I'd like to keep comments on here specifically focused on the tutorials themselves. Each individual case can be handled in the thread.

Thanks and glad you like the tut!
Was This Post Helpful? 0
  • +
  • -

#9 goodmuyis  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-September 08

Posted 24 February 2009 - 02:55 AM

HelLo Mr, thanks for this stuff is just for me
but am trying to change the file size but it doesn't respond to my changes, the size is it in byte or Kb(am sorry for that)

and thanks for ur stuff once again
Was This Post Helpful? 0
  • +
  • -

#10 chingkit  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-May 09

Posted 09 May 2009 - 09:23 AM

Hi,reading this tutorial really caught my attention. I am now working on my personal website, and planning to add my own photo gallery..I try to experiment with the code you have given and I find it so cool and easy to understood to a newbie like me. I Just like ask for one part of the tutorial, because I'm a bit confused. How can I create the directory.. Is it the folder which I'll be using to store all of my php files?..something like this.

root-directory/images.php
root-directory/index.php
root-directory/upload.php
root-directory/images/
root-directory/includes/conn.php

Hoping for your reply.Thanks in Advance=)

This post has been edited by chingkit: 09 May 2009 - 09:50 AM

Was This Post Helpful? 0
  • +
  • -

#11 Jupiter  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 01-February 07

Posted 08 August 2009 - 10:55 AM

Thanks a lot for this nice tutorial..it works like a charm :^:
Was This Post Helpful? 0
  • +
  • -

#12 rkmalbz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 10-August 09

Posted 17 August 2009 - 04:08 PM

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



I'm wondering whats the use of that root-directory..... and how do i put it up?? or how to build the directory?? sorry need some quick basic explanation. ^_^

This post has been edited by rkmalbz: 17 August 2009 - 04:13 PM

Was This Post Helpful? 0
  • +
  • -

#13 neos300  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 62
  • Joined: 21-April 09

Posted 20 August 2009 - 05:57 AM

The root directory is the directory that you will put all your .php files in.
Was This Post Helpful? 0
  • +
  • -

#14 kewlkreator  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 38
  • View blog
  • Posts: 1,065
  • Joined: 25-March 09

Posted 25 September 2009 - 12:23 PM

Thanks so much! It was fun to make!

Root directory:
You really don't have to worry about this. This is the folder where you will put all your files. Since the name of the directory is not needed in this script (other than to view the finished files), this is just another word for "any folder".

This post has been edited by kewlkreator: 25 September 2009 - 12:25 PM

Was This Post Helpful? 0
  • +
  • -

#15 mulson  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 11
  • Joined: 21-September 09

Posted 05 October 2009 - 04:56 PM

View PostRobsphp, on 10 Jan, 2009 - 04:13 PM, said:

akozlik

THANK YOU, I am trying to add to my members database an option to have there own avi file then grab it out of the database and display it.

Would I use the same idea (upload the avi's into a directory then reference them in the users table) ?

regards

Rob


i like the tutorial,but it is possible to display only one image at a time,not neccessary all...this is because i will like to
dispaly only a profile picture for each user,when they login :)

View Postakozlik, on 10 Dec, 2008 - 11:41 AM, said:

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!



i like the tutorial,but it is possible to display only one image at a time,not neccessary all...this is because i will like to
dispaly only a profile picture for each user,when they login.
Was This Post Helpful? 1
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3