blob\text images from MySQL return NULL - php

I post few days ago
Pass MySQL medium blob into IOS NSData\UIImage
but didn't manage to find a solution yet. my specific problem is that when I retrieve images from database, blob or text, it returns NULL, rows that don't have variables in them just return blank
while ($row = mysql_fetch_array($result)) {
$add = array();
$add["Id"] = $row["Id"];
$add["Mail"] = $row["Mail"];
$add["Category"] = $row["Category"];
$add["Phone"] = $row["Phone"];
$add["Msgs"] = $row["Msgs"];
//image from blob
$add["Picture"] = $row["Picture"];
// push single add into final response array
array_push($response["adds"], $add);
}
is there any other way to address images from blob\text?! I tried https://stackoverflow.com/a/6273415/1333294 but nothing works for me.

Finally!!
$img = $row["Picture"];
$b64img = base64_encode ($img);
$b64img = mysql_real_escape_string($b64img);
$add["Picture"] = $b64img;
simple as that! and xcode get it as base64 string and nut NULL. thanks for suggestions...

Add the following code
header("Content-type: image/jpeg");
echo $row['picture'];
// Display image with img html tag
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['picture'] ) . '" />';
echo 'Hello world.';
please find sample code
$response["adds"] = array();
$add = array();
$add["Id"] = 1;
$add["Mail"] = "test#mm.com";
$add["Category"] = "category";
$add["Phone"] = "1234567";
$add["Msgs"] = "ths s txt msg";
//image from blob
$add["Picture"] = "pciture";
// push single add into final response array
array_push($response["adds"], $add);
print_r($response["adds"]);
header("Content-type: image/jpeg");
print $response["adds"][0]['Picture'];

Related

CSV file upload with comma value using Php and mysql?

I was working on the eCommerce site and uploading the CSV file in the PHP database of Size that having the comma. The outcome of the result is the database is coming up with backward slash and double-quotes.
Please help me in rectifying that issue as had wasted my two days working on it.
CSV Format in notepad
Product Name,Footware Size
Shirt,"""35,36,34"""
Image of my csv file
CSV File
But it saved in the table
Table Screenshot
Code OF upload CSV File into the database
if($_FILES['csv_file']['name'])
{
$filename = explode(".", $_FILES['csv_file']['name']);
if(end($filename) == "csv")
{
$handle = fopen($_FILES['csv_file']['tmp_name'], "r");
$find_header = 0;
while($data = fgetcsv($handle,6000,",",'"'))
{
$find_header++;
if($find_header > 1){
$name = $database->escape_string($data[0]);
$foot_size = trim(addslashes($data[2]), '"');;
$products = new Product();
$products->product_name = $name;
$products->created_at = $time;
$products->updated_at = $time;
$result = $products->save();
if($result){
$product_id = $products->id;
if(!empty($foot_size)){
$sizes = explode(',', $foot_size);
$size_str = '';
foreach($sizes as $size){
$size_str .= $size.',';
}
$p_size = rtrim($size_str,",");
$product_size = new FootSize();
$product_size->product_id = $product_id;
$product_size->foot_size = $p_size;
$product_size->date = $time;
$product_size->save();
}
}
}
}
if($result === true){
$session->message('Product File Uploaded Successfully.');
fclose($handle);
redirect_to('add_product_csv');
}
}
else
{
$message = '<label class="text-danger">Please Select CSV File only</label>';
}
}
Problem
You have an error in this line:
$foot_size = trim(addslashes($data[2]), '"');
What it does is to first escape double quotes:
"35,36,34" --> \"35,36,34\"
And then trim them:
\"35,36,34\" --> \"35,36,34\
Solution
Depending on if you actually want to have the quotes stored in your DB or not, call either trim or addslahes (but not both) or none of the two:
Strip quotes:
$foot_size = trim($data[2], '"');
Keep quotes:
$foot_size = $data[2];
# your framework *might* require explicitly escaping of quote chars:
$foot_size = addslashes($data[2]);
# even better:
$foot_size = $database->escape_string($data[2]);

Get Image of Email with PHP

I'm trying to get an image from an E-mail which is sent to my mailserver and save the file to the server. I tried it with this code:
$no_of_occurences = 0;
$intStatic = 2;
$decode = imap_fetchbody($mbox, $val , null);
$no_of_occurences = substr_count($decode,"Content-Transfer-Encoding: base64");
$no_of_occurences--;
echo $no_of_occurences;
if($no_of_occurences > 0){
for($i = 0; $i < $no_of_occurences; $i++){
$strChange = strval($intStatic+$i);
$decode = imap_fetchbody($mbox, $val , $strChange);
$data = base64_decode($decode);
$x = 1;
$fName = './images/'.$ticketurl."_".$x. '.png';
while(file_exists($fName)){
$x++;
$fName = './images/'.$ticketurl."_".$x. '.png';
}
if($x==500){
$valid = false;
exit;
}
$file = $fName;
$success = file_put_contents($file, $data);
}
}
This code is working fine but only if you have one type of appendage in it. If you place one image inline the mail it is working. If you place one as an attachment, it also works. But if you got both (inline and as attachment) it's just getting one image and a second clean png file.
Any suggestions how to solve this behavior?

PDF Files from database keep getting corrupted

