Output Contents of PHP File for a GET/POST request - php

I have a script which generates an XML file when the user accesses the link like so:
domain.com/dirList.php
I would like to print the contents of the XML to the user at the end of the POST or GET request (have not implemented this yet). At the moment I am just viewing the link through a web browser.
This is the code I am using to print the file contents.
# Open XML file and print contents
$filename = "test.xml";
$handle = fopen ($filename, "r");
$contents = fread ($handle, filesize ($filename));
fclose ($handle);
print $contents;
The problem is that it doesn't seem to be working. I think I might be either missing a header like this: ("Content-Type: text/xml"); or maybe my code is wrong.
What do I need to do to get the XML file to print to the browser?

You can just do:
header('Content-type: text/xml'); // set the correct MIME type before you print.
readfile('test.xml'); // output the complete file.

//Check there is any extra space before <? and after ?>
//or
header('Content-type: text/xml');
echo file_get_contents($path.$xmlfile);

Related

File throws an error on download

I'm generating a csv file for download using the following code.
/**#var array $results contains the results of an SQL query**/
$tmpFile = tmpfile(); //Create a temp file to write the csv to
fputcsv($tmpFile, array_keys($results[0])); //Write the column headers
foreach ($results as $result) { //write each row to the file
fputcsv($tmpFile, $result);
}
rewind($tmpFile); //Rewind the stream
$csv = stream_get_contents($tmpFile); //Get the file as text
fclose($tmpFile); //Done with the temp file.
//Set the download headers
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="testDownload.csv"');
//Output the content
echo $csv;
exit(0);
The download appears to start normally, but after a second I get a message in firefox, "[The file] could not be saved, because the source file could not be read." I've tested this with chrome/safari and have gotten similar results. I've also tested with some static content (not from the database) without success.
In the developer console, I can inspect the network request and see that it comes back with status 200 and if I inspect the response, I see the complete file. I can even copy/paste it into a text file and open it in excel.
Additionally, if I comment out the header() lines, the file contents display in the browser without issue.
The content is only ~2500 rows, no special characters.

Getting the content of an xml file creates an XML Parsing Error

I am trying to get the contents of an XML file in case that the file exists or I am generating a new xml file. The problem is that when I am trying to get the xml file I get this error:
XML Parsing Error: no element found Location:
http://mydomain.gr/generate.php Line Number 1, Column 1: ^
My code is this
<?php
include_once('xmlgenerator.php');
$xml = new XmlGenerator();
if($xml->cachefile_exists){
if(!$xml->is_uptodate()){
// echo "update it now";
$xml->createFile = 1;
$data = $xml->create();
Header('Content-type: text/xml');
print($data->asXML());
}else{
//echo "doesn't need any update.";
Header('Content-type: text/xml');
file_get_contents($xml->cached_file);
}
}else{
// echo "Didn't find any cache file. Lets Create it";
$xml->createFile = 1;
$data = $xml->create();
Header('Content-type: text/xml');
print($data->asXML());
}
?>
The XML structure is fine, and I double check about the XML file encoding or the php file that call the XML. Everything is UTF8 without BOM. When I open the XML file directly in a browsers it looks perfect and its a valid file ( checked it with w3c and online tools).
the 2 lines that create the problem(most probably):
Header('Content-type: text/xml');
file_get_contents($xml->cached_file)
I even deleted anything and just used this 2 lines and got the same error.
So what can be wrong? Is there any proper way to include an XML file in a php file, change the headers and show it to the end user? I really don't want to redirect, I need to stay to the same php file just show XML content.
echo file_get_contents($xml->cached_file)

PHP efficiently write and output csv files using fputcsv

