Problem while printing a pdf using base64 decoding in PHP - php

I'm trying to create a PHP program which prints a pdf which is encoded in Base64 to any kind of printer.
I already got the decoding done and the base64 pdf is being converted to a real PDF. However when I send the decoded Base64 to the printer it prints out the decoded string and not a PDF.
My code:
Printer ip is disabled for development
<?php
error_reporting(E_ALL);
$base64 = $_POST['fileBase64'];
$printer = $_POST['printer'];
printer('', 9100, $base64);
function printer($printerIp, $printerPort, $base64): void {
$docname = md5(date("Y-m-d-H-i-s-Z")) . '.pdf';
// Generate the pdf from the base64
//Decode pdf content
$pdf_decoded = base64_decode($base64);
//Write data back to pdf file
$pdf = fopen ($docname,'w');
fwrite ($pdf, $pdf_decoded);
//close output file
fclose ($pdf);
// echo file_get_contents($docname);
try {
$fp = pfsockopen($printerIp, $printerPort, $errno, $errstr);
if ($fp === false) {
echo 'Connection Failed! ' . $errno . ' ' . $errstr;
} else {
fputs($fp, file_get_contents($docname), filesize($docname));
fclose($fp);
echo "Successfully printed";
// If done then delete pdf and clear text file
exec("rm -rf '" . $docname . "'");
}
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
Output of file_get_contents():

Related

Cannot upload wav file on an Azure blob container using PHP

I need to upload audio files in wav format to an Azure container using the Azure SDK for PHP but the content of the wav does not upload. Indeed, I only have a 0 bytes .wav file in my container so i'm not able to use it.
I have tested several codes but this is the best one I have. I am not an expert in PHP but I force him to use this language to integrate it into a CRM.
When I load a text file it also uploads empty so the problem doesn't come from the way I read the file.
Thanks a lot for your help.
<?php
require_once 'vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
use MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
$connectionString = "DefaultEndpointsProtocol=https;AccountName=".getenv('ACCOUNT_NAME').";AccountKey=".getenv('ACCOUNT_KEY');
// Create blob client.
$blobClient = BlobRestProxy::createBlobService($connectionString);
$fileToUpload = "audio.wav";
if (!isset($_GET["Cleanup"])) {
$containerName = "cs-blob-input";
try {
// Getting local file so that we can upload it to Azure
$myfile = fopen($fileToUpload, "w") or die("Unable to open file!");
fclose($myfile);
# Upload file as a block blob
echo "Uploading BlockBlob: ".PHP_EOL;
$content = fopen($fileToUpload, "r");
//Upload blob
$blobClient->createBlockBlob($containerName, $fileToUpload, $content);
// List blobs.
$listBlobsOptions = new ListBlobsOptions();
echo "These are the blobs present in the container: ".PHP_EOL;
do{
$result = $blobClient->listBlobs($containerName, $listBlobsOptions);
foreach ($result->getBlobs() as $blob)
{
echo $blob->getName().PHP_EOL;
}
$listBlobsOptions->setContinuationToken($result->getContinuationToken());
} while($result->getContinuationToken());
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
catch(InvalidArgumentTypeException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/library/azure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
else
{
try{
// Delete container.
echo "Deleting Container".PHP_EOL;
echo $_GET["containerName"].PHP_EOL;
echo "<br />";
$blobClient->deleteContainer($_GET["containerName"]);
}
catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
?>
The problem is here:
// Getting local file so that we can upload it to Azure
$myfile = fopen($fileToUpload, "w") or die("Unable to open file!");
fclose($myfile);
What is happening is, you open a file "audio.wav" for writing.
Based on official docs (See the mode parameter 'w') your file will be created if it not exists. Then, if it exists, it will be truncated to zero size. Then you close the file.
After that you do:
$content = fopen($fileToUpload, "r");
Which reads an empty file. So the uploaded content is => 0 in size

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.

Print PDF file in PHP using sockets

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

How to Convert Text to Speech in PHP

How can I convert text to speech using PHP, possibly generating an MP3 file and sending that back to the user?
Thank You.
Probably following is the code as mentioned in the above link:
<?php
//create a random number filename so that simultaneous users don't overwrite each other
$filename = 'test.txt';
$text = 'This text will be converted to audio recording';
$outputfile = basename($filename, ".txt");
$outputfile = $outputfile . '.wav';
if (!$handle = fopen($filename, "w"))
{
//we cannot open the file handle!
return false;
}
// Write $text to our opened file.
if (fwrite($handle, $text) === FALSE)
{
//couldn't write the file...Check permissions
return false;
}
fclose($handle);
//initialise and execute the festival C engine
//make sure that your environment is set to find the festival binaries!
$cmd = "text2wave $filename -o $outputfile";
//execute the command
exec($cmd);
unlink($filename);
echo "Recording is successful. \nRecording File: " . $outputfile;
//finally return the uptput file path and filename
return $outputfile;
?>
if you use macos you can simply use apple tts
shell_exec("say -o test.aiff this is a test");

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