Passing a valid path to Python from PHP - php

I have a Python program that parses files, takes a path as and argument and parses all files in the given path and all sub directories - using os.walk(path). I want to call this from my php Web App, so the user can specify a path, which is then passed as an argument to the parser. (Passing a path is ok because its all on an internal network).
I can call the parser fine and pass the arguments ok using popen(), but the path that the Python program receives is always invalid. I have had the php script output the command it is sending to the browser. If I copy and paste that command into a command window, the parser works fine.
I know the path the php script passes is invalid from the result of os.path.exists(path) in the Python script
This is the code to call the Python program:
$path = $_REQUEST['location'];
echo "Path given is: ".$path;
$command = 'python C:\Workspaces\parsers\src\main\main.py '. intval($mode).' "'.$path.'"';
echo "<p>".$command."</p>";
$parser = popen($command, 'r');
if ($parser){
echo "<p>Ran the program</p>";
while (!feof($parser)){
$read = fgets($parser);
if (!$read)
echo "<p>Reached end of file</p>";
else
echo "<p>".$read."</p>";
}
}
The command echoed in the browser is like:
python C:\Workspaces\parsers\src\main\main.py 2 "I:\Dir1\Dir2\Dir3"
Where the 2 is just another argument to the script and $_REQUEST['location'] is defined from an input text box in a form on the calling page.
This is on a Windows system, so I am assuming this has something to do with the backslashes in the path.
Basically, I am unsure as to how all the backslashes are being handled. I would like to understand how strings containing backslashes are sent to the php page, and how they are sent again using popen(). I think the result being printed to the browser is not the raw command string, and I can't be sure how many backslashes are really in the command being issued by popen().
If anyone has any ideas I'd really appreciate it.
Edit:
So in the Python program the path is used as follows:
nfiles=0
print 'Parsing all files in directory tree '+path+"<br />"
start = time.time()
if not os.path.exists(path):
print "<p>Path is NOT REAL!!!</p>"
else:
print "<p>Path IS real!</p>"
for root, dirs, files in os.walk(path):
for f in files:
file = os.path.join(root,f)
print file
nfiles+=1
...Code to run parser...
print nfiles, "Files parsed<br />"
This is echoed back to the browser from the $read variable.
Output of that is:
Parsing all files in directory tree I:\Dir1\Dir2\Dir3
Path is NOT REAL!!!
0 Files parsed
This is identical to the output if the command is run from the command line (the command being copied from the browser and pasted into the cmd window). EXCEPT, when run that way the path IS real, and all the files are parsed. (and in the command window the html markup shows too)
The web server and parsers are hosted on my local machine.

