how to call php page with 3 arguments from powershell - php

below is my PS1 code to call PHP. But I want to know how to call the PHP page with 3 arguments and how to get it in PHP.
$workflow_id = 170
$task_num = 3
$next_script = 'testing.php'
$PhpExe = "C:\Admin\bin\php\php7.4.26\php.exe"
$PhpFile = "C:\Admin\www\xpress\"+$next_script+" "+$workflow_id+" "+$task_num
echo $PhpFile
$PhpArgs = '-f "{0}"' -f $PhpFile
$PhpOutput = & $PhpExe $PhpArgs
echo $PhpOutput // could not open file. but the file is present in this path
// testing.php
<?php include("commons/connection.php"); ?>
<?php
$workflow_id = $argv[1];
$task_num = $argv[2];
$update_pass = "UPDATE workflow_details SET Status ='mm' where `Workflow_Number` = $workflow_id and Work_type = 'PrepWork' and Task_Number = $task_num " ;
$status_result=mysqli_query($con,$update_pass);
?>
I am getting could not open file. while running ps1

Your attempt to call your PHP script from PowerShell is flawed in two respects:
$PhpArgs is a single string, which is therefore passed as a single argument, whereas you need to pass -f and the PHP script file name/path as individual arguments.
You're not passing any arguments to pass through to the PHP script.
Therefore, invoke $PhpExe as follows:
# Call script file $PhpFile with the values of $workflow_id and $task_num
# as arguments, and capture the output in variable $PhpOutput
$PhpOutput = & $PhpExe -f $PhpFile -- $workflow_id $task_num

Related

the php code is unable to open the python script

i was trying to open and read a pdf from php using python. but after executing the php code in my browser, its not redirecting to python script.
i want my php code to execute the python script and return the output to
php
php code:
<?php
$command = escapeshellcmd("python filename.py");
$output = shell_exec($command);
echo $output;
?>
python code:
this code will read the pdf from the directory and extracts required data from the pdf and gives the corresponding result as an output to the php code which is printed on the browser
import PyPDF2
import re,time
import sys
start_time =time.time()
# open the pdf file
address="pv3.pdf"
object = PyPDF2.PdfFileReader(address)
#print('hello')
# get number of pages
NumPages = object.getNumPages()
l = list()
# extract text and do the search
for i in range(0, NumPages):
PageObj = object.getPage(i)
Text = PageObj.extractText()
l.append(Text)
#print(len(l))
#print(l[0])
d={}
count=0
for i in range(len(l)):
x = l[i].split('\n')
for j in range(len(x)):
if re.search('[0-9]{8}',x[j]) and (j!=len(x)-1 and re.search('-',x[j+1])==None):
#print(x[j],'in page',i+1,',line no',j+1)
count +=1
str = ''
temp =0
for m in range(j+1,len(x)):
if '~na' not in x[m]:
str+=x[m]
else:
temp = 1
break
if temp==0:
#print('hello')
y=l[i+1].split('\n')
for n in range(len(y)):
if '~' in y[n]:
break
str+=y[n]
# if d[x[j]]==None:
d[x[j]]=str
for x,y in d.items():
print(x,"::::",y,"...,")
print()
#print(l[i])
#print(d)
#print('No of matches are',count)
#print(l[0])
end_time = time.time()
#print('Total time taken :',end_time-start_time)

How can I pass a text file created by php to my python script for processing?

I have a php code that is writing the user input on the webpage into a text file. I wish to pass the text file into my python script that looks like follows:
PHP Script (getfile.php)
<?php
function writetofile($file, $content, $writeType){
$fo = fopen($file, $writeType);
if($fo){
fwrite($fo,$content);
fclose($fo);
}
}
?>
Python Script (predict.py)
clf=joblib.load('model.pkl')
def run(command):
output = subprocess.check_output(command, shell=True)
return output
row = run('cat '+'/Users/minks/Documents/X-test.txt'+" | wc -l").split()[0]
print("Test row size:")
print(row)
matrix_tmp_test = np.zeros((int(row),col), dtype=np.int64)
print("Test matrix size:")
print(matrix_tmp_test.size)
What I am asking is, after writing to a file : $file in php, how can I then pass this file to replace:
row = run('cat '+'/Users/minks/Documents/X-test.txt'+" | wc -l").split()[0]
where the path gets replace by $file and the processing continues? Also, is it possible to pass $file directly to the python code via command line? I am little confused on how this entire passing and processing can be carried out.
Dow you want something like this?
PHP:
$path = "my.txt";
system("python predict.py $path");
Python:
row = run("cat %s | wc -l" % sys.argv[1]).split()[0]

Running a python file from php does not generate the output file

I have a problem running another file from php. I want my php params to be the output of running a python file that calls another file itself.
Here is my php file:
<?php
if (isset($_POST['submit'])) {
$params = solve();
}
function solve() {
exec("python array.py", $output);
return $output;
}
?>
If array.py is simply:
if __name__ == "__main__":
print 1
print 2
print 3
print 4
I will get 1,2,3,4 for my output, but I as soon as I change array.py to the following file that calls os.system, I don't get anything. So the new array.py is:
import os
def main():
os.system("python test.py") #test.py creates tmp.txt with 4 lines w/ values 1,2,3,4
def output():
f = open("tmp.txt", "r")
myReturn = []
currentline = f.readline()
while currentline:
val = currentline[:-1] #Getting rid of '\n'
val = int(val)
myReturn = myReturn + [val]
currentline = f.readline()
f.close()
return myReturn
if __name__ == "__main__":
main()
o = output()
print o[0]
print o[1]
print o[2]
print o[3]
Also if I just run test.py, the output is the file tmp.txt:
1
2
3
4
So now, when I run my php file, the output tmp.txt is not even created in the directory and as a result I don't get any output from my php either.
I am not sure why this is happening because when I just run array.py myself, I get the desired output, and the tmp file is created.
EDIT:
I forgot to include: import os above.
Change exec to:
exec("python array.py 2>&1", $output)
Or check the web server or php error log. This will return the error output from the python script to your php script (not normally what you want in production).

