Jump to content

Php image uploader to database help


Cha0s Blitz

Recommended Posts

Ok , so im fairly new to this beeen watching tuts , messing around with coding to see what does what , well i cant seem to get this uploader to send a image to the db it just errors the code is

<html>
<head>
<title>Image Uploader</title>
</head>
<body>
<form method="post" action="index.php" enctype="multipart/form=data">
File:
<input type="file" name="image" />
<input type="submit" value="upload" />

</form>


<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());


//file propities
$file = $_FILES['image']['tmp_name'];

if (!isset($file))  {
echo "Please select an image";
}
else
{
$image = file_get_contents ($_FILES['image']['tmp_name']);
$image_name = $_FILES['image']['name'];
$image_size = getimagesize($_FILES['image']['tmp_name']);

if ($image_size==FALSE) 
echo "This is not an image file";


else
{
if (!$insert = mysql_query("INSERT INTO imagedb VALUES ('','$image_name','$image')"))
echo "problem uploading image";


else
{
   $lastid = mysql_insert_id();
   echo "image uploaded<p>Your image</p><img scr =get.php?id=$lastid>";
}
}
}
?>
</body>
</html>

 

thats my index.php

 

 

then my get.php is

<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());  

$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM imagedb WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];

header("Content-type: img/jpeg");

echo $image;
?>

 

 

 

My database is called 'test'

and my table is called 'imagedb'

and i have 3 fields 'id'name'image.

 

help would be much appriciated thankyouu

 

Link to comment
Share on other sites

To store a image in a database you have to use the data type BLOB.  I have never experimented with it, but I've seen this question come up on the forums quite a bit and in almost all cases the answer is to store the image in a directory on your server and save the file path in the database.

Link to comment
Share on other sites

There are plenty of tutorials on the web doing just this thing.  Just went and looked at a few and it seams this is how you do it.

 

$tmpName  = $_FILES['image']['tmp_name'];

 

$fp = fopen($tmpName, 'r');

$content = fread($fp, filesize($tmpName));

$content = addslashes($content);

 

Then insert $content into the database.

 

Did not try it but here is where I got it from.

http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

Link to comment
Share on other sites

This is something I've been working on. I'll remove pieces that you won't be needing.

class imageUploader
{
public $image; // [name], [type], [tmp_name], [error], [size]

public $maxFileSize;

public function __construct($image, $max_file_size)
{
	$this->image = $image;

	$this->maxFileSize = $max_file_size;
}

public function isValidImage()
{
	$validExts = array("gif" => "image/gif", "jpeg" => "image/jpeg", "png" => "image/png");

	if(in_array(strtolower($this->image["type"]), $validExts) == true)
	{	
		return true;
	}
	else
	{
		return false;
	}
}

public function isValidSize()
{
	if($this->image["size"] > $this->maxFileSize)
	{
		return false;	
	}
	else
	{
		return true;	
	}
}

public function uploadImage()
{
	if($this->image["error"] > 0)
	{
		$errors[] = "An error has occurred";
	}
	elseif($this->isValidImage() == false)
	{
		$errors[] = "Invalid file type. Only use JPG, GIF or PNG";
	}
	elseif($this->isValidSize() == false)
	{
		$errors[] = "Max file size exceeded.";	
	}

	if(count((array) $errors) == 0)
	{
		move_uploaded_file($this->image["tmp_name"], "PHOTO_DIRECTORY/" . $this->image["name"]); // Replace "PHOTO_DIRECTORY" with directory of photo
		$query = mysql_query("INSERT INTO table (photo_url) VALUES ('PHOTO_DIRECTORY" . $this->image["name"] . "')") or die(mysql_error()); // Update the query with your details
		if($query == true)
		{
		    echo "Success, image has been uploaded";
		}
	}
	else
	{
		echo implode("<br />", $errors);
	}
}
}

 

An example usage of this. Would be...

 

if(isset($_POST['submit']))
{
    $imageUploader = new imageUploader($_FILES['file'], 500000); // 500000 = Max file size
    $imageUploader->uploadImage();
}

 

Basically, the IMAGE does not get stored in the database, but the path to the image does.

 

It should work, let me know if there is any problems.

Link to comment
Share on other sites

You are putting the raw image data into the SQL string. It is very likely that this data contains at least one byte that represents the single quote which you are using to delimit the string (or a NUL byte, or something else). Try wrapping the $image with mysql_real_escape_string(). It is similar to addslashes() but is specific to mysql server. So your INSERT statement would look like this (you should wrap the image name as well):

 

$sql = "INSERT INTO imagedb VALUES ('','"
mysql_real_escape_string($image_name) . "','" . 
mysql_real_escape_string($image) . "')";

that's kinda hard to read, which is why I use sprintf():

 

$sql = sprintf("INSERT INTO imagedb VALUES ('','%s', '%s')"),
  mysql_real_escape_string($image_name), mysql_real_escape_string($image) . "')";

 

Another option is to store it using base64_encode() and decode it (when you retrieve it) with base64_decode(). This will store a string representation so it will take more space.

 

In either case, you are going to have to watch out for the size of the image data. There is a limit on how much data you can send to and retrieve from the database in a single statement. This limit is set in the database server configuration file.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.