How to give php script POST arguments via command line - php

I am debugging a php script that will be called by a javascript function and that have POST arguments. I would like to test it in command line mode. I know it is possible doing it with the php -a option. But once in the interactive mode how to I set up the arguments? And how do I call my php? I can't neither remenber nor find how to do it.
My php script is:
<?php
$data = $_POST['string'];
$fname = $_POST['file'];
$dir=$_POST['dir'];
mkdir($dir);
$file = fopen($fname, 'w');
fwrite($file, $dir."\n");
fwrite($file, $data."\n");
fwrite($file, "/var/www/html/ChemAlive_app/SOFTWARE/utilities/"."\n");
fclose($file);
$saved = getenv("LD_LIBRARY_PATH"); // save old value
$newld = "/usr/local/NWChem/lib/"; // extra paths to add
if ($saved) { $newld .= ":$saved"; } // append old paths if any
putenv("LD_LIBRARY_PATH=$newld");
$saved = getenv("PATH"); // save old value
$newld = "/usr/local/NWChem/bin/"; // extra paths to add
if ($saved) { $newld .= ":$saved"; } // append old paths if any
putenv("PATH=$newld");
exec("cd $dir ; /var/www/html/ChemAlive_app/SOFTWARE/ChemAliveExec/ReactionThermo ".$fname);
?>
Thanks for your help.

you can use the following:
<?php
// check to see if php called from cmd line
if (php_sapi_name() == 'cli') {
//take vars from cmd line args argv[0] is script name
$data = $argv[1];
$fname = $argv[2];
$dir = $argv[3];
} else {
$data = $_POST['string'];
$fname = $_POST['file'];
$dir=$_POST['dir'];
}
then call the script on the command line with
/path/to/php /path/to/script.php 'some data' 'filename' 'dirname'

Related

PHP. How to read a file, if it is writing without a problem with "a+", but is not readable with "r"?

I have two scripts: one of them writes the value of a variable to a file. In another script, I try to read it. It is written without problems, but it is not readable.
Here I write to a file:
$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file, $peer_id);
fclose($file);
Here I read the file:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
// Result is TRUE
}
if(is_readable ($file)){
// Result is FALSE
}
// an empty variables, because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);
The code runs on "sprinthost" hosting, if that makes a difference. There are suspicions that this is because of that hosting.
file_get_contents in short runs the fopen, fread, and fclose. You don't use a pointer with it. You should just use:
$peer_id = file_get_contents($fileLocation);
That is the same for is_readable:
if(is_readable($fileLocation)){
// Result is FALSE
}
So full code should be something like:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
$peer_id = file_get_contents($fileLocation);
} else {
echo 'Error message about file being inaccessible here';
}
The file_get_contents has an inverse function for writing; https://www.php.net/manual/en/function.file-put-contents.php. Use that with the append constant and you should have the same functionality your first code block had:
file_put_contents($fileLocation, $peer_id, FILE_APPEND | LOCK_EX);

PHP script runs multiple times if it contains shell_exec. How could it be?

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.

File manupulation search and replace csv php

I need a script that is finding and then replacing a sertain line in a CSV like file.
The file looks like this:
18:110327,98414,127500,114185,121701,89379,89385,89382,92223,89388,89366,89362,89372,89369
21:82297,79292,89359,89382,83486,99100
98:110327,98414,127500,114185,121701
24:82297,79292,89359,89382,83486,99100
Now i need to change the line 21.
This is wat i got so far.
The first 2 to 4 digits folowed by : ar a catergory number. Every number after this(followed by a ,) is a id of a page.
I acces te id's i want (i.e. 82297 and so on) from database.
//test 2
$sQry = "SELECT * FROM artikelen WHERE adviesprijs <>''";
$rQuery = mysql_query ($sQry);
if ( $rQuery === false )
{
echo mysql_error ();
exit ;
}
$aResult = array ();
while ( $r = mysql_fetch_assoc ($rQuery) )
{
$aResult[] = $r['artikelid'];
}
$replace_val_dirty = join(",",$aResult);
$replace_val= "21:".$replace_val_dirty;
// file location
$file='../../data/articles/index.lst';
// read the file index.lst
$file1 = file_get_contents($file);
//strip eerde artikel id van index.lst
$file3='../../data/articles/index_grp21.lst';
$file3_contents = file_get_contents($file3);
$file2 = str_replace($file3_contents, $replace_val, $file1);
if (file_exists($file)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
if (file_exists($file3)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
// replace the data
$file_val = $file2;
// write the file
file_put_contents($file, $file_val);
//write index_grp98.lst
file_put_contents($file3, $replace_val);
mail('info#', 'Aanbieding catergorie geupdate', 'Aanbieding catergorie geupdate');
Can anyone point me in the right direction to do this?
Any help would be appreciated.
You need to open the original file and go through each line. When you find the line to be changed, change that line.
As you can not edit the file while you do that, you write a temporary file while doing this, so you copy over line-by-line and in case the line needs a change, you change that line.
When you're done with the whole file, you copy over the temporary file to the original file.
Example Code:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
This part is just setting up the basics: The category, the IDs of the articles and then building the related strings.
Now opening the file to change the line in:
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
The file is locked so that no other process can edit the file while it gets changed. Next to that file, the temporary file is needed, too:
$temp = new SplTempFileObject(4096);
After setting up the two files, let's go over each line in $file and compare if it needs to be replaced:
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
Now the $temporary file contains already the changed line. Take note that I used UNIX type of EOF (End Of Line) character (\n), depending on your concrete file-type this may vary.
So now, the temporary file needs to be copied over to the original file. Let's rewind the file, truncate it and then write all lines again:
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
And finally you need to lift the lock:
$file->flock(LOCK_UN);
And that's it, in $file, the line has been replaced.
Example at once:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
$temp = new SplTempFileObject(4096);
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
$file->flock(LOCK_UN);
Should work with PHP 5.2 and above, I use PHP 5.4 array syntax, you can replace [111182297, ...] with array(111182297, ...) in case you're using PHP 5.2 / 5.3.

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 correctly use the PHP function 'fgets'?

I assume I'm using the fgets() wrong. I'm tring to open a PHP file and then try to match a line in that file with a variable I create. If the line does match then I want to write/insert PHP code to the file right below that line. Example:
function remove_admin(){
$findThis = '<tbody id="users" class="list:user user-list">';
$handle = #fopen("../../fns-control/users.php", "r"); // Open file form read.
if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 479); // Read a line.
if ($buffer == '<tbody id="users" class="list:user user-list">') // Check for string.
{
Now I want to write PHP code to the file, starting on line 480. How can I do that?
Useful information may be: IIS 6 and PHP 5.2.
Try this:
<?php
function remove_admin(){
$path = "../../fns-control/users.php";
$findThis = '<tbody id="users" class="list:user user-list">';
$phpCode = '<?php echo \'hello world\'; ?>';
#Import file to string
$f = file_get_contents($path);
#Add in the PHP code
$newfile = str_replace($findThis, $findThis . $phpCode, $f);
#Overwrite the existing file
$x = fopen($path, 'w');
fwrite($x, $newfile);
fclose($x);
}

Categories