WkHtmlToPdf Passing Variables via shell_exec() - php

Here is a sample of my script
$clientid = $_POST['clientid'];
$from_day = $_POST['stat_from_day'];
$from_month = $_POST['stat_from_month'];
$from_year = $_POST['stat_from_year'];
$to_day = $_POST['stat_to_day'];
$to_month = $_POST['stat_to_month'];
$to_year = $_POST['stat_to_year'];
$from_date_string = $from_day . ' ' . $from_month . ' ' . $from_year ;
$to_date_string = $to_day . ' ' . $to_month . ' ' . $to_year ;
$baseurl = "http://www.test.com/";
$part1 = "?Search=" . $clientid . " from_day=" . $from_day . " from_month=" . $from_month . " from_year=" . $from_year ;
$part2 = " to_day=" . $to_day . " to_month=" . $to_month . " to_year=" . $to_year ;
$time = mktime();
$formatted_time = date("d_M_Y", $time);
$command = "xvfb-run -a /usr/bin/wkhtmltopdf --ignore-load-errors";
$url = $baseurl . $part1 . $part2 ;
$html = file_get_contents($url);
$output_dir = '/var/www/stats/pdf/';
$output = $clientid . '_Search_Export_' . $formatted_time . rand(10000, 99999) . '.pdf';
$generate = shell_exec($command . ' ' . $url . ' ' . $output_dir . $output) ;
The problem i seem to be having is with the $command, basically when it runs wkHTMLtoPDF it runs it via a Command Line, and &variable= bit causes the script to error as via command line & is another command, my question is how do i get the variables to be passed correctly so that the script this then sends to, will be able to use $_GET variables that i require for the script to then work ?
I have done a bit of looking up and found something along the lines of using $argv1;
Replacing $_GET to make it work from command line
However i cannot seem to find a reference that closely matches my needs.

Change this:
$url = $baseurl . $part1 . $part2 ;
To this:
$url = "\" . $baseurl . $part1 . $part2 . "\";

Actually wkhtmltopdf accepts and passes POST data to the server-side page being printed/exported to pdf.
All you need is --post fieldName value.
xvfb-run -a /usr/bin/wkhtmltopdf --ignore-load-errors --post username blablabla --post bla2 answer2
You can have as many as that in the command to pass as many post parameters as you want

Related

Exec Command is not working in sql server

I am working on database migration. I have written a code for executing the command that retrieves the data from database and pushes into a csv file. This Works fine in MySQL but when I try to do the same in SQL Server it does not work. Infact when I copy paste the same command into command prompt it works fine. I double checked everything. I do not understand why its not working. It returns blank output. I have already tried many of the solutions provided before. None works. Any help on this is most appreciated.
Here is the code I am using:
//$sqlsrv is used to determine the database server type
$str_query = voc_get_query_string($query);
$output_uri = 'temporary://' . user_password();
$file_path = drupal_realpath($output_uri . '.csv');
if($sqlsrv){
$exec_path = drupal_realpath('private://Binn\sqlcmd');
}else{
$exec_path = drupal_realpath('private://mysql');
}
$sql_uri = 'temporary://' . user_password();
$sql_path = drupal_realpath($sql_uri);
$fp = fopen($sql_path, 'w');
fputs($fp, $str_query);
fclose($fp);
global $databases;
if ($sqlsrv) {
$cmd = ($exec_path .
' -S ' . $databases['default']['default']['host'] .
' -d ' . $databases['default']['default']['database'] .
' -U ' . $databases['default']['default']['username'] .
' -P ' . $databases['default']['default']['password'] .
' -i ' . $sql_path . '>>'. $file_path .
' -s '. '"," -W -m10 -r1');
}
else {
$cmd = ($exec_path . ' ' . $databases['default']['default']
['database'] .
' -h ' . $databases['default']['default']['host'] .
' -u ' . $databases['default']['default']['username'] .
' -p ' . $databases['default']['default']['password'] . ' < '
. $sql_path .
' > ' . $file_path);
}
exec($cmd);
watchdog('cmd', var_export($cmd, TRUE));

Concatenate a string after variable in PHP