When writing .csv files i use fputcsv like this:
- open a temporary file $f = tmpfile();
- write content to file using fputcsv($f,$csv_row);
- send appropriate headers for attachment
- read file like this:
# move pointer back to beginning
rewind($f);
while(!feof($f))
echo fgets($f);
# fclose deletes temp file !
fclose($f);
Another aproach would be:
- open file $f = fopen('php://output', 'w');
- send appropriate headers for attachment
- write content to file using fputcsv($f,$csv_row);
- close $f stream
My question is: What would be the best approach to output the data faster and taking into account server resources ?
First method would use more writes and consume more resources but would output very fast.
Second method uses less writes and would output slower i think.
Eagerly waiting for your opinions on this.
Thanks.
fpassthru() will do what you're doing at a lower level. Use it like this:
# move pointer back to beginning
rewind($f);
while(fpassthru($f) !== false);
# fclose deletes temp file !
fclose($f);
Even though it may be a csv file, there is no need to restrict yourself to csv functions, unless you are generating the file at the time of output.
You could probably see a performance gain if you stream the CSV to output instead of to a file.
Why do you need to write the csv content to a tmp file/php's output stream ?
You just need to echo the csv content directly, there should not be any file operations.
send appropriate headers for attachment
echo the csv content.
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
foreach ($csv_rows as $csv_row) {
echo $csv_row;
}
exit;

A php file as img src

i want to print a image by using a img tag which src is a php file, the script will also process some action at server scirpt. Anyone have an example code?
here is my test code but no effect
img.html
<img src="visitImg.php" />
visitImg.php
<?
header('Content-Type: image/jpeg');
echo "<img src=\"btn_search_eng.jpg\" />";
?>
Use readfile:
<?php
header('Content-Type: image/jpeg');
readfile('btn_search_eng.jpg');
?>
Directly from the php fpassthru docs:
<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
?>
As an explanation, you need to pass the image data as output from the script, not html data. You can use other functions like fopen, readfile, etc etc etc
"<img src=\"btn_search_eng.jpg\" />" is not valid image data. You have to actually read the contents of btn_search_eng.jpg and echo them.
See here for the various ways to pass-through files in PHP.
UPDATE
what you can do without using include as said below in the comments:
try this:
<?
$img="example.gif";
header ('content-type: image/gif');
readfile($img);
?>
The above code is from this site
Original Answer
DON'T try this:
<?
header('Content-Type: image/jpeg');
include 'btn_search_eng.jpg'; // SECURITY issue for uploaded files!
?>
If you are going to use header('Content-Type: image/jpeg'); at the top of your script, then the output of your script had better be a JPEG image! In your current example, you are specifying an image content type and then providing HTML output.
What you're echoing is HTML, not the binary data needed to generate a JPEG image. To get that, you'll need to either read an external file or generate a file using PHP's image manipulation functions.
if you use base64 it would be
<?php
header('Content-Type: image/jpeg');
echo(base64_decode('BASE64ENCODEDCONTENT'));
?>

send a file to client

I want to write a text file in the server through Php, and have the client to download that file.
How would i do that?
Essentially the client should be able to download the file from the server.
This is the best way to do it, supposing you don't want the user to see the real URL of the file.
<?php
$filename="download.txt";
header("Content-disposition: attachment;filename=$filename");
readfile($filename);
?>
Additionally, you could protect your files with mod_access.
In addition to the data already posted, there is a header you might want to try.
Its only a suggestion to how its meant to be handled, and the user agent can chose to ignore it, and simply display the file in the window if it knows how:
<?php
header('Content-Type: text/plain'); # its a text file
header('Content-Disposition: attachment'); # hit to trigger external mechanisms instead of inbuilt
See Rfc2183 for more on the Content-Disposition header.
PHP has a number of very simplistic, C-like functions for writing to files. Here is an easy example:
<?php
// first parameter is the filename
//second parameter is the modifier: r=read, w=write, a=append
$handle = fopen("logs/thisFile.txt", "w");
$myContent = "This is my awesome string!";
// actually write the file contents
fwrite($handle, $myContent);
// close the file pointer
fclose($handle);
?>
It's a very basic example, but you can find more references to this sort of operation here:
PHP fopen
If you set the content type to application/octet-stream, the browser will ALWAYS offer file as a download, and will never attempt to display it internally, no matter what type of file it is.
<?php
filename="download.txt";
header("Content-type: application/octet-stream");
header("Content-disposition: attachment;filename=$filename");
// output file content here
?>
Just post a link on the site to http://example.com/textfile.php
And in that PHP file you put the following code:
<?php
header('Content-Type: text/plain');
print "The output text";
?>
That way you can create the content dynamic (from a database)...
Try to Google to oter "Content-Type" if this one is not the one you are looking for.

Categories