PHP: mysqldump: Couldn't find table: ">" - php

I tried to make simple php script to backup databes using mysqldump but i got this error:
mysqldump: Couldn't find table: ">"
And this is the function that i have write to make the job:
protected function dump($params, $dbs, $backup_folder)
{
if (!is_writable($backup_folder)) {
throw new Exception(sprintf('The backup folder is not writable: %s',
$backup_folder));
}
$backup_folder = trim($backup_folder, "/"); // be sure that there is no / at the end
$baseCmd = 'mysqldump --hex-blob --routines --skip-lock-tables -h%s -u%s -p%s %s > %s';
foreach ($dbs as $db) {
$dest = sprintf('%s/%s', $backup_folder,
$db . '_' . date('YmdHis') . '.sql');
$cmd = sprintf($baseCmd, $params['host'], $params['user'],
$params['password'], $db, $dest);
echo "Exec: $cmd: ";
$last = system(escapeshellcmd($cmd), $res);
echo $res;
if ( 0 !== $res) {
echo "Fail";
} else {
echo "Done \n";
}
}
}
The command printed by this function give:
mysqldump --hex-blob --routines --skip-lock-tables -hdb-backup -uroot -pMyPwd my_db_name > backups/my_db_name_20151010232734.sql
When i execute this command from Shell it works very well but not from Php script.
My config is:
My Desktop System Shell: Ubuntu 15.04
Mysql Server: Mysql 5.6 installed in Ubuntu Server 15.04
PHP version: 5.6.4
Any help ?
Thank you

The escapeshellcmd() command prepends a \ to the >.
From the PHP documentation:
Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\, \x0A and \xFF.
You should either escape each argument individually with escapeshellarg(), or ensure that your method arguments ($params, $db, and $backup_folder) are valid and don't contain one of those chars and just use
system($cmd, $res)
I hope this helps!

Related

How to execute commands through PHP?

I am trying to convert videos into MP4 using FFMPEG. I have it set up this way:
.
.
private $ffmpegPath;
public function __construct($con) {
$this->con = $con;
$this->ffmpegPath = realpath("ffmpeg/bin/ffmpeg.exe");
}
.
.
public function convertVideoToMp4($tempFilePath, $finalFilePath){
$cmd = "$this->ffmpegPath -i $tempFilePath $finalFilePath 2>&1";
$outputLog = array();
exec($cmd, $outputLog, $returnCode);
if($returnCode != 0){
foreach ($outputLog as $line){
echo $line."<br>";
return false;
}
}
return true;
}
And in the browser i get the following error:
'C:\xampp\htdocs\Thinksmart First Sprint' is not recognized as an internal or external command".
In my constructor i have it set up to give me the realpath and i suspect that this is what it does in the command line:
C:/xampp/htdocs/Thinksmart FIrst Sprint/ffmpeg/bin/ffmpeg.exe -i (file temp name) (file name i want)
And this should work, but i dont know why it wont. Any ideas? Its my first time working with video conversions.
As you can see, spaces in your command are used to separate arguments. So if there are spaces in a path you need to quote the entire path with quotes so that the shell/processor knows they aren't separators but are one argument:
$cmd = $cmd = '"' . $this->ffmpegPath . '" -i $tempFilePath $finalFilePath 2>&1';
Which will result in a command something like this:
"C:/xampp/htdocs/Thinksmart First Sprint/ffmpeg/bin/ffmpeg.exe" -i C:/path/to/file1 C:/path/to/file2 2>&1
I think only double-quotes work on Windows. You need to quote $tempFilePath and $finalFilePath if they might have spaces in them as well.

ZipArchive::setPassword doesn't set a password to my newly created file

The new "setPassword" method doesn't take effect (unless I've misunderstood it).
This is my example code:
<?php
$zipFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'filename.zip';
$password = 'P455W0RD';
if (file_exists($zipFilePath)) {
unlink($zipFilePath);
}
$zipArchive = new ZipArchive();
$zipArchive->open($zipFilePath, ZipArchive::CREATE);
if ($zipArchive->setPassword($password)) {
echo 'OK' . PHP_EOL;
}
foreach (range(1, 10) as $fileNumber) {
$zipArchive->addFromString('file' . $fileNumber . '.txt', rand());
}
$zipArchive->close();
It does print "OK" in PHP 5.6.0beta3 (Debian Testing), but there is no password
in the zip file.
What am I missing?
I found a way to bypass the ZipArchive::setPassword() method. I simply wrote a shell script:
#!/bin/bash
command -v zipcloak && echo "exist" || exit -1;
command -v expect && echo "exist" || exit -1;
MYPWD="[password]"
expect -c '
spawn zipcloak [filename]
expect "*Enter password*"
sleep 0.1
send "'"$MYPWD"'\r"
sleep 0.1
expect "*Verify password*"
sleep 0.1
send "'"$MYPWD"'\r"
sleep 0.1
'
I can simply use exec from my php code:
public function encryptZip($filename, $password, $bashdir){
$bash = str_replace('[filename]', $filename, (str_replace('[password]', $password, file_get_contents($bashdir))));
exec($bash);
}
It works only on linux servers, where expect and zipcloak are installed.

