I am trying to use PDO to display image stored in a sql server database in a varbinary(max) field.
$conp = sqlsrv_connect("localhost", array("database"=>"dbname", "UID"=>"uid", "PWD"=>"somepassword"));
$id=16;
$stmt = sqlsrv_query($conp, "select image from image_tbl where id = $id");
$getAsType = SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY);
if (sqlsrv_fetch( $stmt ))
{
$image = sqlsrv_get_field( $stmt, 0, $getAsType);
header("Content-type:image/jpeg;");
fpassthru($image)
}
the above code displays the image correctly. If I try to use PDO as follows it shows a broken image icon.
$sql = "SELECT image FROM image_tbl WHERE id = ?";
$stmt = $conp->prepare($sql);
$stmt->execute(array(&$_GET['id']));
$stmt->bindColumn(1, $image, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-type:image/jpeg;");
echo $image;
without the header information it shows the same data. what am I doing wrong?
UPDATE: when I put file_put_contents('test.jpg', $data); it stores the image correctly. But I still cannot show it on the browser. May be there is something to do with the content-type. Don't know.
EDIT: I have changed the print_r($image); with echo $image;.
Related
I'm very new to development, and I'm trying to retrieve an image from an SQL server over an odbc connection using the below:
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
header('Content-type: image/jpeg');
echo "<img src=".$image."/>";
}
?>
The issue is that I'm getting an icon showing a broken image.
The query is correct as when I change it to the code below, it returns this string instead of the image:
Q2hyeXNhbnRoZW11bS5qcGc=
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
echo $image;
}
?>
I know the code is not correct and might be vulenrable to SQL injection, however I'd appreciate if you can help me retrieve the image.
Many thanks in advance,
J
If you decode the base64 string you get, then you'll see that the decoded data is Chrysanthemum.jpg. This is just the filename of the image, not the image data.
You need to either store the image in the database (not the filename) or add some code to read the image from the filesystem.
BTW, Content-Type image/jpeg requires that the data is the raw image, but your content (<img src=...> ...</img>) is an HTML fragment.
I want to do is when a user decided to change his profile picture the link in the database will be update and move the image to upload folder and destroy the current link and image on the upload folder on that specific user.
My problem in my code is when a user change his profile picture it will add another picture on the upload folder. I want to do is to delete the current image first on that specific user before the new image he selected is move on the upload folder.
php code
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$email = isset($_POST['email']) ? $_POST['email'] : "";
$image = addslashes(file_get_contents($_FILES['imageInput']['tmp_name']));
$image_name = addslashes($_FILES['imageInput']['name']);
$image_size = getimagesize($_FILES['imageInput']['tmp_name']);
move_uploaded_file($_FILES["imageInput"]["tmp_name"], "../upload/" . $_FILES["imageInput"]["name"]);
$location = "elogFiles/upload/" . $_FILES["imageInput"]["name"];
$qOldpic = "SELECT user_image FROM tbl_user WHERE user_email = : email";
$queryOldpic = $db->prepare($qOldpic);
$queryOldpic->bindParam(':email', $email);
$queryOldpic->execute();
$num_rows = $queryOldpic->rowCount();
if ($num_rows == 1) {
unlink($queryOldpic);
$q = "UPDATE tbl_user SET user_image = '$location' WHERE user_email= :email ";
$query = $db->prepare($q);
$query->bindParam(':email', $email);
$results = $query->execute();
echo "1";
}
?>
http://php.net/manual/en/function.unlink.php
above url will help you understand proper approach to delete the previous image file.
If you want to make the error message invisible when that file is not exist on given location, use '#' so you could simply ignore the error display as the following:
<?php
unlink($filename);
?>
Before you do your update, run a select and get the user_image by email, store it into a variable, like $oldPicture.
After that, you should remove the picture like this:
if ((!!$oldPicture) && (file_exists($oldPicture))) {
unlink($oldPicture);
}
You only delete an image if you have a value for its path and the file exists. Make sure the path of $oldPicture is correct. Finally, after the if above you can run your update command. I will not delve into security problems, as it is out of scope in this question, but make sure you prevent SQL injection.
I am trying to retrieve images from my SQL database which have been saved using the image path. The images are saved on the server. When i retrieve the images , nothing is returned.
if(isset($_GET))
{
include_once "mysql_connect.php";
$text = $_GET['text'];
if($text=="")
{
$query = mysql_query("SELECT `URL` FROM `gallery` WHERE `img_text` LIKE '1'")
or die(mysql_error());
while( $rows=mysql_fetch_array($query) )
{
$search[] = $rows[0];
}
$result = array();
$result["result"] = 500;
$result["message"] = "Database Read Successfully";
$result["rows"] = $search;
echo json_encode($result);
exit;
The example of code is for a search without the user entering a value. Within the SQL statement 'URL' is the field where the image paths are stored.The images paths values are the complete URL http://example.com/images/test.jpg and stored as a VARCHAR(200) . Any advice would be appreciated
Your code should not work well. You are not closing the if statement.
Also, when $text is not empty you don't have any query to the database...
You would need something like:
if($text==""){
$query = mysql_query("SELECT `URL` FROM `gallery` WHERE `img_text` LIKE '1'")
or die(mysql_error());
}
//when $text is not empty...
else{
$query = mysql_query("SELECT `URL` FROM `gallery` WHERE `img_text` LIKE '".$text."'")
or die(mysql_error());
}
while( $rows=mysql_fetch_array($query)){
$search[] = $rows[0];
}
By the way, try to use PDO instead of mysql_query, this last one is obsolete and is vulnerable to SQL injections.
The images are in the server, so the path only works there.
If you do a:
echo json_encode($result);
I guess you are returning this info to the client, the images path have no value there if you want to display them!
If you want to show the user the image you need to use a HTML img tag and fill the src attribute with the path FROM THE SERVER.
I have successfully added the original image into my imgs/ folder and also onto the server. But I'm wanting to add the thumbnail into the database. I've added it into the imgs/ folder but can't seem to find away to insert it into the database.
This is the final bit of code that is used to crop the img and insert it to the folder.
I need to insert it into the database also so I can call on it for the $_SESSION User and the Users friend as I have profiles.
if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
if(isset($_GET['a'])){
if ($_GET['a']=="delete"){
if (file_exists($large_image_location)) {
unlink($large_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic_small='".$img."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$img')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
}
Hope someone can help. Thanks.
If you want to add in your database the path of thumbnail ($thumb_image_location), just add the code that inserts the path before unlink().
If you want to store the whole image into database, you need the column to be MEDIUMBLOB type, then, before unlink() read the code of the file that contains the image, for example with:
$img = file_get_contents($thumb_image_location);
Then, INSERT data stored in $img into your database.
Ideally, you don't want to be adding the thumbnail itself to the database, just a reference (filepath) to the file. So, while I don't know what your database looks like, you need to go through the following steps:
Create a field in your table called 'thumbnail' or similar. This will hold the name which the thumbnail file is saved as.
Add the filepath to the database immediately after you crop the large image (ie between the lines '$cropped = ...' and 'header("location....' in your code)
Whenever a user or user's friend is logged in, check this field and pull any thumbnail images referenced in the table.
And that is basically it.
If you want to store only the path of the Image into Database ,than it's fine to insert only the path and serve it with HTML.
Otherwise if you want to store the raw data of the image into Database than you have to encode the Image into base64 String .
Sending/Displaying a base64 encoded Image - Here is how you encode and image at base64.
And store this huge string into a Blob Field Type into databse.
You can use this:
// Read the file
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
$data = addslashes($data);
fclose($fp);
// Create the query and insert into our database.
// image is an BLOB field type
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
I have tried to download images to a directory but now I want to save the images to the database using BLOB type by not using the File Chooser. I mean save the images direct from a URL:
Say:
http://someserver.com/images/imageone.gif
How can I save that directly to database? Do I have to download it first before saving to database? Please help me..
Like you would save any other data.
$imageContents = file_get_contents('http://someserver.com/images/imageone.gif');
$imageContentsEscaped = mysql_real_escape_string($imageContents, $link);
mysql_query("INSERT INTO table_name (imageData) VALUES ('$imageContentsEscaped')", $link);
Make sure the column you want to save the image data to is set to a binary type such as BLOB.
// download image to memory
$image = file_get_contents('http://example.com/my/image.jpg');
// open PDO connection
$db = ...;
// insert downloaded data to the DB
$sql = 'insert into my_table(filename, content) values (?,?)';
$stmt = $db->prepare($sql);
$stmt->bindParam(1, 'my/image.jpg');
$stmt->bindParam(2, $image, PDO::PARAM_LOB);
$stmt->execute();