I want to concatenate string after variable in PHP. dot operator is not working.
foreach ($get_cont as $line)
{
#var_dump($line);
if (strpos($line, "a href"))
{
#echo "$line";
$get_core++;
if ($get_core == 3)
{
#echo $line;
break 1;
}
}
}
#echo $line;
$array = explode(' ', $line);
$core = $array[count($array) - 1];
$core = substr_replace($core, "", -1);
$cmd = "cmd /c curl http://" . $server["server_name"] . ":" . $server["port"] . "/solr" . "/" . $core . "/admin/registry.jsp";
var_dump($cmd);
The output should be like:
cmd /c curl http://server_name:8080/solr/"value of variable core"/admin/registry.jsp.
Please suggest. "." operator is not working.
$cmd = "cmd /c curl http://" . $server["server_name"] . ":" . $server["port"] . "/solr" . "/" . $core . "/admin/registry.jsp";
You've used double quotes for array keys in your variables and to identify your text string. You can see in the syntax highlighting that it is parsing those parts as strings rather than keys as part of your variable/array. You should either use single quotes or use curly braces to declare the variable.
Try
$cmd = "cmd /c curl http://{$server['server_name']}:{$server['port']}/solr/{$core}/admin/registry.jsp";
OR
$cmd = "cmd /c curl http://" . $server['server_name'] . ":" . $server['port'] . "/solr/" . $core . "/admin/registry.jsp";
You can't access super global variable $_SERVER with $server, For this you have to use $_SERVER, For accessing server name you should use $_SERVER["SERVER_NAME"] and for accessing server port you should use $_SERVER["SERVER_PORT"]
Change this to:
$cmd = "cmd /c curl http://" . $server["server_name"] . ":" . $server["port"] . "/solr" . "/" . $core . "/admin/registry.jsp";
This:
$cmd = "cmd /c curl http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . "/solr/" . $core . "/admin/registry.jsp";
Try this:
<?php
$get_cont=array("<a href='www.google.com'>");
foreach ($get_cont as $line)
{
#var_dump($line);
if (strpos($line, "a href"))
{
#echo "$line";
$get_core++;
if ($get_core == 3)
{
#echo $line;
break 1;
}
}
}
;
$array = explode(' ', $line);
$core = $array[count($array) - 1];
$core = substr_replace($core, "", -1);
echo $cmd = "cmd /c curl http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . "/solr/" . $core . "/admin/registry.jsp";
Below worked for me. I handled the values as string instead of storing it in array:
#echo $line;
$core="";
$core_temp="";
$core_temp=strip_tags($line);
$core=substr($core_temp, strpos($core_temp, " ") + 1);
#$array=explode(' ', $line);
#$core = $array[count($array)-1];
#$core=substr_replace($core, "", -1);
#var_dump($core);
#echo "$core";

When PHP is builting URL, script stop working

Everytime I run this part of my script, stript stop working.
$url = $this->getUrl . '?id=' . $this->apiKey . '&email=' . urlencode($this->email) . '&produkt[]=' . urlencode($this->product) . '&orderid=' . $this->order_id;
foreach ($this->products as $product) {
$url .= '&produkt[]=' . urlencode($product);
}
When I change $url = $this->getUr ... ... to $url = http://blablabla.com/blabla... ... all is working fine.
Where is a bug?
yeah, set put "php_flag display_errors on" into .htaccess file in that folder and you'll see where is the problem.
From
$url = $this->getUrl . '?id=' . $this->apiKey . '&email=' . urlencode($this->email) . '&produkt[]=' . urlencode($this->product) . '&orderid=' . $this->order_id;
foreach ($this->products as $product) {
$url .= '&produkt[]=' . urlencode($product);
}
to
$url = $getUrl . '?id=' . $apiKey . '&email=' . urlencode($this->email) . '&produkt[]=' . urlencode($product) . '&orderid=' . $order_id;
$this-> is not defined in my script, so after deleting it, script works fine. But everybody must define $product before url is creating. It works in my script!

Why my PHP defined constants are not evaluated when file is executed using command line?

I am creating a plugin for a WP site and I have to make an initial import of a huge amount of files from another directory. (The plugin is working well, etc etc.) I want to run the import using command line. Everything is OK if executing on local (Windows), but when I execute from Linux bash the defined constants are not evaluated but printed as a string.
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
Is there any setting I have to make to enable evaluation of PHP defined constants? My website is running on Dreamhost server.
When I execute the folowing line:
[myserver]$ /usr/local/php5/bin/php /home/path/to/import.php
I get:
WordPress database error Table 'db_ro.ASCOR_RECORDINGS_TBL' doesn't exist for query INSERT INTO `ASCOR_RECORDINGS_TBL` ...........
The content of the file I execute:
<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . "/wp-load.php";
require_once "class/AscorDbHelper.php";
$origin = realpath("/path/to/files");
$upload_dir = wp_upload_dir();
$subdir = $upload_dir['subdir'];
mkdir(ASCOR_UPLOAD_DIR . "/" . $subdir, 777, true);
require_once $origin . "/classes/PConfFiles.inc.php";
$db = new AscorDbHelper();
$cf = new PConfFiles('/^PC_([0-9\-]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
$catPC = $db->addCategory("Special");
$catOther = $db->addCategory("Other");
if($list){
$pc = $db->addAuthor("Ciprian V.");
foreach($list as $rec){
$fileUrl = $subdir . "/" . $rec[0];
$desc = str_replace("-", " ", $rec[2]);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catPC->id, $pc->id, $desc, null, $rec[1]);
echo "Added: " . $rec[0] . "\n";
}
}
$cf = new PConfFiles('/^([0-9\-]+)\_([^\_]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
if($list){
foreach($list as $rec){
$authorName = str_replace("-", " ", $rec[2]);
$date = $rec[1];
$desc = str_replace("-", " ", $rec[3]);
$fileUrl = $subdir . "/" . $rec[0];
$authorId = $db->getAuthorIdOrSaveIt($authorName);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catOther->id, $authorId, $desc, null, $date);
echo "Added: " . $rec[0] . "\n";
}
}
echo "done";
The constants are defined in the main file of the plugin:
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
define("ASCOR_RECORDINGS_AUTHORS_TBL", $wpdb->prefix . "recordings_authors");
define("ASCOR_RECORDINGS_CATEGORIES_TBL", $wpdb->prefix . "recordings_categories");
define("ASCOR_RECORDS_PER_PAGE", 50);
define("ASCOR_EXTEND_DIR", dirname(__FILE__));
define("ASCOR_EXTEND_URL", plugins_url("", __FILE__));
define("ASCOR_NOTIFY_UPDATED", "updated");
define("ASCOR_NOTIFY_ERROR", "error");
define("ASCOR_UPLOAD_DIR", ABSPATH . "/wp-content/uploads/recordings");
Is the file loaded? Introduce a parse error into it and see if it fails. And try it on Windows too.

