This tutorial goes over the concept of uploading files, and keeping records in a MySQL database.
So lets try this
When: I need to upload files and keep long term records on who uploaded and where it is.
Why: I don’t know, you make up the reasons.
What: Exactly do you need to keep record of? Time, who sent it, where is it?
Who: Depends on how you implement
Where: On the Internet!
How: I’ll show you.
There are two parts, so pay attention closely. (The last part is always the most important) Don’t forget to see more of this post for the sources and part two!
So first we need to make our uploading page. It is pretty much an XHTML template base with an uploading form
<!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.0 Transitional//EN”>
href=“main.css” type=“text/css” media=“screen” rel=“stylesheet”
Upload Index
enctype=“multipart/form-data” action=“upload.php” method=“post”
Choose your file to upload!
name=“uploadedfile” type=“file”
And what would you like to call it? name=“title” type=“text”
type=“submit” value=“upload file”
The most important part is the input for the file, the submit button and the form itself. In this case we have to say that there are multiple parts(the text, and the file) for this file upload so we set the enctype to “multipart/form-data”.
Since we are sending to another page(upload.php), we need to process it.
In upload.php, the basic way to save the file to the uploads directory is like the following(not final)
<?php
//time to see if the file is uploaded.
$putItAt = "uploads/".basename($_FILES['uploadedfile']['name']);
//hmm, will they try uploading a script or a page that might be a security risk?
//lets prevent any .php from getting in, and rename with .txt
$putItAt = str_replace("php","txt", $putItAt);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$putItAt)){
//we could echo, but why don't we just go to the file list now?
savedata();
header("location: listfiles.php");//redirect them to the listfiles.php page
}else{
//we failed. Lets try a slightly different method here. instead of moving, try copying
if(copy($_FILES['uploadedfile']['tmp_name'],$putItAt)){
//we have success!
savedata();
header("location: listfiles.php");
}else{
//we totally failed... so lets tell them.
echo 'You totally failed. click <a href="index.php">here</a> to go back and try again.';
}
}
?>
Next it is noticed that we aren’t saving any information in the database. Here comes the MySQL part.
Make your table in the database, call it what ever you want, in my case I named it ‘thefiles’. The requirement is that we connect to the database and set our script up to be able to query in and for information.
$link = mysql_connect('localhost', 'phpuser', 'phppass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//WE NEED to select the database!
mysql_selectdb("tutorials_upload");
By putting that at the top of our script, we now have a connection to the database so now we want to insert our information when it is uploaded. Now the question is: do we want to be redundant and have the inserting code twice(for copy and move), or do we want to make a function and refer to that function twice? Honestly I choose the later, it makes the code cleaner.
//function time!
function savedata(){
global $_FILES, $_POST, $putItAt;
$sql = "INSERT INTO `tutorials_upload`.`thefiles` (
`ID` ,
`Time` ,
`FileLocation` ,
`IP` ,
`Title`
)
VALUES (
NULL , UNIX_TIMESTAMP( ) , '".mysql_real_escape_string($putItAt)."', '".$_SERVER['REMOTE_ADDR']."', '".mysql_real_escape_string($_POST['title'])."'
);";
mysql_query($sql);
}
So now that I have this function, I need to implement it into the uploading code.
So, now my code finally for upload.php is
<?php
$link = mysql_connect('localhost', 'phpuser', 'phppass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//WE NEED to select the database!
mysql_selectdb("tutorials_upload");
if(!is_dir("uploads")){//do we need to make the uploads directory for the files?
mkdir("uploads");//make the rest of the script safe, though this will only be done once
}
//function time!
function savedata(){
global $_FILES, $_POST, $putItAt;
$sql = "INSERT INTO `tutorials_upload`.`thefiles` (
`ID` ,
`Time` ,
`FileLocation` ,
`IP` ,
`Title`
)
VALUES (
NULL , UNIX_TIMESTAMP( ) , '".mysql_real_escape_string($putItAt)."', '".$_SERVER['REMOTE_ADDR']."', '".mysql_real_escape_string($_POST['title'])."'
);";
mysql_query($sql);
}
//time to see if the file is uploaded.
$putItAt = "uploads/".basename($_FILES['uploadedfile']['name']);
//hmm, will they try uploading a script or a page that might be a security risk?
//lets prevent any .php from getting in, and rename with .txt
$putItAt = str_replace("php","txt", $putItAt);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$putItAt)){
//we could echo, but why don't we just go to the file list now?
savedata();
header("location: listfiles.php");//redirect them to the listfiles.php page
}else{
//we failed. Lets try a slightly different method here. instead of moving, try copying
if(copy($_FILES['uploadedfile']['tmp_name'],$putItAt)){
//we have success!
savedata();
header("location: listfiles.php");
}else{
//we totally failed... so lets tell them.
echo 'You totally failed. click <a href="index.php">here</a> to go back and try again.';
}
}
?>
Next, we have our file list page. We will start off with a basic XHTML template and have a CSS file linked in.
< !DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.0 Transitional//EN”>
href=“main.css” type=“text/css” media=“screen” rel=“stylesheet”
Uploaded Files
href=“index.php”Go back to the index
The main.css has
{
display: block;
width: 160px;
min-height: 160px;
border: thin dashed black;
float: left;
padding: 8px;
}
{
clear: both;
}
{
clear: left;
}
in it, which pretty much makes our list items boxes with a dashed border around them.
So the format I want to use is something like
YYYYYYY
Uploaded By: XXX.XXX.XXX.XXX
href=“uploads/ZZZZZZZ.jpg”YYYYYYY
So, in php, I would query the database for ‘thefiles’ and display the information in the like format.
<?php
//time to get our info
$sql = "SELECT * FROM `thefiles`";
$result = mysql_query($sql);
while($file = mysql_fetch_array($result)){
echo '<li>';
echo '<h1>'.$file['Title'].'</h1><br />';
//now the file info and link
echo '<h3>Uploaded By: '.$file['IP'].'</h3><br />';
echo '<a href="'.$file['FileLocation'].'">'.$file['Title'].'</a>';
echo '</li>';
}
?>
So, finally, our listfiles.php looks like (along with the MySQL connection section) this:
<?php
$link = mysql_connect('localhost', 'phpuser', 'phppass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//WE NEED to select the database!
mysql_selectdb("tutorials_upload");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link href="main.css" type="text/css" media="screen" rel="stylesheet"/>
<title>Uploaded Files</title>
</head>
<body>
<ul>
<?php
//time to get our info
$sql = "SELECT * FROM `thefiles`";
$result = mysql_query($sql);
while($file = mysql_fetch_array($result)){
echo '<li>';
echo '<h1>'.$file['Title'].'</h1><br />';
//now the file info and link
echo '<h3>Uploaded By: '.$file['IP'].'</h3><br />';
echo '<a href="'.$file['FileLocation'].'">'.$file['Title'].'</a>';
echo '</li>';
}
?>
</ul>
<br />
<a href="index.php">Go back to the index</a>
</body>
</html>
All that put together provides something that looks like

and ends with

April 30th, 2010 at 8:47 am
its a nice tutorial a bit to fast
thanks
April 30th, 2010 at 9:09 am
Browse and upload battens are missing
way?
April 30th, 2010 at 10:52 am
@rafi, I’m not sure what you mean by ‘Browse and upload battens are missing’ I assume you mean upload patterns, but still. Are you referring to a file list for what has been uploaded?
June 8th, 2010 at 1:40 am
nice one, it works i had been looking for File Upload system with records in MySQL for ages. Good work Kloplop
October 6th, 2010 at 10:05 am
Great tutorial! I am still a php beginner, and I have a need to do something VERY similar to this for a friend of mine. She owns her own photography business, and I want to be able to allow her to upload client proofs, but this could get very tedious doing this one picture at a time. Is there any way to allow multiple uploads? How would I modify your script?
Thanks!
Dana
October 7th, 2010 at 9:30 pm
Sorry, I saw your comment within 20 minutes, but forgot about it half an hour later. What you want to do is name the upload input element(as in name=”uploadfile”) to something like uploadfile[]
Then, count($_REQUEST['uploadfile'])
and perform the upload accordingly from uploadfile[0] to uploadfile[count - 1]
So that means you should also make a way to have more upload fields in your html.
If you do a google search, there are many wonderful examples. However, this is a great idea for a tutorial I might make some day.
October 11th, 2010 at 10:18 pm
hi i have a problem with your code especially uploading larger size of file.
Notice: Undefined index: uploadedfile in C:\wamp\www\document\upload.php on line 25
Notice: Undefined index: uploadedfile in C:\wamp\www\document\upload.php on line 29
Notice: Undefined index: uploadedfile in C:\wamp\www\document\upload.php on line 37
Warning: copy() [function.copy]: Filename cannot be empty in C:\wamp\www\document\upload.php on line 37
You totally failed. click here to go back and try again.
upload.php same code to your tutorial. i’m trying to upload larger file.
October 12th, 2010 at 8:14 am
Either it is that you aren’t using the exact line for the form settings: enctype=”multipart/form-data” action=”upload.php” method=”post”
Or, your PHP configuration does not allow you to upload files, Or your PHP configuration is ignoring the file because it is too large.
On the page
http://forums.devarticles.com/general-programming-help-4/files-userfile-tmp-name-not-working-1454.html
The last post says “The problem was my file was bigger than the MAX_FILE_SIZE. Silly me.” so check your php settings to see what it is set to.
November 1st, 2010 at 6:12 am
Thanks sooo much for this tutorial, helped me out alot. You are a god. I learn pretty quickly and by watching this tutorial only I learnt basic php and how it’s set out, surprisingly alike to c or c++. LOVE IT MAN <3 maybe more tutorials on maybe things like after that a more advanced view page like a music player for it once you get the link, well thanks heaps man
December 3rd, 2010 at 5:40 am
PHP Tutorials By Kloplop321 » Blog Archive » PHP & MySQL Tutorial 09: File Upload system with records in MySQL is an interesting name for a blog, keep up the good work, thanks, from Preston Todd
January 14th, 2011 at 3:51 pm
hi mate!
i am beginner of php and i try to write code in several way for uploading file. i got the same error each time. finally i copied your code and tried. even-though i got same error.
could you please find out the solution.
the error as follows
Warning: move_uploaded_file(uploads/myname.rtf) [function.move-uploaded-file]: failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/upload/uploading.php on line 33
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘/Applications/XAMPP/xamppfiles/temp/phpjMuJGA’ to ‘uploads/myname.rtf’ in /Applications/XAMPP/xamppfiles/htdocs/upload/uploading.php on line 33
Warning: copy(uploads/myname.rtf) [function.copy]: failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/upload/uploading.php on line 41
You totally failed. click here to go back and try again.
i understand that i need to do some setting somewhere. but i dont know how to do it.
i am using Mac operating system. and using XAMPP.
could you please write me where should i do some setting for permission ?
thank you
January 24th, 2011 at 7:09 am
thanks for the code. its working ok. but how do i check if the file i want to upload is already uploaded at the same location i want to upload my file. waiting to hear from you soon
January 24th, 2011 at 9:08 am
you can do something like
if(!file_exists(“location/for/uploads/”.$_FILE["uploadedfile"]['name'])){
//continue to save over it..
}
However, this is after they have already sent the web page, so the file is in a temporary folder on the server at this point.
February 5th, 2011 at 1:46 am
thanks a lot. i appreciate. God bless you.
April 7th, 2011 at 4:30 pm
Heya mate, brilliant tutorial, has been very helpful. Could you please do a follow on about deleting files as well?
April 9th, 2011 at 9:54 am
Sure, but if you want the answer quickly, the way to delete a file is
unlink($pathToFile)
August 9th, 2011 at 2:59 am
I would like to insert into thefiles table the title without move or copy file to uploads folder. When needed i will alter value of the record then move or copy file to uploads folder. what could i do with the Filename because: Warning: copy() [function.copy]: Filename cannot be empty in C:\wamp\www\PHP-Login\upload.php on line
October 28th, 2011 at 10:12 am
Hi I get blank filelocation, any solution using something instead basename to get the file location?
October 28th, 2011 at 11:12 am
basename does NOT return the file location, basename returns the name of the file, it searches for the last slash in the value you give it, and then gives you what ever is after that(the file name)
If you are giving it a directory, with a / at the end, it will return nothing.
October 29th, 2011 at 10:45 am
Thanks Kloplop, I find the problem finally, I put the global $_FILES, $_POST, $upfile; at the wrong place. NO it works thanks a lot mate!