ERROR_CACHE_MISS when passing value from PHP to bash - php

I am trying to pass some values from a PHP file to a BASH script. I am getting a ERROR CACHE_MISS response.
The variable 'coretown' holes the value 'Houston, TX'. It must be in that format for the bash script to work.
Results of a test to prove the variables are correct
WorkString531cdf6b8b3451.99781853 OutString531cdf6b8b3451.99781853 Houston, TX
Execute the bash script.
$errorTrap=shell_exec("./Find-Town.sh $workPath $outPath $coreTown");
Bash script:
#!/bin/bash
set -x
InFile="./zipcode.txt"
"$Work1"="$1"
"$OutFile"="$2"
"$InString"="$3"
echo "$1";
echo "$2";
echo "$3";
Returned by the 'echo' in the script:
WorkString531cdf6b8b3451.99781853 OutString531cdf6b8b3451.99781853 Houston,
Notice the state (TX) is missing. If I put 'echo "$4";' in there it will display the 'TX'.
Is one of these languages handling the content of 'coreTown' ('Houston, TX') as an array? If so, which one? Amd how do I fix it? My google searches did not address this problem.

Since $coreTown contains a space, that's being treated as an argument delimiter in the shell; you need to quote it or escape the space. Luckily, PHP has a function that does that for you: escapeshellarg.
$workPathEsc = escapeshellarg($workPath);
$outPathEsc = escapeshellarg($outPath);
$coreTownEsc = escapeshellarg($coreTown);
$errorTap = shell_exec("./Find-Town.sh $workPathEsc $outPathEsc $coreTownEsc");

Related

How to pass the string from php to tcl and execute the script