Running a script from another script with session data

I am trying to have a script start another script and put its data into a session variable for the other script to use. The problem is that when the second script, data.php, runs it doesn't seem to be able to access the session variables. They are blank and nothing gets written to data.txt. If I run data.php by itself it writes the last value that $_SESSION["data"] was set to properly, but not when it's run with exec. I am not sure what the problem is. Any ideas?
input.php:
session_start();
$_SESSION["data"] = "Data!";
exec("/usr/bin/php /path/to/data.php > /dev/null 2>&1 &");
data.php:
session_start();
$fp = fopen('data.txt', 'w');
fwrite($fp, $_SESSION["data"]);
fclose($fp);
Edit: I am trying to start data.php from inside input.php and have the variables from input.php accessible in data.php.
You can pass data to PHP scripts running with the CLI as command line arguments. This data will be available to the child script in the $argv array.
input.php:
$arg = "Data!";
exec("/usr/bin/php /path/to/data.php ".escapeshellarg($arg)." > /dev/null 2>&1 &");
data.php
$fp = fopen('data.txt', 'w');
fwrite($fp, $argv[1]);
fclose($fp);
A couple of notes:
It is important to pass each argument through escapeshellarg() to ensure that users are not able inject commands into your shell. This will also stop special shell characters in arguments from breaking your scripts.
$argv is a global variable, not a superglobal like $_GET and $_POST. It is only available in the global scope. If you need to access it in a function scope, you can use $GLOBALS['argv']. This is about the only situation in which I consider the use of $GLOBALS acceptable, although it is still better to handle the arguments in the global scope on startup, and pass them through the scopes as arguments.
$argv is a 0-indexed array, but the first "argument" is in $argv[1]. $argv[0] always contains the path to the currently executing script, because $argv actually represents the arguments passed to the PHP binary, of which the path to your script is the first.
Values from command line arguments always have a string type. PHP is very promiscuous with its typing so with scalar values this doesn't matter, but you (fairly obviously) can't pass vector types (objects, arrays, resources) through the command line. It is possible to pass objects and arrays by encoding them with e.g. serialize() or json_encode(). There is no way to pass resources through the command line.
EDIT When passing vector types I prefer to use serialize() because it carries with it information about the classes that objects belong to.
Here is an example:
input.php:
$arg = array(
'I\'m',
'a',
'vector',
'type'
);
exec("/usr/bin/php /path/to/data.php ".escapeshellarg(serialize($arg))." > /dev/null 2>&1 &");
data.php
$arg = unserialize($argv[1]);
$fp = fopen('data.txt', 'w');
foreach ($arg as $val) {
fwrite($fp, "$val\n");
}
fclose($fp);
Here is a couple of functions from my clip collection I use to simplify this process:
// In the parent script call this to start the child
// This function returns the PID of the forked process as an integer
function exec_php_async ($scriptPath, $args = array()) {
$cmd = "php ".escapeshellarg($scriptPath);
foreach ($args as $arg) {
$cmd .= ' '.escapeshellarg(serialize($arg));
}
$cmd .= ' > /dev/null 2>&1 & echo $$';
return (int) trim(exec($cmd));
}
// At the top of the child script call this function to parse the arguments
// Returns an array of parsed arguments converted to their correct types
function parse_serialized_argv ($argv) {
$temp = array($argv[0]);
for ($i = 1; isset($argv[$i]); $i++) {
$temp[$i] = unserialize($argv[$i]);
}
return $temp;
}
If you need to pass a large amount of data (larger than the output of getconf ARG_MAX bytes) you should dump the serialized data to a file and pass the path to the file as a command line argument.
You could try to urlencode the $_SESSION ["data"] and pass it as an argument to the CLI script:
Script 1
$URLENCODED = urlencode($_SESSION["data"]);
exec("/usr/bin/php /path/to/data.php " . $URLENCODED . " > /dev/null 2>&1 &")
Script 2
$args = urldecode($argv[1]); // thanks for the reminder daverandom ..forgot to do this :)
fwrite($fp, $args);

executing a Windows command line program with system call in PHP

I am trying to execute a program using a system call inside a php file like so:
$newname = 'C:\Users\Jack\Desktop\upload\test.ppt' ;
$program = '"C:\Program Files (x86)\Softinterface, Inc\Convert PowerPoint\ConvertPPT"';
$input = ' /S "'. $newname .'"'
$destination = ' /T "C:\Users\Jack\Desktop\upload\\"';
$switch = ' /C 18';
$command = $program . $input . $destination . $switch;
system($command);
For some reason, the program enters an infinite loop (the browser never stops loading). I have tried the command manually and it works perfectly (takes about 2 sec to complete) but when executing it with a php file doesn't work.
use the backtick(`) symbol to wrap around the command you want to run.

Categories