PHP Script hangs even though max_execution_time & IIS7 Connection Timeout is set

I'm experiencing a very strange problem with my PHP script "hanging" even after the background processes have finished running. I am running PHP 5.3, Windows Server 2008 R2, IIS7 with Tomcat Apache installed.
Project Background My script generates PDF forms through the "shell_exec()" function. Anywhere between 1 - 3,000 forms can be generated. Once all forms have been generated, a download link and "start over" link are supposed to show at the bottom of the page -- instead, the site continues to "load" and the links never show up -- even when I check the server and see that all files have finished generating.
This issue only comes up when generating 300+ forms, which takes 3-6mins.
I have set my php.ini's "max_execution_time" to 1200 (20mins), and IIS7's "Connection Timeout" is also set to 1200 seconds. Here are links to pictures of these settings to confirm I have them set properly:
http://i49.tinypic.com/15gavew.png -- php.ini
http://i49.tinypic.com/9u5j0n.png -- IIS7
Is there another setting that I am missing? Is there a Tomcat Apache Connection Timeout setting that I am unaware of? Does PHP have another "timeout" setting besides "max_execution_time" and "set_time_out"? I've exhausted my resources and have not a clue as to why my script continues to hang, even after the "while loop" has finished running and all PDFs have been successfully created.
Thank you for any and all help/advice.
While Loop Code
/* build zip & directory for PDFs */
$zip = new ZipArchive;
$time = microtime(true);
$new_dir = "c:/pdfgenerator/f-$time";
if(!file_exists($new_dir)) {
mkdir($new_dir);
}
$res = $zip->open("pdf/tmppdf/mf-pdfs_" . $time . ".zip", ZipArchive::CREATE);
$num = 0;
while($row = mysql_fetch_array($result)) {
/* associate a random # assigned to each PDF file name */
$num++;
include($form);
$rand = rand(1,50000);
$file_num = $num * $rand;
$fo = fopen('c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.html', 'w') or die("can't open file");
fwrite($fo, $output);
echo shell_exec('c:\wkhtmltopdf\wkhtmltoimage c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.html c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg');
/* the follow uses ghost script to execute the ImageMagick convert command from cmd.exe */
$magick_dir = 'C:\imagemagick'; // install IM in short DOS 8.3 compatible path
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg -resize "1710x2200^!" c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg' ;
echo shell_exec($send_cmd);
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.pdf';
echo shell_exec($send_cmd);
/* EO ghostscript code */
/* add the newly generated files to the Zip Archive */
if ($res === TRUE) {
//echo "RESULT TRUE...";
$zip->addFile('c:/pdfgenerator/f-' . $time . '/mf_pdf-' . $time . '-' . $file_num . '.pdf','c:/pdfgenerator/f-' . $time . '/mf_pdf-' . $time . '-' . $file_num . '.pdf');
//echo "FILE ADDED!";
}
}
echo "<h2>Download Zip</h2>";
echo "<h2>Start Over</h2>";
$zip->close("pdf/tmppdf/mf-pdfs_" . $time . ".zip", ZipArchive::close());
}
}
Specific Shell Lines
echo shell_exec('c:\wkhtmltopdf\wkhtmltoimage c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.html c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg');
/* the follow uses ghost script to execute the ImageMagick convert command from cmd.exe */
$magick_dir = 'C:\imagemagick'; // install IM in short DOS 8.3 compatible path
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg -resize "1710x2200^!" c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg' ;
echo shell_exec($send_cmd);
$send_cmd=$magick_dir .'\convert c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.jpeg c:\\pdfgenerator\\f-' . $time . '\\mf_pdf-' . $time . '-' . $file_num . '.pdf';
echo shell_exec($send_cmd);
converted all of my mysql_ functions, which are now deprecaded as of PHP 5.5, and utilized MySQLi functions.

Categories