I have a SQL Server table with a column called personal image with image data type.
I want to insert or update this field using PHP sqlsrv extension.
I have that image file for update query and i try this but the image not inserted correctly.
function prepareImageDBString($filepath)
{
$out = 'null';
$handle = #fopen($filepath, 'rb');
if ($handle)
{
$content = #fread($handle, filesize($filepath));
$content = bin2hex($content);
#fclose($handle);
$out = "0x".$content;
}
return $out;
}
$out = prepareImageDBString('871190915.jpg');
$update = "UPDATE Person SET PersonelImage=(?) WHERE no=871190915";
$image1=array($out);
sqlsrv_query($conn, $update, $image1);
Can anyone help me?
Related
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]);
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!
So I have searched high and low for a relevant answer, and I have yet to find one, so I'm just going to ask the question myself. In my MySQL tables I have 5 columns of id, customer__id, file_data, file_name, mime_typethe relevant one here is file_data which is a type of LONGBLOB. Now from what I understand the size of files that a LONGBLOB can handle is pretty substantial but when I try to upload a file that is around 978 KB it fails, could it be that the dimensions of the image are too large (2048 x 1536)?
Here is the code for my uploader. It works very elegantly for things like excel sheets, pdf, word documents, and other stuff, but when it comes to images it fails:
<?php
require_once '../../inc/config.php';
$response = array();
$response['errors'] = false;
$id = $_REQUEST['id'];
if(!empty($_FILES)){
//set default data arrays
$names = array(); //stores file names
$files = array(); //stores the file data
$mime_types = array(); //store the file type as a mime type
//force each file name to the names array
foreach($_FILES['file']['name'] as $name){
array_push($names, $name);
}
//force the file data into its own array spot in the files array
foreach($_FILES['file']['tmp_name'] as $temp){
array_push($files, prepareImageDBString($temp));
}
//force the mimetypes into the mime_types array
foreach($_FILES['file']['type'] as $type){
array_push($mime_types, $type);
}
//process all three of the file arrays simultaneously so that no data is left out
for($i = 0; $i < count($names); $i++){
$file_name = $names[$i];
$file_data = $files[$i];
$mime_type = $mime_types[$i];
//set the query for the data to go into the note_file table in the database
$q = "INSERT INTO brb.files (customer__id, file_name, file_data, mime_type)
VALUES('$id', '$file_name', '$file_data', '$mime_type')";
//run the query
if($stmt = $CONN->prepare($q)){
//process any errors that may occur
if(!$stmt->execute()){
printf("Error Message: %s\n", $CONN->error);
}
}
}
}
echo json_encode($response);
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;
}
?>
If someone could point me in the direction that would be fantastic. Please do not provide be an answer on why the practice is bad, I'm aware it's bad practice and know what proper practice is, this is a learning tool for myself and nothing more, just bear with me on it for a minute.
Thank you to everyone who provides help!
I am trying to write a function to process images in mySQL / PHP but cannot work out how to store the results. I have included a stripped down version of the code to demonstrate the problem.
The blobs in image.image_o are all correctly stored and can be used to output images to the web page. The function runs without error but afterwards the blobs in image.image_r are just a few bytes long and contain text like "Resource id #5"
I am sure I am doing something dumb - just can't see what it is.
function process_images(){
global $mysql
$sql = "select id, image_o from image";
$res = mysqli_query($mysqli, $sql);
if ($res){
while ($ay = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$id = $ay['id'];
$im = imagecreatefromstring($ay['image_o']);
// do something useful with the image
$sql2 = "update image set image_r = '{$im}' where id = $id";
$res2 = mysqli_query($mysqli, $sql2);
if ($res2){
// blah blah
}else{
echo mysqli_error($mysqli)." in res2";
}
}
}else{
echo mysqli_error($mysqli)." in res";
}
}
I agree with the commentary above that this is generally not advisable. However, here is a great article on why you MIGHT do it, and how. It also highlights some of the cons of storing images in the database.
http://forum.codecall.net/topic/40286-tutorial-storing-images-in-mysql-with-php/
You need to make sure you read the data into the field. Not just the file pointer:
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Now take the contents of data and store THAT
In a nutshell, imagecreatefromstring returns "An image resource will be returned on success", not the contents of the file itself. You need to read the contents of that resource before you can store it. Using your code, make the following changes:
function process_images(){
global $mysql
$sql = "select id, image_o from image";
$res = mysqli_query($mysqli, $sql);
if ($res){
while ($ay = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$id = $ay['id'];
$im = imagecreatefromstring($ay['image_o']);
$tempFileName = '/tmp/' . $id . 'jpg';
$imTempFile = imagegd($im, $tempFileName);
$fh = fopen($tempFileName, "r");
$data = fread($fh, filesize($tempFileName));
// do something useful with the image
$sql2 = "update image set image_r = '{$data}' where id = $id";
$res2 = mysqli_query($mysqli, $sql2);
if ($res2){
// blah blah
}else{
echo mysqli_error($mysqli)." in res2";
}
//delete the temp file
unlink($tempFileName);
}
}else{
echo mysqli_error($mysqli)." in res";
}
}
I'm trying to open an encrypted file that will store a list of information, then add a new ID with information, and save the file back as it was originally encrypted. I have xor/base64 functions that are working, but I am having trouble getting the file to retain old information.
here is what I am currently using:
$key = 'some key here';
$id = $_GET['id'];
$group = $_GET['group'];
$file = "groups.log";
$fp = fopen($file, "w+");
$fs = file_get_contents($file);
$filedec = xorstr(base64_decode($fs),$key);
$info = "$id: $group";
$filedec = $filedec . "$info\n";
$reencode = base64_encode(xorstr($filedec,$key));
fwrite($fp, $reencode);
fclose($fp);
function xorstr($str, $key) {
$outText = '';
for($i=0;$i<strlen($str);)
{
for($j=0;$j<strlen($key);$j++,$i++)
{
$outText .= $str[$i] ^ $key[$j];
}
}
return $outText;
}
?>
It should save an entire list of the ID's and their corresponding groups, but for some reason it's only showing the last input :(
I wouldn't call this encryption. "cereal box decoder ring", maybe. If you want encryption, then use the mcrypt functions. At best this is obfuscation.
The problem is that you're doing fopen() before doing file_get_contents. Using mode w+ truncates the file to 0-bytes as part of the fopen() call. So by the time file_get_contents comes up, you've deleted the original file.
$fs = file_get_contents(...);
$fh = fopen(..., 'w+');
in that order will fix the problem.