I want to save the email body (the content of email) in tiff format
I am able to download and save it as txt with:
$data = imap_qprint(imap_body($imap, $num));
file_put_contents($folder.$timestamp, $data);
but I want to save it in tiff and the Format of the content should remain exactly as it is.
Any Ideas how to do it in PHP? Thanks.
Assuming you have ImageMagick installed:
$txt = $folder . $timestamp;
$tiff = $txt . '.tiff';
$cmd = sprintf("convert text:%s %s 2> /dev/null", $txt, $tiff);
exec($cmd, $output, $return_var);
$return_var == 0 or die("Conversion failed\n");
I think there are a lot of other ways tough.
Related
I have created web service (client) in PHP (which uses SOAP protocol) that downloads list of ID's for users that want receive messages.
Now they've changed system (on server side) of delivering list of ID's. They have split xml list of more than 200000 ID's in 7 files and encoded them in base64 and compressed in zip file. I have managed to download every file via my PHP client, decode them from base64, then I have created UTF-8 zip file and wrote contents of message in it as you can see in part of my script here:
<?php
$obj = array('PinsCcIdsAsXmlZipBase64' => "", 'EmptyPage' => FALSE);
$PageNum=0;
while(!$obj['EmptyPage']){
$obj=Send_SOAP_mssg($TipPoruke,$SERVICE_TEST,$SOAP_cert,$NAMESPACE_URI,$cert_password,$ServiceId,$PageNum,$obj);
$zip_file=$OIB_path . 'PinListOfUsersThatDontHavePersonalization' . $PageNum . '.zip';
$f=fopen($zip_file,"wb")or die("Unable to open file!");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$obj['PinsCcIdsAsXmlZipBase64']);
fclose($f);
$zip = new ZipArchive;
$res = $zip->open($zip_file);
if ($res === TRUE) {
$zip->extractTo("C:\\xampp\\htdocs\\NIAS\\OIB\\");
$zip->close();
echo 'Success!';
} else {
echo 'ERROR! ' . $res ;
}
$PageNum++;
}
function Send_SOAP_mssg($TipPoruke,$SERVICE_TEST,$SOAP_cert,$NAMESPACE_URI,$cert_password,$ServiceId,$PageNum,$obj){
$client->__getLastRequest();
$xml=$client->__getLastResponse();
$doc = new DOMDocument();
$doc->loadXML( $xml );
$SOAPRequest = $doc->getElementsByTagName( "EmptyResultSet" );
if ($SOAPRequest->length!=0){
$obj['EmptyPage'] = TRUE;
return $obj;
}
else{
$SOAPRequest = $doc->getElementsByTagName( "PinsCcIdsAsXmlZipBase64" );
$obj['PinsCcIdsAsXmlZipBase64'] .= base64_decode($SOAPRequest->item(0)->nodeValue);
$obj['EmptyPage'] = FALSE;
return $obj;
}
}
?>
Problem occurs when I try to extract content of zip files. I got error 19 (Not a zip archive) as a result of this function
$res=$zip->open($zip_file);.
Same goes for manually extracting file
except extracting it with 7-zip, then I don't have errors.
In this code:
$obj['PinsCcIdsAsXmlZipBase64'] .= base64_decode($SOAPRequest->item(0)->nodeValue);
// ...
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$obj['PinsCcIdsAsXmlZipBase64']);
base64_decode gives you a binary result, this zip content. The Now UTF-8 comment is false: you have a binary string, the actual zip file. You do not need to add the BOM:
$ php -a
Interactive shell
php > $content = base64_decode("UEsDBAoAAAAAADiaeEkAAAAAAAAAAAAAAAAFABwAYS50eHRVVAkAA8suN1jLLjdYdXgLAAEE6AMAAAToAwAAUEsBAh4DCgAAAAAAOJp4SQAAAAAAAAAAAAAAAAUAGAAAAAAAAAAAAKSBAAAAAGEudHh0VVQFAAPLLjdYdXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEASwAAAD8AAAAAAA==");
php > $f=fopen("a.zip","wb");
php > fwrite($f,$content);
php > fclose($f);
That gives me a correct zip file.
A zip file uses offsets to find its internal structures. If you prepend bytes, these offsets are now wrong: you have a corrupted zip file. 7zip tries (and succeeds) to find the correct value but ZipArchive and Windows Compressed Folders don't seem to do that.
I encode a file with a special watermark for be downlaoded by the user
I would like to be able to start the downlaod when ffmpeg encode the file.
I have a php page which one create the water mark , launch ffmpeg and start the download with X-sendifle
The download don't start, adding sleep(15) let's the download start just I receive only what is done
Actually I use Apache2 as the webserver with X-sendfile mod
Okay I finally find how to do
Using X-sendfile it's a wrong idea
Using mp4 it's a wrong idea because at the end of the encodage the software rewrite 4 bytes at the beginning of the file
So this is the code I use for be able to send a file like webm or flv files when ffmpeg encode the output
shell_exec('ffmpeg command');
sleep(2); //wait few second for the software start
$foutput ="where/is/your/output.file";
header('Content-Disposition: attachment; file.name.for.the.user"');
header("Keep-Alive:timeout=200, max=500");
//sending by chunk
set_time_limit(3600);
$file =fopen($foutput , 'r');
$files = fstat($file);
$filesize= $files['size'];
$last = 0;
echo fread($file , $filesize);
sleep(5); //wait a little for the software add new bytes
$last = $filesize;
$files = fstat($file);
$filesize= $files['size'];
$done =0;
while( $done < 2 ){
if ($filesize != $last){
fseek($file , $last);
$read = $filesize - $last ;
echo fread($file , $read);
$last =$filesize;
sleep(5);
$files = fstat($file);
$filesize= $files['size'];
}else{
fclose($file);
return 0;
};
};
I'm a noob for coding and got a problem with my "while" just the code work really good without any issue
Do not use filesize , this command don't like when a file change of size all time and return only 4096 in that case
The download will be slow , this is normal , you receive chunk by chunk what the software done like with ffmpeg the transfer is between 200 to 1200 kb/s
My hosting does not have ffmpeg's silenceremove filter, so I'm trying to remove the beginning and end silence of an audio file with silencedetect then cut. I'm trying to do this programmatically with php. At this point, I can't even detect the silence. I've tried:
define('UPLOAD_DIR', $_SERVER['DOCUMENT_ROOT'].'/audiofiles/');
$filein = UPLOAD_DIR . "music.ogg";
$fileout = UPLOAD_DIR . "music_no_silence.ogg";
$fileouttxt = UPLOAD_DIR . "music_log.txt";
$ffmpeg = "/usr/local/ffmpeg/bin/ffmpeg";
I first tried to put the ffmpeg command into a variable and then tried to access the output but was unable:
$output = shell_exec("$ffmpeg -i $filein -af silencedetect=n=-50dB:d=1");
echo $output;
I then tried to create a.txt log of the conversion but the .txt file doesn't show anything about the silencedetect. Furthermore, how would I be able to extract the info that I need programmatically from the .txt log in order to use it in php?
shell_exec("$ffmpeg -i $filein -af silencedetect=n=-50dB:d=1 $fileout 2> $fileouttxt");
I'm basically trying to adapt the answer at https://stackoverflow.com/a/25698675 into php
Edit: Here's kind of a hack way to do it:
define('UPLOAD_DIR', $_SERVER['DOCUMENT_ROOT'].'/audiofiles/');
$filein = UPLOAD_DIR . "music.ogg";
$fileout1 = UPLOAD_DIR . "music_out1.ogg";
$fileout2 = UPLOAD_DIR . "music_out2.ogg";
$ffmpeg = "/usr/local/ffmpeg/bin/ffmpeg";
$command = "$ffmpeg -i $filein -filter_complex silencedetect=n=-10dB:d=0.5 -y $fileout1 2>&1";
$output = array();
exec($command,$output);
$searchword1 = 'silence_end';
$endmatches = array_filter($output, function($var) use ($searchword1) {return preg_match("/\b$searchword1\b/i", $var);});
$endmatches = array_values($endmatches);
$parts1 = explode(" ",$endmatches[0]);
$a = $parts1[4];
$a = $a-.5;
$searchword2 = 'silence_start';
$startmatches = array_filter($output, function($var) use ($searchword2) {return preg_match("/\b$searchword2\b/i", $var);});
$startmatches = array_values($startmatches);
$parts2 = explode(" ",end($startmatches));
$b = $parts2[4];
$b = $b+.5;
$c = $b-$a;
exec("$ffmpeg -i $fileout1 -ss $a -t $c -y $fileout2 && rm $fileout1");
PHP's shell_exec returns the output written to stdout and ffmpeg writes the messages to stderr. If you want to use shell_exec you must redirect the stderr output to stdout using 2>&1.
You also need to specify at least one output file for ffmpeg, in this case /dev/null.
set_time_limit(0);
$input_file = 'music.ogg';
$cmd = "ffmpeg -i {$input_file} -af silencedetect=n=-50dB:d=1 -f null /dev/null 2>&1";
$output = shell_exec($cmd);
if (preg_match_all("/^\[silencedetect\s[^]]+\]\s([^\n]+)/m", $output, $matches)) {
var_export($matches[1]);
}
An alternative is to use proc_open and stream_get_contents.
I have a very simple PHP script that calls shell_exec to start a 3rd party application.
No matter what application I try to run (including notepad.exe),
if the script contains the call to shell_exec, the script is called multiple times,
if the script doesn't contain this call, it runs just once.
I can provide any source code needed, let me know what do you want to see, I just absolutely don't know where to look.
Windows 2008 R2, PHP 5.5.1, IIS 7.5, Amazon EC2 server
And no, there isn't any loop inside the script, because I have placed
file_put_contents('log.txt', $_SERVER['REQUEST_URI'], FILE_APPEND);
as the first script row and I can see it written multiple times in the log.
EDIT:
It doesn't happen on my local host. And it happens with exec also.
PHP script stripped down to bare minimum:
<?php
//Report any errors
ini_set("MAX_EXECUTION_TIME", "-1");
ini_set('max_input_time', -1);
ini_set ("display_errors", "1");
error_reporting(E_ALL);
require_once('PhpConsole.php');
PhpConsole::start(true, true, dirname(__FILE__));
function writeLog($content, $logname)
{
$temp = $content ." at " .date("D M j G:i:s T Y") ."\r\n";
$f = fopen($logname, 'a+');
fwrite($f,$temp,strlen($temp));
fclose($f);
}
function createBackground()
{
//Set the correct content type
header('content-type: image/png');
//Create our basic image stream 225px width, 225px height
$image1 = imagecreate(1362, 762);
// Set the background color
$white = imagecolorallocate($image1, 255, 255, 255);
// Save the image as a png and output
imagepng($image1, "saves/back.png");
// Clear up memory used
imagedestroy($image1);
}
function buildFramesSequence()
{
array_map('unlink', glob("saves/*"));
array_map('unlink', glob("*.mp4"));
unlink("list.txt");
$url = realpath('') ."/" .$_GET["jfile"] ;
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$noOfFrames = count( $results['ani']);
$lastframe = "saves/back.png";
createBackground();
$elements = createElements($results['pre']);
$frame_elements = array();
$prev_element = null;
for ($i = 0; $i <$noOfFrames; $i++)
{
$format = 'image%1$05d.png';
$imgname = sprintf($format, $i);
copy($lastframe, "saves/" .$imgname);
}
}
function createVideo()
{
writeLog("before build", "log.txt");
buildFramesSequence();
writeLog("after build", "log.txt");
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$localpath1 = realpath('') ."/ffmpeg/ffmpeg.exe";
} else {
$localpath1 = "ffmpeg";
}
$localpath2 = realpath('') ."/saves/image%05d.png";
$mp3name = $_GET["mfile"];
$localpath3 = realpath('') ."/" .$mp3name;
$temp = substr($mp3name, 0, -1);
$localpath4 = realpath('') ."/" .$temp ."4";
writeLog(" before ffmpeg", "log.txt");
$output = shell_exec("notepad.exe");
// $output = shell_exec("ffmpeg $localpath1 .' -f image2 -r 20 -i ' .$localpath2 .' -i ' .$localpath3 .' -force_fps ' .$localpath4. ' 2>&1 &');
// exec("notepad.exe", $output = array());
// debug($output);
writeLog($localpath4, "list.txt");
return $output;
}
file_put_contents('log.txt', $_SERVER['REQUEST_URI'], FILE_APPEND);
set_time_limit(0);
$output = createVideo();
echo $output;
?>
This is a very strange issue that still happens to this day with exec() system() shell_exec() etc. If your command creates a file the quickest solution is to check whether that file exists, like so:
[ -f path/file.mp4 ] || #Your command here#
This checks whether the file path/file.mp4 exists, if not, the second condition runs, which is your command. To check the opposite use the ampersand, like so:
[ -f path/file.mp3 ] && #Command here#
I'm not sure if anyone is still having problems with this, but maybe yours is the same issues that I just had. I was creating a file with exec, and appending a datetime stamp to it.
I was ending up with 5 files. Turns out, because I was redirecting all calls to my index.php thru htaccess, then when I had some images that were directing to relative path assets/images/image.jpg, then it would redirect that thru my index page and call my script multiple times. I had to add a slash to the image path: /assets/images/image.jpg.
Hope this help someone.
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");