command line combine pdfs through php exec

I just setup wkhtmltopdf to take html docs and turn them into pdfs but now I need a way to combine the multiple pdfs.
Any suggestions?
We do have pdflib license if there is something it can do but seems its mainly an api for custom building pdfs.
If you got wkhtmltopdf I suppose you're using Linux and you got a root shell access.
You could use Pdftk Toolkit via system() or exec().
First install it. It's a package in Debian/Ubuntu, for example:
sudo apt-get install pdftk
Then make sure that's visible in your bin search PATH.
And a simple PHP snippet:
// In / Out filenames
$input_files = array( 'file_one.pdf', 'file_two.pdf' );
$file_out = 'merged.pdf';
// Escape names and create argument
$line_parts = '';
foreach( $input_files as $file ) {
$line_parts .= escapeshellarg( $file ) . ' ';
}
// Run pdftk
$cmd = 'pdftk ' . $line_parts . ' cat output ' . escapeshellarg( $file_out );
system( $cmd, $retval );
if( $retval ) { print 'There was an error!'; }

Filesize 0 mysqldump

I am using Windows 7 and using php i am backing up my database with the help of mysqldump. The file gets successfully written but the size remains always 0. Any idea why is this happening?
Note :- If i type the same command in command line, it works. This is my function :-
public static function BackupDatabase($backupPath){
$fileName = uniqid() .'.sql';
$backupCommand = 'mysqldump -u ' . DBUsername .' -p' . DBPassword .' abc >' . $backupPath . $fileName ;
$retVal = '';
$feedback = system($backupCommand, $retVal);
if($feedback == NULL || $feedback == '')
return 'Database backed up successfully by name ' . $fileName;
else
return $feedback;
}
EDIT :-
public static function BackupDatabase($backupPath){
$fileName = uniqid() .'.sql';
$backupCommand = 'mysqldump -u ' . DBUsername . ' abc > ' . $backupPath . $fileName .' 2>&1' ;
echo $backupCommand;
$retVal = '';
$feedback = system($backupCommand, $retVal);
echo $retVal;
if($feedback == NULL || $feedback == '')
return 'Database backed up successfully by name ' . $fileName;
else
return $feedback;
}
Thanks in advance :)
I believe is caused by the environment setting.
You can execute mysqldump successfully in the command line as you probably has mysqldump register in your environment.
While running in a PHP, the path to mysqldump might not recognized by user that running the web server.
And
$feedback = system('unknown program > file', $retval);
Will always set $feeback = ''; even PHP cannot find where is your mysqldump program, it still pipe a single character to backup file.
You can put in absolute path to mysqldump to test again.
Check your $backupCommand string. It seems to me that there are some spaces missing (e.g. in the vicinity of '-p').
After much headache, this syntax worked for me:
cmd /c " C:\mysqldump.exe -h $mysql_server -u $mysql_user --password=$mysql_password $dbname > C:\Dump.sql "

Is it possible to remove a Password from a PDF file using PHP?

I would like to ask if it's possible to use PHP in removing a password from a password-protected PDF file in which I already know the password? I've seen this page which provides many options but using bash script. :( I was required to use PHP as much as possible. Any suggestions appreciated!
Of course it's possible, all you need to do is reverse engineer the encryption and compression and implement the reverse operations in PHP - but why bother:
<?php
`gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=unencrypted.pdf -c .setpdfwrite -f encrypted.pdf`;
?>
C.
I use qpdf on linux to remove pdf password. To install run:
sudo apt install qpdf
Here is the function which invokes qpdf from php:
function removePdfPassword($inFilePath, $password, $outFilePath)
{
if (empty($inFilePath) || empty($password) || !file_exists($inFilePath)) {
return false;
}
$cmd = 'qpdf -password=' . escapeshellarg($password) . ' -decrypt ' . escapeshellarg($inFilePath) . ' ' . escapeshellarg($outFilePath);
exec($cmd, $output, $retcode);
$success = $retcode == 0;
if (!$success) {
#unlink($outFilePath);
}
return $success;
}

Categories