PDA

View Full Version : how to upload files to mysql database using PHP


Adam_C
11-07-2009, 07:00 PM
I am new to php and need to find out how to upload files to a mysql database

i want to include (in my form)

- name
- short description
- full description
- icon (png image) that has to be 100px x 100px
- the file (has to be swf)

can someone provide a full walkthrough - either external full tutorial or write it out here?

i would be very greatful :) thanks,

Adam.

Adam_C
11-07-2009, 07:02 PM
sorry forgot to add,

- time and date it was uploaded
- how do i make a 'play counter' to see how many times a game has been played then put it into the database?

:)

edbr
11-09-2009, 01:48 AM
best to upload to a folder and add a link in the database to that uploaded file.
time and date you will need a datetime field or timestamp
try tizag for tutorials on uploads see our own pp tutorials for a good beginners course

Adam_C
11-09-2009, 03:59 PM
best to upload to a folder and add a link in the database to that uploaded file.
time and date you will need a datetime field or timestamp
try tizag for tutorials on uploads see our own pp tutorials for a good beginners course

how would i upload a file in a php form to a folder? the reason i ask is because i want to upload things all at the same time as it is much easier :)

thanks :)

edbr
11-10-2009, 12:57 AM
check out tizag for tuts or search for a php upload script

tux
11-11-2009, 09:37 AM
Hi Adam,

Here is a script that uploads an image file and also resizes the image and copies each new image to a folder.

You can alter it to suit your own requirements.

Hope it helps.

Regards Paul

<?php
// function to get file extension
function getExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// define max file size, change to suit your own maximum file size
define ("MAX_SIZE","1000");
$errors=0;
//get the original file from form
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image = $_FILES["file"]["name"];// from your upload form
$uploadedfile = $_FILES['file']['tmp_name'];// from your upload form
// check for correct file extension
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension! ';// build your own error handling here
$errors = 1;
}
// check for correct file size
else
{
$size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";// build your own error handling here
$errors = 1;
}
// check which extension we have and create file
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
//resize image and create thumbs and small thumbs
list($width,$height)=getimagesize($uploadedfile);
//for main images, this keeps the width at 300px regardless of portrait or landscape
$newwidth=300;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
//for thumbnails, change the $newwidth variable to what ever size you need
if($width > $height){//landscape
$newwidth1=100;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1) ;
}elseif($width < $height){//portrait
$newheight1=100;
$newwidth1=($width/$height)*$newheight1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1) ;
}
//for smaller thumbnails, my site required this smaller thumb. Delete this section if you dont need it
if($width > $height){//landscape
$newwidth2=50;
$newheight2=($height/$width)*$newwidth2;
$tmp2=imagecreatetruecolor($newwidth2,$newheight2) ;
}elseif($width < $height){//portrait
$newheight2=50;
$newwidth2=($width/$height)*$newheight2;
$tmp2=imagecreatetruecolor($newwidth2,$newheight2) ;
}
// create new resized files
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$ne wheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$ newheight1,$width,$height);

imagecopyresampled($tmp2,$src,0,0,0,0,$newwidth2,$ newheight2,$width,$height);
//declare destinations
$filename = "Images/Gallery/Test/". $_FILES['file']['name']; //
$filename1 = "Images/Gallery/Test/Test_Thumbs/". $_FILES['file']['name']; // your destination paths here
$filename2 = "Images/Gallery/Test/Test_Thumbs/Small/". $_FILES['file']['name']; //
//write files to folders
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename2,100);
//destroy temps to save memory
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
imagedestroy($tmp2);
}
}
}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "Image Uploaded Successfully!";
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload Image Files and Resize</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form name="upload" enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="file" name="file" id="file" >
<input type="submit" name="Submit" id="Submit" value="Upload Image">
</form>
</body>
</html>

Adam_C
11-15-2009, 02:03 AM
thanks, does the above script upload a file to a folder e.g 'uploads' then automatically use the url of the file in the html form?

does this make sense?

thanks again, Adam.

tux
11-15-2009, 08:01 PM
The user will browse for a file on their hard drive. Then when they submit the form the file will be uploaded to your server and saved in the folder you specify in the script.

Is this what you mean??

Adam_C
11-15-2009, 08:03 PM
The user will browse for a file on their hard drive. Then when they submit the form the file will be uploaded to your server and saved in the folder you specify in the script.

Is this what you mean??

kind of, i want them to be able to upload the file to my server and then a link to that file will be placed in a database

tux
11-15-2009, 09:15 PM
In the script this variable '$image' is the file name.

What I do is save just the file name to my database and then hard code the path to the folder that the image is stored in and then echo out just the file name. Like this....

<a href="pathto my file/<?php echo $image; ?>">Click to see my file.</a>