Check to see what user the PHP server is running as. If I:\ is a network drive, don't expect those to be mapped under that user. Use a UNC path instead.
Things to try:
a different path (we know C:\Workspaces\parsers\src\main\ works, why don't you try that?)

Related

Want to open a vm through php code using virsh command

I want to open a vm through following php code:
<?php
$output = shell_exec("virt-viewer --connect qemu:///system 1 2>&1");
echo "<pre>$output</pre>";
?>
I already set the permission of a file with read,write and execute.
I am getting the following error:
(virt-viewer:15162): Gtk-WARNING **: 22:45:33.686: cannot open display:
please help if i am missing something or doing something wrong.
Thanks
How web page works:
Browser makes request to web server, web server delivers html and optionally other asset files (css, js..), but generally, html is loaded first and it stays as it is - content is not changed (except if it's changed by JS, which is not the case here).
Your call will execute some shell command it will return some response (some text) and you'll get it inside some var. If you display that static text as part of your page how do you expect that it will act as GUI?!?
That's just not possible. Imaging that you are calling from shell_exec() exe file of some video game? Will the game then run in the browser?!?
You can call shell commands in order to trigger some action on server (i.e. rescale some image, process some video) or to collect some response (i.e. free disk space or something). But expecting that if you call something form shell will appear in browser is just not realistic.

How to use exec method to start exe application and pass arguments in PHP?

It sounds very simple but I must be missing something here. I have a custom exe program, which is inside C:\dummy\dummytest.exe and I have a text file inside C:\text\test.txt . All I want to do is start dummytest.exe by passing test.txt as argument in PHP. Here is what I tried:
$arg = "C:\text\test.txt"
exec("C:\dummy\dummytest.exe".$arg);
I tried with just single '\' also. And I tried
exec("C:\dummy\dummytest.exe $arg"); but nothing seems to work. I get C:\dummy is not recognized as an internal or external command, operable or batch file error.
When I go to command line manually and do
C:\dummy\dummytest.exe test.txt
the application runs just fine. What am I missing here with exec?
Use the "shell_exec" command instead.
shell_exec("[BAT or EXE-File] [Params]");
Hope this helps!
EDIT
When using executables and parameters with paths you have to quote them.
So, an example would look like this:
echo nl2br(shell_exec("\"F:\\N3V Games\\Trainz Simulator 12\\compile_gs.bat\" \"F:\\xampp\\htdocs\\SHELL\\EBuLa.gs\""));
This example prints the output of a CMD-Window directly to the page.
If the executable is placed in the same directory like the php-file you can just run:
echo nl2br(shell_exec("compile_gs.bat EBuLa.gs"));

Send data from php to python and back

I have been searching for a while in how to successfully exec a Python script through PHP, just for a test thats all.
I've never actually worked with Python and a while since I programmed in PHP but looked for a simple code to send data from PHP to Python and then in .py send back data to PHP.
I have tried exec in PHP, with and without json enc/dec without any success.
These are the commands that have I tried in PHP:
* $result = shell_exec('pythontest.py' . escapeshellarg(json_encode($data)));
* exec("python pythontest.py", $resultData);
var_dump($resultData);
with no success.
In pythontest.py: a print to send back data.
Tried with full paths of both Python and pythontest.py (PHP).
enc/dec with json works in PHP file so nothing seems to be wrong in the PHP code still I can't run the script!
As I said, I haven't worked with Python before so I wonder if there is more needed than just writing the code in the script in order to make it work?
I have seen many posts about this and tried their code that "would work for them" but not for me^^
Additional info: PHP through WAMP, .py in same map. It is supposed to be web based, if that makes it difference.
Check to make sure that the directory containing python.exe is in the PATH of your PHP script (via getenv('PATH')).
Try running python c:\path\to\pythontest.py directly via a Windows command prompt. Does that work? If not, debug PATHs and issues from there, then try again in PHP.
If your WAMP stack runs PHP with limited permissions, check to make sure that user has "Read and execute" type permissions on the python.exe file, as well as the entire directory which contains it, recursively. This might be overkill, but recursively setting perms for that user on the whole python distribution directory rules out permissions-related problems.
Try qualifying the python executable's name with .exe, e.g. c:\python27\python.exe pythontest.py (you might have tried that anyway, since you say you tried with "full paths", but I'm throwing it out there to make sure you included the .exe).
Try replacing the contents of pythontest.py with something extremely simple (e.g. print 'hello') and check whether or not behavior changes.
Also, please post the contents (or at least first lines) of pythontest.py.
I have now tried changing the path, as python.exe was not in the same directory.
My end result on this was
$output = getenv('PATH');
echo "Real Path: " . $output . "<br>";
$ret = apache_getenv("PATH");
echo "Apache Path: " . $ret . "<br>";
apache_setenv("PATH", "C:/Python33");
$ret = apache_getenv("PATH");
echo "Apache new path: " . $ret . "<br>";
$output = getenv('PATH');
echo "Real path, hopefully changed: " . $output . "<br>";
this was just to see if i could change the path, since i have never done that before.
i have now only
import sys, json
print ("hello")
in my python file and tried to run it through cmd, and it worked.
but when i try run it with php, it fails once again.
i have also looked over the permissions:
admin, user have permission to read and execute, i even added "Everyone" with full permission on folder and sub-folder/files just to see if that made any difference.
something i have missed or did i do something wrong with permission, python code or paths ?

Linux command populate file from php script output

I have a PHP script which generates some complex XML output. The XML is currently being output as a webpage but instead of a webpage I need it as a physical file on my server.
So, I wonder if there is a way to pipe the output of my PHP script into the Linux touch command so that my PHP output populates, or overrides, a file on my server?
I am currently trying the following code without success:
touch test | php xml_reports.php
You can actually run PHP from the command line.
php filename.php
So if your php file consisted of:
<?php
echo "Hello World";
?>
The output would be "Hello World" (without the quotes) in your terminal. So if you were writing an application in PHP, try and think about how you would approach it without the browser rendering your output. I hope that helps.
[edit]
You might also want to look into shell_exec. (http://php.net/manual/en/function.shell-exec.php)
Assuming I understand your question correctly, here is a solution. In this case however, rather than piping the PHP output, the PHP code itself outputs a copy of the file on the server. I'm not sure how vital it is that this is done through a linux pipe. Also note that this solution is copied from http://forums.codewalkers.com/showpost.php?p=40350&postcount=3.
1) at the very start of your script put this line :
ob_start();
2) at the very end of your script, put this:
$page = ob_get_contents();
ob_end_flush();
$fp = fopen("output.html","w");
fwrite($fp,$page);
fclose($fp);
And, bam, you should have the whole page in a file called output.html.
Now, one thing you need to be sure of is that the webserver server can
write the file output.html. That means you need to make sure the
webserver has the permissions to write in whatever directory you plan
to store that file in.
How does it work? Basically, it just buffers all output from your
script. Then, you store that buffer into a string. Then you send the
buffer to the browser. Then you store that string in a file...

Bizarre file_get_contents() behavior with plain-text files & no extension?

I've been working on a local app over the last few days and I've noticed that one of my 'exec()' functions to call an external program didn't fire correctly. Upon further investigation it was obvious that the program did execute, but it quit prematurely as an important line utilizing 'file_get_contents()' didn't retrieve the contents of the file specified.
The file is a plaintext file without an extension. I'm guessing that 'file_get_contents()' is treating the file as a directory since there is no extension? It's strange because if I manually execute the same program from a web browser, everything works perfectly.
Here's an example line for clarity -
while(file_get_contents('plaintextfile') == "something"){
/// Do This
}
The above works just fine when I visit /program.php from a web browser, but when calling it like this it gives me a file/folder not found error for 'plaintextfile'.
exec('php /program.php', $output);
foreach($output as $output){
print $output . "<br>";
}
Thanks in advance to anyone who can shed some light on this situation. I'm really puzzled by this...
PHP as executed from the browser and executed by the command line (in the exec() call) may use different php.ini configurations, and may have different file search paths. The best course of action is to supply the full path to plaintextfile.
if(!file_get_contents('/path/to/plaintextfile')){
// file couldn't be read
}

Categories