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