Run scripts in php - php

I am running a python script through my php. It works fine on console but returns null when I run it on browser.I even tried writing output to a file, but it doesn't return anything.
The php code is:
<?php
$y = "python Code.py";
$output = shell_exec($y);
if($output!=null){
echo $output;
}
else {
echo "No output";
}
$myfile = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($myfile, $output);
fclose($myfile);
?>

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
#!/usr/bin/env python **is this in the first line of you python script?**
chmod +x /usr/custom/test.py

Related

sudo_exec returns nothing

I try to ping www.google.de with shell_exec and store the result into a variable but i get no result back from shell_exec.
<?php
$ping = 'sudo ping -c 4 ';
$url = 'www.google.de';
$command = $ping . $url;
$ping_result = shell_exec($command);
$datei = fopen("/var/www/myProject/result_ping","w") or die ("Could not open file!");
sleep(10);
if ($datei == false)
{
$ping_result = "Cannot open file!";
}
else
{
fwrite ($datei , $ping_result);
fclose ($datei);
}
echo $command; //Output: sudo ping -c 4 www.google.de
echo $ping_result; //Output: nothing
?>
The file result_ping has all rights (chmod 777).
Maybe the webserver is not allowed to execute ping?
Add 2>&1 to your command to ensure you're not getting an error message that shell_exec would filter off:
$command = $ping . $url . ' 2>&1';
shell_exec will return NULL in case of error. With that modification you redirect any error message to normal output, thus forcing shell_exec show every message you would normally get on a console session.

Start-Job PHP Script Not Working in Powershell?

I have a PHP script that looks like:
if(file_exists("temp.txt")){
$myfile = fopen("temp.txt", "a") or die("Unable to open file!");
}
else{
$myfile = fopen("temp.txt", "w") or die("Unable to open file!");
}
date_default_timezone_set("America/New_York");
$date = date('m/d/Y h:i:s a', time());
$text = $date . PHP_EOL;
fwrite($myfile, $text);
fclose($myfile);
When I run the above script in Powershell using
php myscript.php
A text file is created and written into.
If I try to run the same file with
Start-Job ScriptBlock {php myscript.php}
I'll get a response like
But my text file is never written into. It seems like Start-Job never starts my PHP script.
How do I get Start-Job to start running PHP scripts?
Ok I'll write an answer about all of this:
From test (with your script as origin) I added some echo to get something in Receive-Job in powershell.
It was obvious the script was running as intended, but not in the expected directory.
So I added a getcwd() within an echo and this show me the working dir for the job (or scriptblock) is my documents directory) and I found the file there wihtin my home\documents.
Here the final script I eneded with:
echo "I'm running in ".getcwd()." !\n";
if(file_exists("temp.txt")){
$myfile = fopen("temp.txt", "a") or die("Unable to open file!");
}
else{
$myfile = fopen("temp.txt", "w") or die("Unable to open file!");
}
echo "Ok, file was opened: \n".print_r(fstat($myfile),1)."\n";
date_default_timezone_set("America/New_York");
$date = date('m/d/Y h:i:s a', time());
$text = $date . PHP_EOL;
$r=fwrite($myfile, $text);
echo "Write in file returned $r \n";
fclose($myfile);
echo "File closed\n";
And that is the output is with Powershell:
Start-Job -ScriptBlock { D:\wamp\bin\php\php5.4.3\php.exe D:\wamp\bin\php\php5.4.3\test.php }
Id Name State HasMoreData Location Command
-- ---- ----- ----------- -------- -------
51 Job51 Running True localhost D:\wamp\bin\php\php5....
And retrieving the output:
Receive-Job 51
I'm running in C:\Users\my_name\Documents !
Ok, file was opened:
Write in file returned 24
File closed
Hope it will help.

php realtime output of console process

i want to run a command in console then 'echo' it via a log file. i wrote following code. but it doesnt work. if i put command direct in 'popen' it waits first the page load..
what can be done ?
shell_exec("nohup $cmd > out.log 2>&1");
if( ($fp = popen("tail out.log" , "r")) ) {
while( strpos($txt, "FINISH") == false){
$txt = fread($fp, 1024);
echo $txt;
flush();
}
}

allow php invoked by exec() to write to console

I invoked a php file by exec() doing this :
<?php
$cmd = "php -q nah.php";
exec($cmd);
echo "lalal";
?>
and the nah.php has this :
<?php
echo "yaya";
sleep(3);
?>
It does sleep for 3 seconds but the file can echo out to the command.
How can I do echo the output from nah.php
If you want to capture the output of another process, then you can use backticks
$output=`command line`;
or capture it with exec()
exec('command line', $output);
However, both of these techniques only give the output when the external process has run to completion. If you want to grab the output as it happens, you can use popen (or proc_open for more control), e.g. something like this
$handle = popen('command line 2>&1', 'r');
while (!feof($handle))
{
$read = fread($handle, 2096);
echo $read;
}
pclose($handle);
The 2>&1 at the end of the command line is a handy idiom if running within a shell like bash. It redirects stderr to stdout, so any errors the command generates will be returned to PHP. There are more advanced ways to capture stderr, this just makes it easy.
Change your first script to:
<?php
$cmd = "php -q nah.php";
echo `$cmd`;
echo "lalal";
exec() creates a new console and executes the php file there, it returns the output in an array (One element per line return) that is passed in as a second argument. So if you change your code to:
<?php
$output = array();
$cmd = "php -q nah.php";
exec($cmd, $output);
$lines = count($output);
for($i = 0; $i < $lines; $i++)
echo $output[$i];
echo "lalal";
?>

Starting a bash script from a php script

I'm trying to run a bash script using shell_exec but It doesnt seem to work. (Nothing seems to happen) I'm using nginx and the latest php5-cgi. Heres what the php file looks like:
<?php
$startserver = "./startserver.sh";
$startserver = shell_exec($startserver);
$getprocess = "pidof hlds_amd";
$pid = shell_exec($getprocess);
$fh = fopen('closeserver.sh', 'w');
$command = "kill -9 $pid";
fwrite($fh, $command);
fclose($fh);
$string = "at -f closeserver.sh now + 1 hour";
$closer = shell_exec($string);
?>
and this is what the bash script looks like:
#!/bin/bash
cd /home/kraffs/srcds
./hlds_run -game cstrike -autoupdate +maxplayers 12 +map de_dust2 > hlds.log 2>&1 &
Theres no errors in the phpscript and the file gets created just fine but $startserver doesnt seem to get executed and $pid is empty. Did I miss something in the php file or do I need to change permissions for an user? Thanks for your help.
replace shell_exec, with below function and try again
<?php
function runcmd($EXEC_CMD)
$handle = popen ($EXEC_CMD, 'r');
$output = "";
if ($handle) {
while(! feof ($handle)) {
$read = fgets ($handle);
$output .= $read;
}
pclose($handle);
}
return $output;
}
?>

Categories