Print PDF file in PHP using sockets - php

I want to print PDF file using sockets (because of script speed). I found this on other thread:
<?php
if(($conn = fsockopen('192.168.10.112',9100,$errno,$errstr))===false){
echo 'Connection Failed' . $errno . $errstr;
}
$data = <<<HERE
^XA
^FT50,200
^A0N,200,200^FDTEST^FS
^FT50,500
^A0N,200,200^FDZebra Printer^FS
^XZ
HERE;
#send request
$fput = fputs($conn, $data, strlen($data));
#close the connection
fclose($conn);
?>
How to print PDF file using this method?

What it appears you're doing here is connecting directly to a network printer.
You should be able to print a file this way. Lets say you have file.pdf, then you can do this:
fputs($conn, file_get_contents('file.pdf'), filesize('file.pdf'));

Related

fopen(w+): failed to open stream

I'm currently creating a quote which has values that can be changed. It requires PDF conversion.
This conversion is done using wkhtmltopdf, unfortunately the old way I used did not convert the changed values and that is why my script is changed.
However it fails at line 7:
$fp = fopen('w+','/tmp/tmp.html');
The complete script:
<?php
try {
$content = $_REQUEST['content'];
if(!file_exists('/tmp') ){
mkdir('/tmp', 0777);
}
$fp = fopen('w+','/tmp/tmp.html');
if($fp){
fwrite($fp, $content);
fclose($fp);
$filename = '/tmp/out_' . time() .'.pdf'; // output filename
shell_exec('wkhtmltopdf /tmp/tmp.html ' . $filename);
//then eventually ask user for download the result
header("Content-type:application/pdf");
// It will be called output.pdf
header("Content-Disposition:attachment;filename='output.pdf'");
readfile($filename);
}else{
echo 'html file could not be created';
}
} catch (Exception $e) {
echo 'exception: ', $e->getMessage(), "\n";
}
//
I hope anyone could tell me what I'm doing wrong.
If more info is necessary, let me know.

localhost (at custom port) returns empty data after POST request

I am trying to use a PHP to read data from the local server localhost, but it seems no data is returned from it. Here is my full script.
<?php
$address = "localhost";
echo "Attempting to open the socket at ".$address."...\n";
$fp = fsockopen($address, 49801, $errno, $errstr, 10);
echo "Error number is "; echo $errno; echo ".\n";
echo "Error string is ".$errstr.".\n";
echo "Attempt complete.\n";
if ($fp) {
print "Socket in now open.\n";
syslog(LOG_INFO, "socket.php: Reaching the specified address...");
print "Writing requests...\n"; //Hangs for about 1-2 minutes
fwrite($fp, "POST / HTTP/1.0\r\nUser-Agent: PHP XMLRPC 1.0\r\nHost: ".$address."Content-Type: text/xml\r\nContent-Length: ".strlen($payload)."\r\n\r\n");
$msg = "";
while($data = fread($fp, 32768)) {
$msg= $msg.$data;
}
if (strlen($msg) != 0) {
print "Final message: ***".$msg."***\n";
} else {
print "There is no data received from '".$address."'\n";
}
fclose($fp);
} else {
print "Error\n";
}
?>
Here is the output I am getting in the terminal:
Attempting to open the socket at localhost...
Error number is 0.
Error string is .
Attempt complete.
Socket in now open.
Writing requests...
There is no data received from 'localhost'
As mentioned in the script above, the second last line Writing requests... hangs for about 1 or 2 minutes, then an empty string is appended.
I think it is rather curious because this script works well on HTTP's port 80 or on SSH's port 22. I have restricted access to localhost:49801's configuration, and thus am not able to make any changes to the server's config.
I was however wondering if something was wrong with the server's config so that I don't have to tear out my hair for another day.
By the way, I am running PHP 5.4 on CentOS 7.
Edit
The '111' in "Content-Length: 111" is an arbitrary number that depends on the payload's string length.
Thanks your your help!
You got no reply from your server because he is waiting 111 bytes of data from you.
if you send the right amount of data to your server he will respond accordingly.
Below is working example where I change the Content-Length to 9
and then I send the 9 bites of data using fwrite:
<?php
$address = "localhost";
$payload = "Some data";
echo "Attempting to open the socket at ".$address."...\n";
$fp = fsockopen($address, 49801, $errno, $errstr, 10);
echo "Error number is "; echo $errno; echo ".\n";
echo "Error string is ".$errstr.".\n";
echo "Attempt complete.\n";
if ($fp) {
print "Socket in now open.\n";
syslog(LOG_INFO, "socket.php: Reaching the specified address...");
print "Writing requests...\n";
fwrite($fp, "POST / HTTP/1.0\r\nUser-Agent: PHP XMLRPC 1.0\r\nHost: ".$address.
"\r\nContent-Type: text/xml\r\nContent-Length: ". strlen($payload) ."\r\n\r\n");
//We send the data to the server
fwrite($fp, $payload);
$msg = "";
while($data = fread($fp, 32768)) {
$msg= $msg.$data;
}
if (strlen($msg) != 0) {
print "Final message: ***".$msg."***\n";
} else {
print "There is no data received from '".$address."'\n";
}
fclose($fp);
} else {
print "Error\n";
}
?>

php file download sometimes not working (gzopen, gzwrite, gzclose)

