I got a code here using file_exist. it checks if a .txt and a .jpg file exist in the directory. and then displays those in an alert box. it works well for the .txt but not in the .jpg. it displays the image source instead of the image itself. what am i doing wrong here? can you give me some help regarding this? thanks a lot in advance! here's my code.
search.php
<?php
class Model
{
public function readexisting()
{
if(
file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.txt")
&&
file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.jpg")
)
{
$myPic = "/Alchemy/ajax/events/folder-01/event-01.jpg";
echo $myPic;
$myFile = ($_SERVER['DOCUMENT_ROOT'] . "/Alchemy/events/folder-01/event-01.txt");
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData ;
}
else
{
echo "The file $myFile does not exist";
}
}
}
?>
You need to apply header() and tell PHP that you are rendering an image.
header("Content-type: image/jpeg");
OR depending upon which file you are rendering, apply proper headers.
Remove the echo $myPic; and then add this before the echo $theData;
header("Content-type: image/jpeg");
In general you have to inform the browser for the data type you are sending. Also note, that the header() command should be located before you start sending any data to the browser.
Also, if you will manipulate multiple file types (ie: png, jpg, gif) you should change the MIME type in the deader command to map the appropriate file type.
header("Content-type: image/gif"); // For gif images
header("Content-type: image/png"); // For png images
header("Content-type: image/jpeg"); // For jpg images
For an image (or anything else for that matter) you'll need to send a content-type header, otherwise it will not be shown. You can do this by getting the mime-type first here and then adding the header by doing this before the echo.
header("Content-Type: ". $mimetype);
echo $theData;
Where $mimetype is the mime type retrieved.
Related
I am getting response from cURL which is an encoded string format of pdf(i guess) - see attached image.
I am getting pdf file if i directly put the url in browser. Since its asking for api credentials for viewing the pdf, its not user friendly and i am looking for another way to directly download the file.
So i am trying to get the string content of the pdf file with cURL and i am getting exactly what in the image attached(only small portion attached).
Using that string content, i tried to save it as a plain txt file and from there i tried to decode the string text and to create a pdf file newly. After creating i need to download the same.
I could create text file with the string data i got from cURL and could create pdf also. But the downloaded file showing Failed to load PDF document.
Below is the code i have tried and i am not sure whether i tried correctly or not.
function pdf_download(){
$this->load->helper('file');
$curl = $this->api_call->callapi('GET',APIURL."carts/96171/tickets");
$content = $curl;
$my_file = FCPATH . '/document/text.txt';
if (write_file($my_file, $content) == FALSE)
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
$pdf_base64 = $my_file;
//Get File content from txt file
$pdf_base64_handler = fopen($pdf_base64,'r');
$pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64));
fclose ($pdf_base64_handler);
//Decode pdf content
$pdf_decoded = base64_decode ($pdf_content);
//Write data back to pdf file
$pdf_file=FCPATH . '/document/ticket.pdf';
$pdf = fopen ($pdf_file,'w');
fwrite ($pdf,$pdf_decoded);//Creating a pdf from the encoded content in txt file
fclose ($pdf);
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=tickets.pdf");
ob_clean(); flush();
readfile($pdf_file);//downloading the pdf file
exit();
}
Since streaming a download to the browser requires sending headers, you must not output anything before sending headers. Therefore, you must get rid of:
if (write_file($my_file, $content) == FALSE)
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
If you definitely need to check if the file was written (for debugging purposes, I assume) you may use CI's log_message() to write a debug entry in the logs or just set a control variable. For example:
if (write_file($my_file, $content) == FALSE)
{
log_message('debug', "Unable to write file");
$file_written = false;
}
else
{
log_message('debug', "File succesfully written");
$file_written = true;
}
Also, there's some headers missing to ensure the file is not streamed to the browser but sent for download, as well as some required to make sure the file is correctly downloaded
header('Content-Description: File Transfer');
header('Content-Type: '. mime_content_type($pdf_file)); // since you're using Codeigniter, this will try to use the correct mimetype
header('Content-Disposition: attachment; filename="ticket.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($pdf_file));
readfile($pdf_file);
The wrong line in the above given code is $pdf_decoded = base64_decode ($pdf_content);.
It should be changed to $pdf_decoded = $pdf_content;
Since string in encoded format is already getting which is needed for creating PDF. So no need to decode it.
Also the above code is reduced as below.
function pdf_download(){
$this->load->helper('file');
$this->load->helper('download');
$cart_id=$this->input->get('cart_id');
$curl = $this->api_call->callapi('GET',APIURL."cart/'.$cart_id.'/tickets");
$pdf_file=FCPATH . 'document\voucher-'.$cart_id.'.pdf';
if (write_file($pdf_file, $curl))
{
force_download($pdf_file, NULL);
}
}
I am setting up a random image function but trying to prove the concept before handling the randomizer.
Right now I have a test.php file. It contains:
<?php
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');
header('Content-type: image/jpeg;');
header("Content-Length: " . filesize($img));
fpassthru($fp);
exit;
?>
And then in another html file I have <img src="test.php">
The goal is just to return the image. The image url works is right, and test.php returns a 200. But the image just shows the little broken image icon.
I have also tried readfile() with no luck.
I am just trying to show this image.
filesize does not work on HTTP URLs. The docs say:
This function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
However, the HTTP wrapper does not support the stat function. Because of this, you send a wrong Content-Length header and the HTTP response cannot be interpreted by your browser.
I see two possible solutions:
Load the image into memory and use strlen:
$image = file_get_contents('http://example.com/img.jpg');
header('Content-type: image/jpeg;');
header("Content-Length: " . strlen($image));
echo $image;
Use the $http_response_header variable to read the remote response's Content-Length header:
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');
header('Content-type: image/jpeg;');
foreach ($http_response_header as $h) {
if (strpos($h, 'Content-Length:') === 0) {
header($h);
break;
}
}
fpassthru($fp);
Another alternative would be to use some of the various built in functions for generating / manipulating images - in the case of the code below it is for a png but similar functions exist for jpg,gif and bmp.
Using a url as the filepath relies upon that setting being enabled by your host ( on dev obviously you control whether it is enabled or not )
Using these functions also gives you the possibility to add your own text at runtime, combine images and all sorts of other cool things.
<?php
if( ini_get( 'allow_url_fopen' ) ){
$imgPath='http://localhost/images/filename.png';
} else {
$imgPath=realpath( $_SERVER['DOCUMENT_ROOT'].'/images/filename.png' );
}
header("Content-type: image/png");
$image = imagecreatefrompng($imgPath);
imagesavealpha($image,true);
imagealphablending($image,true);
imagepng($image);
imagedestroy($image);
?>
I'm trying to load an image, edit it, save it and then display it from a script that is called within IMG tags. The script works if I want to just display the image and it does save the image. But it won't save it and then display it. Does anyone know what I'm doing wrong? Any help would be greatly appreciated.
<?php
header('Content-Type: image/png');
$file_location = "test.png";
if (file_exists($file_location)) {
$img_display = #imagecreatefrompng($file_location);
// This section of code removed as doesn't affect result
imagepng($img_display, $file_location);
chmod($file_location, 0777);
imagepng($img_display);
imagedestroy($img_display);
}
?>
Try this and checks if your folder has permission to save the image. chmod 777 on it for sure.
<?php
header('Content-Type: image/png');
$file_location = "test.png";
if (file_exists($file_location)) {
$img_display = imagecreatefrompng($file_location); // Create PNG image
$filename = $file_location + time(); // Change the original name
imagepng($img_display, $filename); // Saves it with another name
imagepng($filename); // Sends it to the browser
imagedestroy($img_display); // Destroy the first image
imagedestroy($filename); // Destroy the second image
}
Try this:
ob_start();
imagepng($img_display);
$contents = ob_get_clean();
file_put_contents($file_location, $contents);
echo $contents;
imagedestroy($img_display);
I am trying to use header('Content-type: image/jpeg') to edit and display jpeg photos as follows.
header('Content-type: image/jpeg')
$filename = 'aaa.jpg';
$im = imagecreatefromjpeg($filename);
imagefilter($im, IMG_FILTER_CONTRAST,50);
imagejpeg($im);
imagedestroy($im);
In the same file,I also have other simple codes like $abc = $_POST['abc'].
After I put the header, code before the header and code after image destroy($im) no longer work. And when I put any code such as $_post['abc'] before the header, both header and code doesn't work. All codes were fine before I included header and code to manipulate and output image. It is my first time using header('Content-type: image/jpeg') and I cannot find the answer after trying for so long. Please help. Thank you.
If you want to output html page, do not send image header. But instead, at first output the transformed image to a file on your server and add the <img> or <a>nchor tag in your html page:
<html><body>
<?php
$output_dir = 'images';
if (!file_exists($output_dir)) {
mkdir($output_dir, 0777);
}
$filename = 'aaa.jpg';
$filename2 = 'aaa2.jpg';
if (!file_exists($filename)) {
echo 'Input image not exists!'; exit;
}
$im = imagecreatefromjpeg($filename);
imagefilter($im, IMG_FILTER_CONTRAST, 50);
imagejpeg($im, $output_dir.'/'.$filename2);
imagedestroy($im);
echo 'Original image:<br/><img src="'.$filename.'" /><br/>';
echo 'Transformed image:<br/><img src="'.$output_dir.'/'.$filename2.'" />';
?>
</body></html>
That image header send in case, you want to output it as standalone image. For more examples have a look at php.net.
I currently have it working so it displays a dialogue box to save the image on your computer:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=".$_GET['name']);
echo $jpg;
}
just wondered if there is any way to put the file straight into a directory/file without the need of a dialogue box?
like an uploader?
No, there is not.
Just Read the content of the page and save in a file using fopen , fwrite e.t.c.
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
ob_start();
header('Content-Type: image/jpeg');
echo $jpg;
$image=ob_get_clean();
//and here write it into file
}
OR following is my code you can remove unneccessary things that are not useful for you
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$im = $GLOBALS["HTTP_RAW_POST_DATA"];
$filename=$_GET['name'];
$fullFilePath='files/'.$filename;
$handle=fopen($fullFilePath,"w");
fwrite($handle,$im);
fclose($handle);
$returnVars = array();
$returnVars['write'] = "yes";
$returnString = http_build_query($returnVars);
//send variables back to Flash
echo $returnString;
}