Is there a PHP functionallity same as read -i in BASH so that a script can prompt the user and provide a default answer like this:
Are you doing ok? (yes/no): yes
Where "yes" is the default answer provided by the script, which the user can erase and input another.
The readline function does not seem to have what it takes. Is there any other way to do this?
Using a stream does not seem to work either:
<?php
echo "Are you doing ok? (yes/no): ";
$in = fopen('php://stdin', 'rw+');
fputs($in, 'yes'); // should be the default?
$answer = fgets($in);
fclose($in);
echo "\nYou entered: {$answer}\n";
Whatever is in written by the fputs($in, 'yes'); line is ignored:
Are you doing ok? (yes/no): yes
You entered:
Am I using the stream incorrectly? Or maybe there is some other way to achive the default value?
EDIT:
Maybe I simlified the example to much. The real issue is not a simple yes/no prompt - this is just an example. Let me emphasize again: I'm aiming for providing exactly the same functionallity as the read -i BASH command. The $answer in my specific case holds an URL, so I would like for the user to be provided with the first part of the url (scheme, host, port), so he can add/edit the rest (path, query), fragment. Like this:
Enter url: http://www.example.com/foo/
now the user complement the path with bar/baz and we get:
You entered: http://www.example.com/foo/bar/baz
But on the other hand the user also should have the option to erase the first part of the url and provide completely different string:
Enter url: ftp://www.my-super-specific-domain.com/foo/bar
There's no built in way of doing this because writing some code that does it is quite straight forward:
function writeQuestion($question, $answers)
{
echo $question . ' (' . implode('/', $answers) . '): ' . PHP_EOL;
}
function readAnswer($possibleAnswers, $defaultAnswer)
{
$in = fopen('php://stdin', 'rw+');
$answer = trim(fgets($in));
if(!in_array($answer, $possibleAnswers))
{
return $defaultAnswer;
}
return $answer;
}
$question = 'Are you doing ok?';
$answers = array('yes', 'no');
$defaultAnswer = 'yes';
writeQuestion($question, $answers);
$answer = readAnswer($answers, $defaultAnswer);
You can wrap standard bash read for prefilled/populated edit and call it from you main php cli script
bash script named xreadline:
#! /bin/bash
IFS="";read -r -p "$1" -i "$2" -e STRING;echo "$STRING"
main php cli script:
#!/usr/bin/php
<?php
function xreadline ($prompt,$prefill)
{
$on = exec ('./xreadline "'.$prompt.'" "'.$prefill.'"');
return $on;
}
$answer = xreadline ('Your answer: ', 'xyz');
echo $answer;
.....
This approach fully supports UTF8 instead of native PHP readline.
Comment messed my code so here is standalone php cli file with function call to "read" command.
Little bit tricky, but hopefully will work as supposed to. :-)
#!/usr/bin/php
<?php
function xreadline ($prompt,$prefill)
{
return exec ('/bin/bash -c \'read -r -p "'.$prompt.'" -i "'.$prefill.'" -e STRING;echo "$STRING";\'');
}
echo "Prompt test :\n";
$output = xreadline ("edit this prefilled prompt: ","prefilled stuff");
echo "\n";
echo $output;
Related
If I execute an R program through macOS Terminal it works fine, but if I execute that program through PHP exec() I get an error which says "Rscript not found".
submit.php:
<?php
// print "hello";
$a = $_POST['a'];
$b = $_POST['b'];
// echo shell_exec("calc");
$output = exec("Rscript /xampp/htdocs/demo/1.R ".$a." ".$b);
print $output
?>
1.R:
setwd("C:/xampp/htdocs/demo")
print("hello")
args=commandArgs(trailingOnly = TRUE)
a = args[1]
b = args[2]
c = as.numeric(a)+as.numeric(b)
cat(c)
You need to tell the command interpreter where Rscript is located. In a normal login, you'd have a long PATH variable to search through, but when running from PHP you have a much more limited path. To figure out where the executable is located, type which Rscript from Terminal. Use the resulting path in your PHP script.
Also note that dumping raw user input into shell commands is a very bad idea. You should always use escapeshellarg() to make sure the input is sanitized. I would also suggest capturing the full output in the event that R outputs more than one line.
<?php
$a = escapeshellarg($_POST["a"]);
$b = escapeshellarg($_POST["b"]);
$r = "/xampp/htdocs/demo/1.R";
$lastline = exec("/usr/local/bin/Rscript $r $a $b", $output, $return);
// you could check the value of $return for non-zero values as well
// full output is returned as an array
echo implode("\n", $output);
Finally, you'll want to check your setwd() command in the R script. Might have some trouble with C: on a Mac! ;)
I have an html form that asks the user to input a domain name, this is posted to the php7.0 page below for processing by a shell script which then passes output through aha for writing to an html page which is then displayed.
The problem I have is how can I prevent users from injecting commands like:
domain.com | rm * -rf
I thought this could be done using safe_mode and restricting the directory from which commands can be run but it seems this feature is now deprecated.
$domain_arg = escapeshellarg( $_POST['domain'] );
$today = date("Y-m-d-H:i:s");
$cmd = "/home/ubuntu/dtest/dtest.sh $domain_arg | aha -b -t 'Domain test of $domain_arg' > /var/www/website/results/$domain_arg.$today.html";
$output = shell_exec($cmd);
header("Location: http://the.web.com/results/$result.$today.html");
You use escapeshellarg on the arguments before running them, the result is a single quoted string such as 'domain.com | rm *'. Your problem is that you're not using this as a shell argument, but as a portion of a shell argument:
aha -b -t 'Domain test of $domain_arg'
This will absolutely cause the problems you're describing. Try something like this instead:
<?php
$domain_arg = escapeshellarg($_POST["domain"]);
$log_msg = escapeshellarg("Domain test of $_POST[domain]");
$today = date("Y-m-d-H:i:s");
$log_file = preg_replace(
"/[^\w:\\/.-]/i",
"_",
"/var/www/website/results/$_POST[domain].$today.html"
);
$cmd = "/home/ubuntu/dtest/dtest.sh $domain_arg | aha -b -t $log_msg > $log_file";
$output = shell_exec($cmd);
$result = rawurlencode($output); // just guessing that's where it comes from
$today = rawurlencode($today);
header("Location: http://the.web.com/results/$result.$today.html");
You should rather use escapeshellcmd() instead of escapeshellarg().
I have been trying to work this out for a couple days now and can't crack it.
I'm trying to use php to echo the result of tesseract.
After everything I've researched and tried, I feel like the below code should work.
<?php
echo '<pre>';
echo exec('/usr/local/bin/tesseract /home/username/www/ocr/images/hello.png result');
echo '</pre>';
?>
The command runs fine via SSH and if I change the above to suit ifconfig it works fine.
Any ideas to get this working?
You could try cat-ing the result as a 2nd command once tesseract is done. shell_exec appears to be better at returning the full output vs. exec.
<?php
$res = shell_exec('/opt/local/bin/tesseract /Users/stressederic/Sites/Sandbox/OCR/CC/gold.jpg result && cat result.txt');
var_dump($res);
I ended up getting this working by just breaking everything down.
file_put_contents("$tmpFile",file_get_contents($img));
$cmd = "/usr/local/bin/tesseract $tmpFile stdout";
exec($cmd, $msg);
$arraymsg = $msg;
$msg = implode(' ', $msg);
echo $msg;
its work
var_dump(exec('/usr/bin/tesseract 6.png out1 -l eng+ara'));
or
var_dump(shell_exec('/usr/bin/tesseract 6.png out1 -l eng+ara'));
tip:
in laravel =>
6.png Into the folder public
lang=> eng or ara are language
Please help me as I have been trying to get this to work for two days.
I have a text file which has the array to define username and passwords.
$USERS['user'] = 'pass1';
I am trying to make a PHP to change this password
//name - call_pwd.php
$commandline='./change_password ' . $_SESSION["logged"] . " " . $_POST["old_password"] . " " . $_POST["new_password"]
$output = shell_exec("$commandline");
Here is the bash file I made to change this password. Because I am not good at it I have to use so many variables to make it easily.
#!/bin/bash
#name - change_password
username=`echo "$1"`
old_password=`echo "$2"`
new_password=`echo "$3"`
old_string=`echo "\['$username'\] = '$old_password'"`
new_string=`echo "['$username'] = '$new_password'"`
sed -i "s/${old_string}/${new_string}/" passwords.php
if [ "$?" == 0 ]
then
echo "Password changed Successfully."
else
echo "Could not change password, try again."
fi
When I run this script from the root prompt it works fine and changes the password. But from PHP it won't work. It keeps giving me the message "Could not change password, try again."
As I read " and ' needs to be escaped if you want to use sed with php and I tried that with
sed -i \"s/${old_string}/${new_string}/\" passwords.php
sed -i \""s/${old_string}/${new_string}/\"" passwords.php
The permissions on passwords.php is full permission for all users.
I have also tried putting absolute paths everywhere but that also didn't work.
The $output variable on my call_pwd.php comes out as when I echo $commandline $old_string and $new_string
change_password user pass1 pass2
\['user'\] = 'pass1'
['user'] = 'pass2'
Could not change password, try again.
Please help me. Thanks.
Apologies for such a long post.
Why are you doing it this way? You could do everything in PHP with [un]serialize() and file_[put/get]_contents().
$ php -r '
$USERS = [ "user" => "pass1" ];
file_put_contents("passwords.php", serialize($USERS));'
$ cat passwords.php;
a:1:{s:4:"user";s:5:"pass1";}
$ php -r '
$USERS = unserialize(file_get_contents("passwords.php"));
$USERS["user"] = "newpass";
file_put_contents("passwords.php", serialize($USERS));'
$ cat passwords.php
a:1:{s:4:"user";s:7:"newpass";}
I won't make any comment on the security implications of doing this, but if you want to simply change some values in a text file when you are already using PHP, why not just use PHP?
I login to AS400 and go to QSHELL(STRQSH). After that I pasted the following command and run it in QSHELL
system "IVIEW/PRTDISTL APPNAME(MYJOBLOG) STMF(TEST_89.PDF) HOLD(*NO)"
It works. But when I execute the above command using PHP script as the follow
$cmd = "IVIEW/PRTDISTL APPNAME(MYJOBLOG) STMF(TEST_89.PDF) HOLD(*NO)";
$cmd = 'system "' . $cmd . '"';
$output = array();
exec ($cmd, $output , $retVal);
echo "return value code: " . $retVal;
It returns error code of 255. Please help me how to fix this issue. Thanks
Try the PHP Toolkit for i5/OS. There is a older Redbook that describes it: http://www.redbooks.ibm.com/redbooks/pdfs/sg247327.pdf
An example from there:
<HTML>
<?php
/* Connect to server */
$conn = i5_connect("localhost", "PHPUSER", "MYPASSWORD");
if (!$conn)
die("<br>Connection using \"localhost\" with USERID and PASSWORD failed. Error
number =".i5_errno()." msg=".i5_errormsg())."<br>";
else
echo "<br>Connection using \"localhost\" with USERID and PASSWORD OK!<br>\n";
/* Call Retrieve Network Attributes command */
$ret = i5_command("rtvneta", array(), array("sysname" => "sysn", "lclnetid"=>"lclnet"));
if (!$ret) die("<br>rtvneta command failed. errno=".i5_errno()."
msg=".i5_errormsg());
print "<h1><b>Results of \"rtvneta\" command </b></h1><br>" ;
print "System Name : $sysn<br>" ;
print "Local Net ID : $lclnet<br>" ;
/* Close connection */
i5_close($conn);
?>
</HTML>
I see two pontential problems:
PHP runs in PASE, not in QShell. Try to manually run your call from QP2TERM.
User rights. Make sure QTMHHTTP (or whatever user runs PHP) has the apropriate rights to the program you try to call.
You can check for further information in stdout, which you should have in $output, and your PHP-server joblog as mentioned at IBM i information center (possibly needing the flag 'system -K').