Adam_C
11-16-2009, 12:49 AM
i have this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TITLE</title>
<!--LINKS TGO CSS AND JS-->
</head>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="content">
<div id="sidebar">
<ul>
<li class="home"><a href="index.php" >Home</a></li>
<li class="about"><a href="about.php" >About</a></li>
<li class="portfolio"><a href="portfolio.php" >Portfolio</a></li>
<li class="contact"><a href="contact.php" >Contact</a></li>
<li><a href="upload.php">Upload</a></li>
</ul>
</div>
<div id="maincontent">
<h3 class="mainheader">Upload</h3>
<br />
<br />
<br />
<br />
<p class="p"><br />
<?php
// function to get file extension
function getExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// define max file size, change to suit your own maximum file size
define ("MAX_SIZE","1000");
$errors=0;
//get the original file from form
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image = $_FILES["file"]["name"];// from your upload form
$uploadedfile = $_FILES['file']['tmp_name'];// from your upload form
// check for correct file extension
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension! ';// build your own error handling here
$errors = 1;
}
// check for correct file size
else
{
$size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";// build your own error handling here
$errors = 1;
}
// check which extension we have and create file
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
//declare destinations
$filename = "uploads/". $_FILES['file']['name'];
//write files to folders
imagejpeg($src,$filename,100);
//destroy temps to save memory
imagedestroy($src);
}
}
}
$user="user";
$password="password";
$database="dbname";
$con = mysql_connect (localhost,$user,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tablename", $con);
$file=uploads/ $image;

mysql_query("INSERT INTO logos (name, shortinfo, longinfo, content)
VALUES ($name, $shortinfo, $longinfo, $file)");
$sql = null;

if ($sql) {
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
} echo'<h2 class="centered">Thank you!</h2>';
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{?>
<script type="text/javascript">alert("Image Uploaded Successfully!")</script><br />
<a href="index.php" style="margin-left:30px;">Click Here To Go Home</a>
<br /><br />
<a href="upload.php" style="margin-left:30px;">Upload Another File?</a>
</p>
</div>
</div>
</div>
</body>
</html>

what have i done wrong? :S

tux
11-16-2009, 07:03 AM
Hi Adam,

Got to go to work but will take a look at this when I get home.

In the meantime, your main php code should go at the top of the page before the doc type. The server reads the php first processes it and then sends the results out to the browser.

Regards Paul

Adam_C
11-16-2009, 03:39 PM
Hi Adam,

Got to go to work but will take a look at this when I get home.

In the meantime, your main php code should go at the top of the page before the doc type. The server reads the php first processes it and then sends the results out to the browser.

Regards Paul

thanks Paul, will do that now.

very much appreciated,

Adam.

tux
11-16-2009, 06:01 PM
Hi Adam,

I have written some code for you. Copy it to a new page and save it as adam.php.

You will have to edit your database connection code to suit. As long as your table name is 'logos' and your field name is 'content' you should not have to edit anything else.

When you run the page you should have a form to upload files. Try a few different files, to big, correct size, wrong extension etc. You should get success messages and error messages. As you upload correct files the links will start to build.

Pick the bones out of the script and see if you can understand what each part of the code is doing. Once you get to understand whats going on you can adapt it to your own pages.

Let me know how you get on.

Paul

<?php
////////////////////////////////////// connection script - enter your details here
$user="user";
$password="password";
$database="dbname";
$con = mysql_connect (localhost,$user,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tablename", $con);
///////////////////////////////////////error handling - if an error is detected in the url the appropriate error will be displayed
$error = $_GET['error'];
if($error == 1){
$error = "Unknown Image extension!";
}elseif($error == 2){
$error = "You have exceeded the size limit";
}else $error = '';
//////////////////////////////////////upload/resize script

function getExtension($str) {// function to get file extension

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// define max file size, change to suit your own maximum file size
define ("MAX_SIZE","1000");
$errors=0;
//get the original file from form
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image = $_FILES["file"]["name"];// from your upload form
$uploadedfile = $_FILES['file']['tmp_name'];// from your upload form
// check for correct file extension
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{

header("location:adam.php?error=1");// error handling here - if the file ext is wrong the script will exit and redirect with error in the url
exit;///////////////////////////////// note that I have used adam.php as the file name, change this if you save the file differently
}
// check for correct file size
else
{
$size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{

header("location:adam.php?error=2");// error handling here - if the file size is wrong the script will exit and redirect with error in the url
exit;///////////////////////////////// note that I have used adam.php as the file name, change this if you save the file differently
}
// check which extension we have and create file
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
//declare destinations
$filename = "uploads/". $_FILES['file']['name'];
//write files to folders
imagejpeg($src,$filename,100);
//destroy temps to save memory
imagedestroy($src);
}
}
}
//If no errors registered, insert file name into database and print the success message
if(isset($_POST['Submit']) && !$errors)
{
mysql_query("INSERT INTO logos (content) VALUES ('$image')");

$success = "Image Uploaded Successfully!";
}
//////////////////////////////////////////////////select file names from database
$query = sprintf("SELECT * FROM logos ");
$result = @mysql_query($query);
$row = @mysql_fetch_array($result);
?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TITLE</title>
<!--LINKS TGO CSS AND JS-->
</head>
<body>
<p><?php echo $success; ?><?php echo $error; ?></p>
<form name="upload" enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="file" name="file" id="file" >
<input type="submit" name="Submit" id="Submit" value="Upload Image">
</form>

<?php if($success){ do{ ?>
<p><a href="uploads/<?php echo $row['content']; ?>">View File!</a></p>
<?php
}while($row = @mysql_fetch_array($result));
}
?>
</body>
</html>

Adam_C
11-16-2009, 06:15 PM
thanks v much :)

will do it now :D

Adam_C
11-16-2009, 07:07 PM
have used the script and it uploads the photos to the folder but it doesnt upload the url of the file to the database,

also how do i add the other elements of the form into the database?

thanks, Adam. :)

tux
11-16-2009, 07:20 PM
Lets get this working first Adam.

Check that the table name and field name is correct.

They must be exactly the same as you have in your DB.

The script assumes that the table name is 'logos'' and the field name is 'content'. Change them in the INSERT query if yours are different. I took those names from an earlier post I think.

It works okay my end so it must be something your end.

Copy the code as you now have it and post it so I can check it.