Get Image of Email with PHP - 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?

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]);

Page Hit Counter - Working but want to limit it to per IP Address

I currently have a working script that counts the number of views and stores them in a .txt file.
It's working fine but how do I make it so that it limits to your IP Address?
I tried this but it's not counting.
// Get filename of Page
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php');
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
// Remove .php extension
$counterName = basename($pageName, ".php").".txt";
// Open the file for reading
// "a+" Read & write the file. Create file if not exist.
$fp = fopen($counterName, "a+");
$fpIP = fopen("ip_".$counterName, "a+");
fwrite($fpIP, $ip."-");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Reopen the file and erase the contents
$fp = fopen($counterName, "w");
$ipRead = file_get_contents('ip_index.txt');
if(strpos($ipRead, "$ip") !== FALSE) {
echo $count;
}
else {
fwrite($fp1, $count);
echo $count;
}
fclose($fp);
Below is my updated code with Barmar's code (fully working) which will show each individual visitor how many times they have been to your page based on their IP address.
// Get filename of Page
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php');
// Remove .php extension
$counterName = basename($pageName, ".php").".counter";
// Get IP
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
$count_text = #file_get_contents($counterName);
$counters = $count_text ? json_decode($count_text, true) : array();
if (isset($counters[$ip])) {
$counters[$ip]++;
} else {
$counters[$ip] = 1;
}
file_put_contents($counterName, json_encode($counters));
echo $counters[$ip];
Store an associative array that's keyed off $ip in the counter file.
$count_text = #file_get_contents($counterName);
$counters = $count_text ? json_decode($count_text, true) : array();
if (isset($counters[$ip])) {
$counters[$ip]++;
} else {
$counters[$ip] = 1;
}
file_put_contents($counterName, json_encode($counters));
echo $counters[$ip];
You don't need the ip_XXX.txt file in this design.

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!

blob\text images from MySQL return NULL

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'];

file_get_contents gives me failed to open stream

I have simple CI (CodeIgniter) code. what I want to do is: when I enter the pictures path to textarea, php downloaded each picture to my server and gave them filenames, but I have these errors:
Message: file_get_contents(http://geosmiley.ge/Upload/Product/42/1.jpg ) [function.file-get-contents]: failed to open stream: Invalid argument
Message: file_get_contents(http://geosmiley.ge/Upload/Product/42/2.jpg ) [function.file-get-contents]: failed to open stream: Invalid argument
Here is my CI code:
$image = explode("\n", $_POST['images']);
for ($i = 0; $i < count($image); $i++){
if (substr($image[$i], 0, strlen($this->host) - 1) != $this->host){
file_put_contents('images/'.$title_url.'_'.$i.'.jpg', file_get_contents($image[$i]));
$image[$i] = $this->host.'/images/'.$title_url.'_'.$i.'.jpg';
}
}
$poster = $image[0];
$images = implode("\n", $image);
What it does is simply downloads last file and for first and second files gives me that error
and please don't give me other advice like using cURL of fopen. I think that it is correct way because php downloads LAST FILE successfully. Please help me to solve my problem
From the manual:
A URL can be used as a filename with this function if the fopen
wrappers have been enabled.
You will either need to set allow_url_fopen to true or use cURL instead.
I don't know Why the problem happened but here is the code that fixed it, thanks to "NikiC" who found out that witespace " " was the problem, I fixed it.
This Code doesn't work
$image = explode("\n", $_POST['images']);
for ($i = 0; $i < count($image); $i++){
if (substr($image[$i], 0, strlen($this->host) - 1) != $this->host){
file_put_contents('images/'.$title_url.'_'.$i.'.jpg', file_get_contents($image[$i]));
$image[$i] = $this->host.'/images/'.$title_url.'_'.$i.'.jpg';
}
}
$poster = $image[0];
$images = implode("\n", $image);
This is working code
$image = explode("\n", $_POST['images']);
for ($i = 0; $i < count($image); $i++){
if (substr($image[$i], 0, strlen($this->host) - 1) != $this->host){
if ($i < count($image)-1){
$kk = substr($image[$i], 0, strlen($image[$i]) - 1);
} else {
$kk = $image[$i];
}
if ($this->download($kk, 'images/'.$title_url.'_'.$i.'.jpg')){
$image[$i] = $this->host.'/images/'.$title_url.'_'.$i.'.jpg';
}else{
echo($image[$i]);
}
}
}
//****************************************************
public function download($url, $path){
if (file_put_contents($path, file_get_contents($url))){return TRUE;}else{return FALSE;}
}
Wrap your URL in quotes; make it a string

Categories