I want to pass the string from my php like
<?php
str1="string to pass"
#not sure about passthru
?>
And my tcl script
set new [exec $str1]#str1 from php
puts $new
Is this Possible? Please let me know I'm stuck with this
The simplest mechanism is to run the Tcl script as a subprocess that runs a receiving script (that you'd probably put in the same directory as your PHP code, or put in some other location) which decodes the arguments it is passed and which does what you require with them.
So, on the PHP side you might do (note the important use of escapeshellarg here! I advise using strings with spaces in as test cases for whether your code is quoting things right):
<?php
$str1 = "Stack Overflow!!!";
$cmd = "tclsh mycode.tcl " . escapeshellarg($str1);
$output = shell_exec($cmd);
echo $output;
echo $output;
?>
On the Tcl side, arguments (after the script name) are put in a list in the global argv variable. The script can pull them out with any number of list operations. Here's one way, with lindex:
set msg [lindex $argv 0]
# do something with the value from the argument
puts "Hello to '$msg' from a Tcl script running inside PHP."
Another way would be to use lassign:
lassign $argv msg
puts "Hello to '$msg' from a Tcl script running inside PHP."
Note however (if you're using Tcl's exec to call subprograms) that Tcl effectively automatically quotes arguments for you. (Indeed it does that literally on Windows for technical reasons.) Tcl doesn't need anything like escapeshellarg because it takes arguments as a sequence of strings, not a single string, and so knows more about what is going on.
The other options for passing values across are by environment variables, by pipeline, by file contents, and by socket. (Or by something more exotic.) The general topic of inter-process communication can get very complex in both languages and there are a great many trade-offs involved; you need to be very sure about what you're trying to do overall to pick an option wisely.
It is possible.
test.php
<?php
$str1="Stackoverflow!!!";
$cmd = "tclsh mycode.tcl $str1";
$output = shell_exec($cmd);
echo $output;
?>
mycode.tcl
set command_line_arg [lindex $argv 0]
puts $command_line_arg

Output from a PHP script to C scanf of program

I wonder how is it possible to pass an output from PHP to scanf of a c program? The normal way of inputing in this C program is to use an echo -ne "\x0a etc..........." | ./program on terminal. The thing is that I cannot apply it on PHP. could someone help me? Lets say I want to output the variable $var from PHP to the C program.
Use popen() inside the script to run a command with input from the script. To get hex characters, put them inside a double-quoted string, and concatenate them to the variables.
$pipe = popen($program, "w");
$vartmp = $passwordHEX . "\x00\x00\x00\x00\x00\x00\x00\x00‌\x00\x00x00" . $Pass‌​wordHash;
fwrite($pipe, $vartmp);
pclose($pipe);

PHP variable into Python

I understand there are questions like mine already asked, but I can't figure this out even with the answers in those questions.
PHP:
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py'.$var1);
?>
Python:
import sys
print(sys.argv[1])
Error received when running in Python:
IndexError: list index out of range
Both scripts are in the same folder.
Could someone please provide an answer with the code changes?
Error
If the Python script runs with no arguments at all, then that sys.argv[1] index is out of range.
Scripts
ExecPython.php
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py ' . $var1);
echo "<pre>$result</pre>";
TestingStuff.py
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
Demo
Explanation
We will start with the Python script. The goal is, that the script prints the first argument passed to it - without running into the "IndexError: list index out of range" error.
python TestingStuff.py 123 we want the output 123.
In Python the arguments passed to the script reside in sys.argv. It's a list. sys.argv[0] is always the script name itself (here TestingStuff.py). Using the example from above sys.argv[1] is now 123.
Handling the edge cases: "no argument" given.
python TestingStuff.py
This will result in an "IndexError: list index out of range" error, because you are trying to access a list element, which is not there. sys.argv[0] is the script name and sys.argv[1] is not set, but you are trying to print it and BAM goes the error. To avoid the error and only print the first argument, we need to make sure, that the list sys.argv contains more than one element (more than the script name). That's why i've added if len(sys.argv) > 1:.
That means: print the first argument only, if the list has more than 1 argument.
Now we can test the Python script standalone - with and without arguments.
And switch over to the PHP script.
The goal is to execute the Python script from PHP.
PHP provides several ways to execute a script, there are for instance exec(), passthru(), shell_exec(), system(). Here we are using shell_exec(). shell_exec() returns the output of the script or command we run with it.
In other words: if you run $result = shell_exec('php -v');, you'll get the PHP version lines in $result.
Here we are executing the Python script TestingStuff.py and add an argument, which is $var1. It's a string and added via concatenation to the string given to shell_exec(). The $result is echoed. I wrapped pre-tags around it, because i thought this is executed in the web/browser context. If you are using the scripts only on the CLI, you might drop the pre-tags.
Execution flow
the PHP script is executed
shell_exec() executes the Python script
shell_exec() returns the output of the Python script as $result
$result is printed by PHP via echo

PHP system() keeps echo even though

So I need to found out if an upload from a user is images/ video and what type. I currently use
"filetype"=>system("file -i -b ".$_FILES['file']['tmp_name'])
which is inserted into my MongoDB collection via this
$s3file='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
$collection = static::db()->media;
$datetime = time();
$mediaupload = array("owner"=>$_SESSION['user_information'][0]['_id'],"filelink"=>$s3file,"filetype"=>system("file -i -b ".$_FILES['file']['tmp_name']),"filesize"=>$size,"uploadtime"=>$datetime,"ownerid"=>$_SESSION["user_information"][0]['_id']);
$collection->insert($mediaupload);
$media = $collection->findOne($mediaupload);
However what I am noticing is it echos the result out to the PHP page - which is not what I need it to do. i know it is the system function because when I remove that function it does not echo the uploaded file type to the php code.
I am wondering therefor how can i still run that system file -i -b function and get it to include into the MongoDB database but not echo the result into the public php page return.
Try something like (for multi-line output)
exec("file -i -b ".$_FILES['file']['tmp_name'], $output);
array("filetype"=>$output);
It may look a little unorthodox, but exec uses its second input parameter as a way to pass the output information back to you - the output of file will be stored as an array into $output.
From the docs:
If the output argument is present, then the specified array will be
filled with every line of output from the command. Trailing
whitespace, such as \n, is not included in this array. Note that if
the array already contains some elements, exec() will append to the
end of the array. If you do not want the function to append elements,
call unset() on the array before passing it to exec().
If you simply want the first line from the output, use the simpler version:
array("filetype"=>exec("file -i -b ".$_FILES['file']['tmp_name']));
I have switched the system to exec() and that seems to of fixed my issue

Passing a path in a PHP CLI script argument

I'm writing a php CLI script that accepts, among other argument, a path.
So an example is:
php myscript.php -p=/Volumes/Macintosh HD/Users/andrea/samples
The script has his own way to red the arguments and it properly gets the value for -p, setting it in a variable called $project_path.
However, when I test the folder with isdir($project_path) it returns false.
I've tried to pass the path in different ways:
/Volumes/Macintosh\ HD/Users/andrea/samples
'/Volumes/Macintosh HD/Users/andrea/samples'
"/Volumes/Macintosh HD/Users/andrea/samples"
'/Volumes/Macintosh\ HD/Users/andrea/samples'
"/Volumes/Macintosh\ HD/Users/andrea/samples"
Non of them works.
What's the format I must use to make it work?
Please consider that the script must also work on different OS (i.e. Windows).
The problem is the path argument is automatically escaped:
I need to unescape it.
The returned string is:
\'/Volumes/Macintosh\ HD/Users/andrea/samples\'
Short answer: Use escapeshellarg()
Long answer:
chmod +x yourscript.php
-
$path = '/Volumes/Macintosh HD/Users/andrea/samples';
$cmdline = sprintf('/home/user/yourscript.php -p=%s 2>&1', escapeshellarg($path));
$output = shell_exec($cmdline);
Example cli script:
#!/usr/bin/php
<?php
fwrite(STDOUT, print_r($_SERVER, TRUE));
exit(0); // exit with exit code 0
?>
I eventually used the getopt() to get unescaped arguments (I don't know why there is this difference) and str_replace( array( "'", '"'), '', $file_path ); to remove the wrapping quotes.

Categories