So I am storing my files in a database. Don't ask why, just know that I am not in control of this. Next, I am able to successfully store them as a hexidecimal representation and then spit them back for display with no problem, but then I attach them to an email using PHPMailer and they get sent properly with the right name and all, but they are corrupted. I will walk you through step by step below so that you know exactly how it is being stored, and this may help me debug my issue. (Please note that all code is paraphrased to save space and only show what is needed)
STEP 1
File is grabbed and then processed
$name = $_FILES['file_data']['name'];
$file = prepareImageDBString($_FILES['file_data']['tmp_name']);
$mime_type = $_FILES['file_data']['type'];
name, file, and mime_type are stored
here is the function prepareImageDBString()
function prepareImageDBString($filepath){
$out = 'null';
$handle = #fopen($filepath, 'r');
if($handle){
$content = #fread($handle, filesize($filepath));
$content = bin2hex($content);
#fclose($handle);
$out = $content;
}
return $out;
}
STEP 2
When the file is being viewed I show it as an embedded object. This file is small so I just posted the whole code. Do note that the file shows up with no problems here.
$q = "SELECT lease_doc_file_data FROM lease_doc_file WHERE lease_doc__id ='".$_GET['id']."'";
$file = "";
foreach($CONN->query($q) as $row){
$file = $row['lease_doc_file_data'];
}
if(!empty($file)){
header("Content-type: application/pdf");
ob_clean();
flush();
echo hextobin($file);
}
Here is the function hextobin()
function hextobin($hexstr){
$n = strlen($hexstr);
$sbin = "";
$i = 0;
while($i < $n){
$a = substr($hexstr,$i,2);
$c = pack("H*", $a);
if ( $i == 0 ){ $sbin = $c; }
else { $sbin .= $c;}
$i += 2;
}
return $sbin;
}
STEP 3
Finally the part where I go to send it as a mailer.
$q = "SELECT lease_doc_file_data, lease_doc_file_name, lease_doc_file_type FROM lease_doc_file WHERE lease_doc__id ='$id'";
$file_data = "";
$file_name = "";
$file_type = "";
foreach($CONN->query($q) as $row){
$file_data = $row['lease_doc_file_data'];
$file_name = $row['lease_doc_file_name'];
$file_type = $row['lease_doc_file_type'];
}
$file_data = hextobin($file_data);
$mail->AddStringAttachment($file_data, $file_name, 'binary', $file_type);
So this is the three step process and I"m not sure where the error is coming from. Hopefully someone can help! Thank you for all help in advance!

How to get Image on browser from binary data in php

I have 1 column containing binary format data.
I want to display that Image on browser and I am useing codeignater
My Model Code
function GetLogoById($Id)
{
$this->load->database();
$query = $this->db->query( "EXEC GetLogoById '$Id'" );
$result = array();
foreach ($query->result() as $row)
{
$result[] = array("Logo"=> $row->Logo);
}
return $result;
}
My Controller Code:
public function GetLogoById()
{
$this->load->model('MyModel');
$result = $this->MyModel->GetLogoById($Id);
$result = base64_decode($result);
echo $result;
}
It return in browse. What I am missing....
try with this.
$this->load->model('GetLogoById');
$result = $this->mymodel->GetLogoById($CarrierId);
header('Content-type: image/png');
echo $result[0]['Logo'];
Try this:
public function GetLogoById()
{
$this->load->model('MyModel');
$result = $this->MyModel->GetLogoById($Id);
//$result = base64_decode($result);
header('Content-Type: image/jpeg'); #set a header
echo $result;
}
<?php
public function GetLogoById() {
$this->load->model('MyModel');
// Get your result
$result = $this->MyModel->GetLogoById($Id);
// Do base64 decode if you encoded it.
$result = base64_decode($result);
// Set header according to the image type.
// if the image is jpg use 'image/jpeg'
// if the image is png use 'image/png'
// and so on ...
header('Content-Type: image/jpeg');
// Only echo the exact value. Keep in mind that no other
// space or any other values are echoed
echo $result;
// Also make sure that there must not be any spaces or other values before or after the php tags
}
?>
// This is a sample.
<?php
$image_data = file_get_contents( __DIR__ . '/dino_babu.jpg');
$image_token = base64_encode($image_data); // Save this token to database
$image_data_decode = base64_decode($image_token); // retrieve the token & decode it
header('Content-Type: image/jpeg'); // Set the header
echo $image_data_decode; // Print the data
?>

fread, filesize usage with remote picture

I'm doing a script that takes the image from Twitter API, and return's it on base64, but I have troubles because the file is on a remote server (Twitter). Here I show the code, the main problem is with the fread() and filesize(). I get this:
Warning: filesize() [function.filesize]: stat failed for http://a0.twimg.com/profile_images/...jpg in...
<?
mysql_connect...;
mysql_select_db...;
$autho_name = ...;
include '../twitter/LibTwitter.php';
$sql = mysql_query("SELECT * FROM `users` ORDER BY id DESC");
while($result = mysql_fetch_array($sql)) {
$userid = $result["userid"];
$busqueda = $twitter->usersShow($userid);
$username = $busqueda["screen_name"];
$img_src = str_replace("_normal.", "_reasonably_small.", $busqueda["profile_image_url"]);
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
}
?>
I replaced personal data with ... because of obvious reasons, no problem with that. Thanks!
Just use file_get_contents() to fetch the image, then it's a simple matter of:
$img = file_get_contents('http://a0.twimg...etc....');
$size = strlen($img);
$base64 = base64_encode($img);

Categories