I convert binary data to JPEG. PHP is cool for this, because I need just to send header('Content-Type: image/jpeg;'); and echo my binary.
But I have content above that binary like so:
echo 123;
header('Content-Type: image/jpeg;');
$data = hex2bin($CmnObiektZalacznik[0]->Binaria);
echo $data;
It will of course it will warn with Warning: Cannot modify header information - headers already sent by so i thought it (header and binary JPEG) could be outputed to temporary buffer something like that:
echo 123;
ob_start();
header('Content-Type: image/jpeg;');
$data = hex2bin($CmnObiektZalacznik[0]->Binaria);
echo $data;
ob_end_flush();
But I get to do it?
Related
I'm requesting an image from graph.facebook.com
The response header uses "content-type: image/jpeg" and prompts me to download instead of displaying it in the browser.
Is there a way (using PHP) to "intercept" the download and convert it to an image format?
Cheers.
UPDATE:
This kind of works. It returns the image to the browser (visible in Chrome's Network tab), but I'm not sure how to display it in an <img> tag:
<?php
$data = file_get_contents("https://www.petmd.com/sites/default/files/what-does-it-mean-when-cat-wags-tail.jpg");
// $data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
$qwe = imagepng($im);
imagedestroy($im);
return $qwe;
}
else {
echo 'An error occurred.';
}
?>
You code is invalid. You do not use return from non function as it makes no sense. If your case you need to replace
return $qwe;
with just plain
echo $qwe;
I'd also follow it by instant die(); and remove closing ?>. That should be all you need to make it work.
Not sure what is the point of fetching JPEG file but outputting PNG thought. You are gaining nothing but wasting time and resources, so the whole conversion code is pretty useless and echoing what you just downloaded should be perfecly sufficient:
header('Content-Type: image/jpeg');
$data = file_get_contents(".....");
if ($data !== false) {
echo $data;
}
die();
PS: As a homework, get rid of using file_get_contets() for network access and use cURL, esp. the network wrapper the former uses can be disabled.
On a web page, I am writing some data into a CSV file using the below code and finally closing with fclose();
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename);
$out = fopen('php://output', 'w');
fputcsv($out, $cvs_cols);
fclose($out);
echo "HELLO WORLD"; // sneaks into CSV!?
Why is it that "HELLO WORLD" gets into the CSV download file when it has already fclose()? I want to output the rest of the HTML for the page to be displayed in the browser. How can I do that?
After 1 HTTP request follows 1 response. You cannot send content type text/csv and content type text/html at the same time (maybe yes with SPDY, but not with pure HTTP).
fclose closes your file descriptor but not the output to the browser.
You should also set a Content-Length header and put in the filesize.
Mark Baker already gave the most important point in the comments:
echo and writing to php://output puts content into the same stream: STDOUT. Other options would be to write the CSV to memory (but its senseless if you don't use it) or to a file. Read more about the those streams: http://www.php.net/manual/en/features.commandline.io-streams.php
Possible solution:
You need 2 HTTP requests. 1 For the download, the other for your HTML. Most popular way is it to first use the HTML response and put something in like
<meta http-equiv="refresh"
content="3; URL=http://yourserver.com/download.php?id=pdf&id=123" />
This starts the download after 3 seconds.
There is no 'CSV File' (yet).
What you are doing is sending a data stream to the client, and telling the client that this stream has a Content-Type of text/csv and a filename of $filename. The client can then chose to save this as a CSV file or just display it in the browser.
This code:
$out = fopen('php://output', 'w');
fputcsv($out, $cvs_cols);
fclose($out);
Is effectively doing the same thing that echo $cvs_cols would do (with a little extra stuff to format a csv output).
So when there is a call to echo "HELLO WORLD"; it gets sent in the same data steam as the contents of the $cvs_cols variable.
When you call fopen('php://output', 'w') you are creating a second file handle to php://output as one is created by default to output from calls to echo etc. So when you are calling fclose($out) you're only closing the second file handle.
A very old thread here but to fix this I just added a simple exit(); command. So a button calls the same page with a query string of 'action=export_csv' then that action is run with the exit(); on the last line, hope that helps out.
Export CSV
Then the 'action' on the page is:
if(isset($_GET['action']) && $_GET['action']=='export_csv'){
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=email-responses.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Email address'));
$db = new PDO('mysql:host=hostname_mysql;dbname=database_mysql;charset=UTF8', username_mysql, password_mysql);
$query = "SELECT XXX FROM XXXX";
$result = $db->query($query);
$data = $result->fetchAll(PDO::FETCH_ASSOC);
// loop over the rows, outputting them
foreach($data as $row){
fputcsv($output, $row);
}
fclose($output);
exit();
}
use
ob_clean() : ob_clean — Clean (erase) the output buffer
flush() : flush — Flush the output buffer(flush)
ob_start();
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename);
$out = fopen('php://output', 'w');
fputcsv($out, $cvs_cols);
fclose($out);
ob_end_clean(); // the buffer and never prints or returns anything.
echo "HELLO WORLD"; // sneaks into CSV!?
UPDATE:
I used another solution to write my data into a file. It seems that I can't echo data while AJAX is waiting for a response. So I now use fwrite.
$fileHandle = '';
$fileHandle = fopen("export.txt","w");
fwrite($fileHandle, $export);
Original:
Hi there,
maybe my logic is wrong.
I make an AJAX call to get data from another URL.
That worked so far.
But now I want to add an file export also.
$handler = new MyHandler();
// Step 1: get data from URL
$dataAjax = $handler->getData($_POST['data']);
// Step 2: write the data into a text file to provide a download
$handler->writeToText($dataAjax);
echo json_encode($dataAjax);
Now the console shows me a "parserError" because my JSON data contains also the string I wanted to write into the file. That's bad and unwanted.
This below is just a test how I want to write my data into a txt file:
function writeToText($data)
{
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=export.txt");
header("Pragma: no-cache");
header("Expires: 0");
$title = "";
$title .= "Name,Quantity,Model,Price,Weight,Status"."\n";
echo $title;
}
That is how the error looks like:
{
"readyState": 4,
"responseText": "Name,Quantity,Model,Price,Weight,Status\n[{\"domain\":\"Text\",\"name\":\"Banana\}]",
"status": 200,
"statusText": "OK"
}
parsererror
http://sourceforge.net/projects/phpqrcode/, is a great library but i can't find how to return the png image as a string, the basic examples are
QRcode::png('code data text', 'filename.png'); // creates file
QRcode::png('some othertext 1234'); // creates code image and outputs it directly into browser
i checked the documentation and nothing, help! :B
ob_start();
QRCode::png('text', null);
$imageString = base64_encode( ob_get_contents() );
ob_end_clean();
$qrTempDir = 'path/to/your/temp';
$filePath = $qrTempDir.'/'.uniqid();
QRcode::png('some text', $filePath);
$qrImage = file_get_contents($filePath);
unlink($filePath);
This should be what you're looking for. You can extend it to show an image like that:
<img src="data:image/png;base64,<?php echo base64_encode($qrImage) ?>" />
Unfortunately, the library does not support any other method at the moment, because calling the QRcode::png function without the file parameter not only makes it send those headers, but it also exits the code execution, so there is no retracting or overwriting the headers.
I ran into the same problem as #iim.hlk
This is what i did slightly modified #Lusitanian his answer to this
ob_start();
QRCode::png($string);
$imageString = base64_encode( ob_get_clean() );
header('Content-Type: text/html');
This fixes the header issue by simply overwriting it. Not clean or anything but it works for the purpose.
this works for me
include '../phpqrcode/qrlib.php';
$content = "any content";
ob_start();
QRcode::png($content);
$result_qr_content_in_png = ob_get_contents();
ob_end_clean();
// PHPQRCode change the content-type into image/png... we change it again into html
header("Content-type: text/html");
$result_qr_content_in_base64 = base64_encode($result_qr_content_in_png);
then in your html file
<img src="data:image/jpeg;base64,$result_qr_content_in_base64'"/>
I'm struggling trying to read a php file inside a php and do some manipulation..after that have the content as a string, but when I try to output that with echo or print all the php tags are literally included on the file.
so here is my code:
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
$file = file_get_contents($path);
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}
and this will return a string like
<div id="content>
<h2>Here is my title</h2>
<p><? echo "my body text"; ?></p>
</div>
but this will print exactly the content above not compiling the php on it.
So, how can I render this "compilePage" making sure it returns a compiled php result and not just a plain text?
Thanks in advance
function compilePage($page, $path) {
$contents = getMenuFor($page);
ob_start();
include $path;
$contents .= "\n".ob_get_clean();
return $contents;
}
To evaluate PHP code in a string you use the eval function, but this comes highly unadvised. If you have a file containing PHP code, you can evaluate it with include, include_once, require, or require_once depending on your need. To capture the output of an included file - or required, or whichever method - you need to enable output buffering.
You can use output buffering for this, and include the file normally:
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
ob_start();
include $path;
$file = ob_get_contents();
ob_end_clean();
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}
The include() call will include the PHP file normally, and <?php blocks will be parsed and executed. Any output will be captured by the buffer created with ob_start(), and you can get it later with the other ob_* functions.
You need to use include() so it will execute. You can couple this with output buffering to get the return in a string.
function compilePage($page,$path){
$contents = array();
$menu = getMenuFor($page);
//output buffer
ob_start();
include($path);
$file = ob_get_contents();
ob_end_clean();
array_push($contents,$menu);
array_push($contents,$file);
return implode("\n",$contents);
}