As title I am trying to upload images on a DB Mysql using PHP:
Here are the scripts: (I know I should use mysqli...)
form in HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title> Carica un'immagine </title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000">
Invia questo elemento: <input name="userfile" type="file"></br>
<input type="submit" value="Carica">
</form>
</body>
</html>
PHP script:
<?php
//Connect to DB
$conn = mysql_connect('localhost', 'realegr', 'pass', 'my_realegr');
if (!$conn){
die("Could Not Connect to MySQL!");
}
if(!mysql_select_db("my_realegr")){
die("Could Not Open Database:" . mysql_error());
}
//file properties
$file = $_FILES['userfile']['tmp_name'];
if (!isset($file)){
echo "<p>Please Select an Image</p>";
} else {
$image = mysql_real_escape_string(file_get_contents($_FILES['userfile']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['userfile']['name']);
$image_size = getimagesize($_FILES['userfile']['tmp_name']);
if ($image_size==FALSE) {
echo "<p>NOT AN IMAGE</p>";
} else {
echo "<p>File is an Image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images (name, image) VALUES ('$image_name','$image')")){
echo ("<p>Error Uploading Image: " . mysql_error() . "</p>");
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
?>
Obviously there is another php script (get.php),but the problem is in this one.
The error I got is this:
File is an Image. Processing...
Error Uploading Image: Data too long for column 'image' at row 1
I can't understand the reason...(the image is of just 70 kb)
(THis is my table:
id int primary key Auto_increment
name varchar(50)
image blob
)
Don't save image data in the database. There is no need, and could even cause your site to run more slowly!
Instead, save it into an uploads folder that isn't publicly accessible using move_uploaded_file() http://php.net/manual/en/function.move-uploaded-file.php
Once you do that, store the path to the file in the DB!
Currently you have this line:"INSERT INTO images (name, image) VALUES ('$image_name','$image')". What if you attempted to change it into something like:
<?php
// NOTICE THE "LOAD_FILE"
// WHERE $fileToLoad IS THE PATH TO THE UPLOADED IMAGE-FILE
"INSERT INTO images (name, image)
VALUES('$image_name', LOAD_FILE({$fileToLoad}))";
However, storing images in the Database, from experience, is always not the very best of options...consider storing the images in a dedicated folder and simply saving only the address in your Database....
Related
I'm working on a php tutorial where a thumbnail generation page allows me to select from a dropdown list of photos in a directory on my server and upon hitting the submit button, a thumbnail of given size is created using a custom thumbnail class (the thumbnail overwrites the original image, which is fine for what I'm doing now). It's basic stuff and works as expected.
The page code:
<?php
$folder = '../images/';
use ClassFiles\Image\Thumbnail;
if (isset($_POST['create'])) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($_POST['pix']);
$thumb->setDestination('../images/');
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
?>
<form method="post" action="">
<p>
<select name="pix" id="pix">
<option value="">Select an image</option>
<?php
$files = new FilesystemIterator('../images/');
$images = new RegexIterator($files, '/\.(?:jpg|png|gif)$/i');
foreach ($images as $image) {
$filename = $image->getFilename();
?>
<option value="<?= $folder . $filename; ?>"><?= $filename; ?></option>
<?php } ?>
</select>
</p>
<p>
<input type="submit" name="create" value="Create Thumbnail">
</p>
</form>
</body>
</html>
The custom thumbnail class is lengthy and for the sake of brevity I'm not posting it here unless requested, as it works fine.
So here's the problem:
I decided to take the image path and image filename information from an upload page I've been working on and store them in session variables that could be taken to the thumbnail generation page. The code in the thumbnail generation page was modified as shown:
<?php
require_once('includes/session_admin.php');
$folder = $_SESSION['image_path'];
use ClassFiles\Image\Thumbnail;
$getSize = getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']);
$imagePath = $_SESSION['image_path'];
$imageFilename = $_SESSION['image_filename'];
if ($getSize[0] > 400) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($imageFilename);
$thumb->setDestination($imagePath);
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Image is " . $getSize[0] . "px wide and is OK!";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
// this was just to test that the session variables were correct
echo $_SESSION['image_path'] . $_SESSION['image_filename'];
echo '<br>';
print_r(getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']));
?>
<!--
Removed the form...
-->
</body>
</html>
Now, instead of the conditional statement checking to see if $_POST was submitted, the code (I thought) would automatically check to see if the image, given the full path and filename, is wider than 400px, and if so, resize the image using the custom thumbnail class.
But, this throws errors from the thumbnail class, the same class that works just fine with the original thumbnail generation page code from the tutorial.
This works in the original tutorial code:
$thumb = new Thumbnail($_POST['pix']);
but not when modified to take a session variable instead:
$thumb = new Thumbnail($imageFilename);
I've looked and looked for any suggestion that $_POST was required here, I checked that the session variables were passing along the proper information, and they are. But making the switch from $_POST to using a session variable prevents this from working.
As you'll see, I'm still learning php and this is one of those hurdles that has held me up all day. Perhaps the answer is glaringly obvious, but I'm certainly at a standstill.
All input is appreciated, thanks!
Try this before set the object of your class
$_POST['pix']=$_SESSION['image_filename'];
So you set the POST variable manually and use it a The thumbnail class suppose it
I have two files, one to upload an image and another to retrieve it from the database and present it on the web page. However the image only appears as broken image icon. I do not understand why.
Thanks for any help in advance.
The HTML form:
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="image">File:</label>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
The php to upload it(The connection to the DB is left out below but it works perfectly):
//file stuff
$file= $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image";
else {
$image=addslashes(file_get_contents($_FILES['image']['tmp_name']));
$imageName=addslashes($_FILES['image']['name']);
$imageSize=getimagesize($_FILES['image']['tmp_name']);
if(!$imageSize)
echo "Thats not an image you mong";
else {
//upload
$query="INSERT INTO store VALUES('','$imageName','$image')";
$sendQuery=mysql_query($query);
if(!$sendQuery)
echo "This is embarressing. It didn't work";
else {
$lastid=mysql_insert_id();
echo "Image was uploaded. <br>Your image:";
echo "<img src=get.php?id=$lastid/>";
}
}
}
The PHP to retrieve the image(Again the DB connection is left out below but works perfectly):
$id=addslashes($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
Make sure the the opening php tag is the very first line of the file. If the opening php tag is not on the first line of the file then content has already been written to the response causing calls to the header() function to be ignored.
<?php // this has to be on line 1
// do database connections stuff, no output can be sent to the response.
$id=addslashes($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
Maybe one of the magic quote setting (magic_quotes_gpc), try:
$image=stripslashes($image['image']);
You should be using mysql_real_escape_string() instead of addslashes() and only if magic quotes are not enabled.
I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.
What is the best method to achieve this?
You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.
Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.
The contents of getimage.php are small and simple:
// Check user permissions if necessary...
// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.
// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();
In your HTML:
<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />
It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.
If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.
ln -s /webroot/pictures /outside-of-webroot/uploads
If you're using an Apache server you could also have a look at mod_alias.
I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.
Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.
This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.
<?php
include("auth.php");
// uploadimg.php
// By Tyler Biscoe
// 09 Mar 2008
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;
if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
{
$error = "Error: File size must be under ". $max_kb . " kb.";
}
if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
{
$error .= "Error: Invalid file type. Use gif or jpg files only.";
}
if(!$error)
{
echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
$handle = fopen($_FILES["file"]["tmp_name"],'r');
$file_content = fread($handle,$_FILES["file"]["size"]);
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$id = $_POST["userid"];
echo $_FILES["file"]["tmp_name"];
$default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
$default_result = mysql_query($default_exist_sql);
$results = mysql_fetch_array($default_result);
if(!$results["default_image"])
{
$insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
mysql_query($insert_sql);
}
$sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
mysql_query($sql);
}
else
{
echo "<div id='alertBox'>". $error . "</div>";
}
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />
<form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method = "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>
This next one displays the file:
<?php
// image.php
// By Tyler Biscoe
// 09 Mar 2008
// File used to display pictures
include("connect.php");
$imgid = $_GET["id"];
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");
$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];
?>
Then:
<img src="image.php?id=your_img_id">
first time using stack overflow.
I have followed the following 2 part youtube tutorial on uploading/storing an image in a MYSQL database. I have followed the instructions but my image is not appearing for me. I use connect.php to connect to the database, this appears to be working fine. It seems the problem is with get.php as when I test echoing any images from it I always get no image.
used phpmyadmin to create the database and am using xampp.
here is the link to the youtube tutorials
http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=fvwrel
Included are the files
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
</form>
<?php
include 'connect.php';
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image.";
else{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name=addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE)
echo "That's not an image.";
else{
if(!$insert = mysql_query("INSERT INTO store VALUES('','$image_name','$image')"))
echo"Problem uploading image";
else{
$lastid = mysql_insert_id();
echo "image uploaded.<p />your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
</body>
</html>
Here is get.php
<?php
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image('image');
header("content-type: image/jpeg");
?>
And finally connect
<?php
// connect to database
$db_host="localhost";
$db_username="root";
$db_pass="";
$db_name="test";
#mysql_connect("$db_host","$db_username","$db_pass") or die("Could not connect to mysql");
mysql_select_db("$db_name")or die("Cant find database");
?>
Your get.php doesn't echo $image.
Also $image=$image('image'); should be $image=$image['image'];, and $_REQUEST('id') should be $_REQUEST['id'].
P.S. Don't use addslashes to prevent against SQL injections. Use mysql_real_escape_string.
You never echo the image data in get.php, so you're serving a blank 0-byte image.
You are missing a line after the header output
header("content-type: image/jpeg");
echo $image;
Very quick glance, in get.php change:
$image=$image('image');
to
$image=$image['image'];
mysql_fetch_assoc() converts the results into an array.
You better of bas64_encoding an decoding that way none ansi chars wont create a problem.
base64_encode(file_get_contents($_FILES['image']['tmp_name']));
This is wrong as array is [] not ()
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image['image'];
header("content-type: image/jpeg");
echo base64_decode($image);
Piece of code I use in a site of mine:
<?php
ob_start();
require_once("db.php.lib");
DBLogin();
$sql = "select pic_user_id, pic_full_data as bindata, pic_full_mime as mime, pic_full_size as size from pics where pic_name = '".urldecode($_GET["pic_name"])."'";
$result = DBExec($sql);
if ($result)
{
$row = DBGetNextRow($result);
if ($row)
{
header("Content-type: ".$row["mime"]);
header("Content-length: ".$row["size"]);
ob_clean();
echo $row["bindata"];
ob_end_flush();
}
}
?>
It looks like you're leaving out the actual output of the image data, and the length might be required by some browsers...
guys.
I tried to load image stored in mysql blob field with php, but the image does not show correctly. In firebug, I got these infos: get-image.php Dimensions0 × 0File size5.35KBMIME typeimage/jpeg
Here is my code
HTML
<html>
<head>
<title>Demo of Database Image in a page</title>
</head>
<body>
Here is your picture:<br>
img src=get-image.php?id=1 width=400 height=300><br>
</body>
</html>
PHP
<?php
include "db.php";
$conn = OpenDbConnection();
$key = $_GET["id"];
$tkey = "" . $key . "";
$strsql = "SELECT * FROM `images` WHERE `image_id` = " . $tkey;
$rs = mysql_query($strsql, $conn) or die(mysql_error());
if (!($row = mysql_fetch_array($rs))) {
die("File not exists.");
}
header("Content-type: image/jpeg");
echo $row["content"];
mysql_free_result($rs);
mysql_close($conn);
?>
Please someone tell me what is wrong with my code?
Please try this code.
Instead of
echo $row["content"];
Use this code
?>
<img scr="<?php echo $row["content"];?>" />
<?php
Thanks,
Kanji
Maybe it's because of blog type. Whenever you upload an image which exceed the limit of blob, then image not displayed correctly. Try to change type from blob to long blob.