<?php
set_time_limit(0);
$myfile = gzopen($constpath . '.gz', 'w');
if (!$myfile){
throw new \UnexpectedValueException('could not open datafeed.gz file');
}
$mystream = gzopen($constURL, 'r');
if (!$mystream){
throw new \UnexpectedValueException('could not open gzip remote file');
}
echo '1<br>';
while (!gzeof($mystream)){
$data = gzread($mystream, 8096);
gzwrite($myfile, $data);
}
echo '4<br>';
gzclose($mystream);
gzclose($myfile);
echo '5<br>';
echo 'down done';
//begin ungzip
$fp = fopen($constpath . '.csv', 'w');
$gz = gzopen($constpath . '.gz', 'r');
if (!$gz){
throw new \UnexpectedValueException(
'could not open gzip file'
);
}
if (!$fp){
gzclose($gz);
throw new \UnexpectedValueException(
'could not open destination file'
);
}
while (!gzeof($gz)) {
fwrite($fp, gzread($gz, 8096));
}
gzclose($gz);
fclose($fp);
echo 'ungzip done';
?>
Hi,
guys so above is my code, it intermittently allows me to download the gz file then unzip it, however it does not seem to be doing this in any sort of pattern or anything else, is there anything i need to know about how to use these functions like maybe is there a limit on the URL length (it's currently about 2.5K characters) but unfortunately not something i can change. what would people recommend on how to debug if there're bugs? or what i can do?
thanks!
EDIT: something i've noticed is that it is taking an absolute age to create a 25kB file, and previous to that it is 0kB, it then stops at 25kB
when i open the file in nano i get
^_�^H^#^#^#^#^#^#^C^#^#^#��^C^#^#^#^#^#^#^#^#^#
but when i unzip and open in windows there is nothing there?

Unable to fread output of a remote php file

I am using the output of a php file on a remote server, to show content on my own web-site. I do not have access to modify files on the remote server.
The remote php file outputs java script like this:
document.write('<p>some text</p>');
If I enter the url in a browser I get the correct output. E.g:
https://www.remote_server.com/files/the.php?param1=12
I can show the output of the remote file on my website like this:
<script type="text/javascript" src="https://www.remote_server.com/files/the.php?param1=12"></script>
But I would like to filter the output a bit before showing it.
Therefore I implemented a php file with this code:
function getRemoteOutput(){
$file = fopen("https://www.remote_server.com/files/the.php?param1=12","r");
$output = fread($file,1024);
fclose($file);
return $output;
}
When I call this function fopen() returns a valid handle, but fread() returns an empty string.
I have tried using file_get_contents() instead, but get the same result.
Is what I am trying to do possible?
Is it possible for the remote server to allow me to read the file via the browser, but block access from a php file?
Your variable $output is only holding the 1st 1024 bytes of the url... (headers maybe?).
You will need to add a while not the "end of file" loop to concatenate the entire remote file.
PHP reference: feof
You can learn a lot more in the PHP description for the fread function.
PHP reference: fread.
<?php
echo getRemoteOutput();
function getRemoteOutput(){
$file = fopen("http://php.net/manual/en/function.fread.php","r");
$output = "";
while (!feof($file)){ // while not the End Of File
$output.= fread($file,1024); //reads 1024 bytes at a time and appends to the variable as a string.
}
return $output;
fclose($file);
}
?>
In regards to your questions:
Is what I am trying to do possible?
Yes this is possible.
Is it possible for the remote server to allow me to read the file via
the browser, but block access from a php file?
I doubt it.
I contacted the support team for the site I was trying to connect to. They told me that they do prevent access from php files.
So that seems to be the reason for my problems, and apparently I just cannot do what I tried to do.
For what it's worth, here is the code I used to test the various methods to read file output:
<?php
//$remotefile = 'http://www.xencomsoftware.net/configurator/tracker/ip.php';
$remotefile = "http://php.net/manual/en/function.fread.php";
function getList1(){
global $remotefile;
$output = file_get_contents($remotefile);
return htmlentities($output);
}
function getList2(){
global $remotefile;
$file = fopen($remotefile,"r");
$output = "";
while (!feof($file)){ // while not the End Of File
$output.= fread($file,1024); //reads 1024 bytes at a time and appends to the variable as a string.
}
fclose($file);
return htmlentities($output);
}
function getList3(){
global $remotefile;
$ch = curl_init(); // create curl resource
curl_setopt($ch, CURLOPT_URL, $remotefile); // set url
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //return the transfer as a string
$output = curl_exec($ch); // $output contains the output string
curl_close($ch); // close curl resource to free up system resources
return htmlentities($output);
}
function getList4(){
global $remotefile;
$r = new HttpRequest($remotefile, HttpRequest::METH_GET);
try {
$r->send();
if ($r->getResponseCode() == 200) {
$output = $r->getResponseBody();
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return htmlentities($output);
}
function dumpList($ix, $list){
$len = strlen($list);
echo "<p><b>--- getList$ix() ---</b></p>";
echo "<div>Length: $len</div>";
for ($i = 0 ; $i < 10 ; $i++) {
echo "$i: $list[$i] <br>";
}
// echo "<p>$list</p>";
}
dumpList(1, getList1()); // doesn't work! You cannot include/requre a remote file.
dumpList(2, getList2());
dumpList(3, getList3());
dumpList(4, getList4());
?>

how to save a local copy of xml being output by certain website

I want to save a local copy of xml being ouput by a certain website, and everytime I changed the URL of a website to get another copy of xml it will overwrite the file that saved from previous website, how can I do this in php?
$xml = file_get_contents('http://example.com/file.xml');
file_put_contents('file.xml', $xml);
Thanks! Is there a problem using that script if the generated xml of the URL is so huge about 50MB?
Here's my code please take a look tell me if it is okay.
$url = "http://projects.com/read.php";
$fp = fopen($url, 'r');
if ($fp) {
while (!feof($fp))
$buffer .= fgets($fp, 1024);
fclose($fp);
file_put_contents('file.xml', $buffer);
} else {
echo 'Could not connect to: ' . htmlentities($url) . '<br />';
echo 'Error #' . $err_num.': ' . $err_msg;
exit;
}

Categories