Displaying an image from an SQL BLOB with PHP - php

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.

Related

Post multiple URL

I want to post multiple images by posting the url's but I don't know how to do this because I am new to PHP.
<?PHP
if(isset($_POST['post_image']))
{
$image_url=$_POST['image_path'];
$data = file_get_contents($image_url);
$new = '../images/myimage.jpg';
$upload =file_put_contents($new, $data);
if($upload) {
echo "<img src='../images/myimage.jpg'>";
}else{
echo "Please upload only image files";
}
}
?>
The problem with your script is, that you are not saving the file anywhere. So you have no access to it when trying to return it to the client.
In order to save an image using a POST you need to make sure you have set the following enctype inside your form.
<form action="upload.php" method="post" enctype="multipart/form-data">
Then you can use this function to save the img
move_uploaded_file($_FILES["myImg"], "/path/to/imgDir")
And later show it to the client using:
echo "<img src='/path/to/imgDir/myImg'>"
For more information about the topic i advice you to consult the following URL
https://www.w3schools.com/php/php_file_upload.asp

PHP: "Submit" box

I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");
//Perfom submit function
if(isset($_POST['Submit']))
fseek($fh, 0, SEEK_END);
fwrite($fh, "$addres_add") or die("Could not write to file");
fclose($fh);
print("Address added successfully. Updated book:<br /><br />");
echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
<p>
You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");
Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");
Otherwise, all the addresses will be on the same line.
Here is a simpler version of your program.
<?php
$file_path ="address_book.txt";
// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
echo("Error opening file. \n");
// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
// Append the new name (used the newline character to make it more readable)
$file_contents .= $_POST["any_name"] ."\n";
// Write the new content string to the file
file_put_contents($file_path, $file_contents);
print("Address added successfully. Updated book:<br /><br />");
echo($file_contents);
}
else
{
echo("Both form elements must be set. \n");
}
?>
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.

Uploading image failing on php back-end

I'm trying to implement a small update profile pic form.
<form method="post" action="<?php echo $filename;?>" name="change_picture_form" id="change_picture_form" enctype="multipart/form-data">
<input type="hidden" name="action" value="change_picture" />
<input type="file" name="new_user_picture">
<input type="submit" class="submitButton" value="Save Changes"/>
</form>
The target php file has the following code:
echo $_FILES['new_user_picture']['size']." ";
echo $_FILES['new_user_picture']['tmp_name']." ";
echo $_FILES['new_user_picture']['name']." ";
echo $_FILES['new_user_picture']['error']." ";
echo $_FILES['new_user_picture']['type']." ";
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"];
if( is_uploaded_file( $picture_uploaded ) ) {
$imagesize = getimagesize( $picture_uploaded );
switch( $imagesize[2] ) {
case IMAGETYPE_PNG:
$extension = '.png';
echo "<script>console.log('Reached here!!')</script>";
try {
$image_original = imagecreatefrompng( $picture_uploaded );
if (!$image_original)
echo '<script>console.log("not image original")</script>';
} catch(Exception $e) {
echo "<script>console.log('Error!!')</script>";
}
break;
case IMAGETYPE_JPEG: ....
...
}
}
Here, I have similar code for many image types. I tested this code by trying to uploading a png image. The first 5 echo statements display expected results - the size, error value of zero, the name, the type and the temp name.
I get "Reached here!!" on my console.
imagecreatefrompng, however, seems to crash silently. Try-catch somehow doesn't seem to catch the error.
Help? Thanks!
I haven't handled file uploads in PHP in forever, but is it possible that this line:
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"]
should be
$picture_uploaded = $_FILES["new_user_picture"] ?
The first line, as is, should be getting you the uploaded file's file name, whereas the second line (the edited line above) should be a reference to the file itself.
HTH.
EDIT: Well, seeing as how my answer is incorrect... does this help? http://www.php.net/manual/en/function.imagecreatefromstring.php
. There's a helper function in the user notes/comments that might simplify what you're doing

How to serve multiple images which reside above the www root within a single page?

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">

Getting an image from a database using PHP

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...

Categories