header("location:http;//")
Above line does not seem to work when executing PHP scripts from command line. How best can I open links via command line?
A very hastily and quickly tested method might be to use exec passing in the path to a known browser with the url as it's argument - seemed to work ok.
<?php
$url='https://www.google.co.uk';
$cmd=sprintf( '%%userprofile%%\AppData\Local\Google\Chrome\Application\chrome.exe %s', $url );
exec( $cmd );
?>
Thanks to #Álvaro's comment the above can be simplified further( on Windows at least )
<?php
$url='https://www.google.co.uk';
$cmd=sprintf( 'start %s',$url );
exec( $cmd );
?>
The solution provided above would only work for windows. IT would not work on mac OS . Here is a more general solution
public function open(string $url): void
{
switch (PHP_OS) {
case 'Darwin':
$opener = 'open';
break;
case 'WINNT':
$opener = 'start';
break;
default:
$opener = 'xdg-open';
}
exec(sprintf('%s %s', $opener, $url));
}
header() is HTTP-related only and is used to tell what headers should by returned by the server to the client's browser which performed the request. Location, in particular, simply means Hey ! Check out this place instead: xxxxx.
The client's browser, in turn, will decide by itself if it chooses to follow this advice or not (it usually does) but at no time, the served fetches these informations to re-serve them again to its client.
So the best way to do is to use your script throughout a web browser instead (as it supposed to be). If you want to « open links » from a command line, simply type your browser's executable name followed by an URL (e.g.: firefox http://www.stackoverflow.com).
If what you want to do instead is fetching files or specific pages from a remote web server, use a command line client such as wget or curl instead.
Related
I try to execute a command "wget" to download a file on my server A and then execute a python who will scrypt argument in this file.
My script:
switch ($_POST["parse"]) {
case 'parse1':
shell_exec("wget http://localhost/".$file_path);
shell_exec("python /opt/lampp/htdocs/mysite/api/scripts/script_parse.py ".$file_path." 1");
echo $file_path;
break;
default:
echo "no";
break;
}
However (I'm with local xampp under debian), the file is not downloaded and I have a page that loads into space when I try to execute the script (with or without file) but that does nothing .
So I'm looking since last night but I can not.
Besides, I like to avoid that the page load until the end of script execution.
Instead of shell_exec() and wget to download the file, use "file_get_contents()`. It supports both the HTTP and the HTTPS protocols, among many others, and it'll also give you an informative error message if downloading fails.
You will also need to add some error handling to your code, as stated in the comment by Arek. Since that is the only way you can properly handle the situations where something goes wrong, and they will. Not only for your sake, to make it easier to detect and debug, but also for your users.
Read the PHP manual, find out what values the different functions return in case of errors, and check against these. If any of the functions does return an erroneous value, then show an error message to the user and abort the rest of business logic (the stuff your code is really meant to do).
I have a server running on Linux that execute commands to 12 nodes (12 computers with Linux running in them). I recently downloaded PHP on the server to create web pages that can execute commands by opening a specific PHP file.
I used exec(), passthru(), shell_exec(), and system(). system() is the only one that returns a part of my code. I would like PHP to act like open termainal command in linux and I cannot figure out how to do it!
Here is an example of what is happening now (Linux directly vs PHP):
When using linux open terminal command directly:
user#wizard:/home/hyperwall/Desktop> /usr/local/bin/chbg -mt
I get an output:
The following settings will be used:
option = mtsu COLOR = IMAGE = imagehereyouknow!
NODES = LOCAL
and additional code to send it to 12 nodes.
Now with PHP:
switch($_REQUEST['do'])
{ case 'test':
echo system('/usr/local/bin/chbg -mt');
break;
}
Output:
The following settings will be used:
option = mtsu COLOR = IMAGE = imagehereyouknow!
NODES = LOCAL
And stops! Anyone has an explanation of what is happening? And how to fix it? Only system displays part of the code the other functions display nothing!
My First thought is it can be something about std and output error. Some softwares dump some informations on std out and some in std error. When you are not redirecting std error to std out, most of the system calls only returns the stdout part. It sounds thats why you see the whole output in terminal and can't in the system calls.
So try with
/usr/local/bin/chbg -mt 2>&1
Edit:
Also for a temporary work through, you can try some other things. For example redirect the output to file next to the script and read its contents after executing the command, This way you can use the exec:
exec("usr/local/bin/chbg -mt 2>&1 > chbg_out");
//Then start reading chbg_out and see is it work
Edit2
Also it does not make sense why others not working for you.
For example this piece of code written in c, dumps a string in stderr and there is other in stdout.
#include <stdio.h>
#include<stdlib.h>
int main()
{
fputs("\nerr\nrro\nrrr\n",stderr);
fputs("\nou\nuu\nuttt\n",stdout);
return 0;
}
and this php script, tries to run that via exec:
<?php
exec("/tmp/ctest",&$result);
foreach ( $result as $v )
{
echo $v;
}
#output ouuuuttt
?>
See it still dumps out the stdout. But it did not receive the stderr.
Now consider this:
<?php
exec("/tmp/ctest 2>&1",&$result);
foreach ( $result as $v )
{
echo $v;
}
//output: errrrorrrouuuuttt
?>
See, this time we got the whole outputs.
This time the system:
<?php
echo system("/tmp/ctest 2>&1");
//output: err rro rrr ou uu uttt uttt
?>
and so on ...
Maybe your chbg -mt writes additional code to stderr instead of stdout? Try to execute your script inside php like this:
/usr/local/bin/chbg -mt 2>&1
The other responses are good for generic advice. But in this specific case, it appears you are trying to change your background on your desktop. This requires many special considerations because of 'user context':
First, your web server is probably running as a different user, and therefore would not have permissions to change your desktop.
Second, the program probably requires some environmental variables from your user context. For example, X programs need a DISPLAY variable, ssh-agent needs SSH_AGENT_PID and SSH_AUTH_SOCK, etc. I don't know much about changing backgrounds, but I'm guessing it involves D-Bus, which probably requires things like DBUS_SESSION_BUS_ADDRESS, KONSOLE_DBUS_SERVICE, KONSOLE_DBUS_SESSION, and KONSOLE_DBUS_WINDOW. There may be many others. Note that some of these vars change every time you log in, so you can't hard-code them on the PHP side.
For testing, it might be simpler to start your own webserver right from your user session. (i.e. Don't use the system one, it has to run as you. You will need to run it on an alternate port, like 8080). The web server you start manually will have all the 'context' it needs. I'll mention websocketd because it just came out and looks neat.
For "production", you may need to run a daemon in your user context all the time, and have the web server talk to that daemon to 'get stuff done' inside your user context.
PHP's system only returns the last line of execution:
Return Value: Returns the last line of the command output on success, and FALSE on failure.
You will most likely want to use either exec or passthru. exec has an optional parameter to put the output into an array. You could implode the output and use that to echo it.
switch($_REQUEST['do'])
{ case 'test':
exec('/usr/local/bin/chbg -mt', $output);
echo implode('\n', $output); // Could use <br /> if HTML output is desired
break;
}
I think that the result of execution, can changes between users.
First, try to run your PHP script directly into your terminal php yourScript.php
If it runs as expected, go to your Apache service and update it to run with your own credentials
You are trying to change the backgrounds for currently logged in users... While they are using the desktop. Like while I'm typing this message. I minimize my browser and 'ooh my desktop background is different'. Hopefully this is for something important like it turns red when the reactor or overheating.
Anyway to my answer:
Instead of trying to remotely connect and run items as the individual users. Setup each user to run a bash script (in their own account, in their own shell) on a repeating timer. Say every 10 minutes. Have it select the SAME file.. from a network location
/somenetworkshare/backgrounds/images/current.png
Then you can update ALL nodes (1 to a million) just by changing the image itself in /somenetworkshare/backgrounds/images/current.png
I wrote something a while ago that does just this -- you can run a command interpreter (/bin/sh), send it commands, read back responses, send more commands, etc. It uses proc_open() to open a child process and talk to it.
It's at http://github.com/andrasq/quicklib, Quick/Proc/Process.php
Using it would look something like (easier if you have a flexible autoloader; I wrote one of those too in Quicklib):
include 'lib/Quick/Proc/Exception.php';
include 'lib/Quick/Proc/Exists.php';
include 'lib/Quick/Proc/Process.php';
$proc = new Quick_Proc_Process("/bin/sh");
$proc->putInput("pwd\n");
$lines = $proc->getOutputLines($nlines = 10, $timeoutSec = 0.2);
echo $lines[0];
$proc->putInput("date\n");
$lines = $proc->getOutputLines(1, 0.2);
echo $lines[0];
Outputs
/home/andras/quicklib
Sat Feb 21 01:50:39 EST 2015
The unit of communication between php and the process is newline terminated lines. All commands must be newline terminated, and all responses are retrieved in units of lines. Don't forget the newlines, they're hard to identify afterward.
I am working on a project that uses Terminal A on machine A to output to Terminal B on Machine B, both using linux for now. I didnt see it mentioned, but perhaps you can use redirection, something like this in your webserver:
switch($_REQUEST['do'])
{ case 'test':
#process ID on the target (12345, 12346 etc)
echo system('/usr/local/bin/chbg -mt > /proc/<processID>/fd/1');
#OR
#device file on the target (pts/0,tty0, etc)
echo system('/usr/local/bin/chbg -mt > /dev/<TTY-TYPE>/<TTYNUM>');
break;
}
Definitely the permissions need to be set correctly for this to work. The command "mesg y" in a terminal may also assist...Hope that helps.
I've seen PHP reading shell_exec live output and PHP: Outputting the system / Shell_exec command output in web browser, but can't get the following working.
NB: originally, my shell script was running some python, but I have simplified it.
live.sh
uname -a
date
watch --no-title date
live.php
<?php
$cmd = "sh live.sh";
while (# ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
echo '<pre>';
while (!feof($proc))
{
echo fread($proc, 4096);
# flush();
}
echo '</pre>';
?>
The uname and date outputs appear in the browser okay, but the watch output does not.
Am I in fact attempting the impossible?
I would advise against the approach of using watch, and you are probably in for more trouble than you expect.
Firstly, long running command might be affected by the (default) PHP timeout, so you may have to tweak that.
Then, watch probably uses terminal sequences to clear the screen, and I am not sure how this translates to the output code.
I would rather suggest setting up a client side mechanism to periodically repeat a call to the sever side live.php.
This post on SO will help you get started.
jQuery, simple polling example
the page above uses the jquery library, but you could use native Javascript equivalent if you want to.
The simplest example (from that page) would be :
function poll(){
$("live.php", function(data){
$("#output_container").html(data);
});
}
setInterval(function(){ poll(); }, 5000);
In your page, set up a container for your results
<div id="output_container"></div>
In your example, you remove the watch from your script and replace it with the command you intended watching.
You probably want this only for some special thing. So, for those you can try ajaxterm.
Really easy to use, (4.line installation)
wget http://antony.lesuisse.org/software/ajaxterm/files/Ajaxterm-0.10.tar.gz
tar zxvf Ajaxterm-0.10.tar.gz
cd Ajaxterm-0.10
./ajaxterm.py
and you will get full bash running interactively in the browser. (after the login/password). Written in python, so easily adaptible for you. Also, see here.
I have PHP code that requires other php files by address $_SERVER['DOCUMENT_ROOT'].'/subdir/file.php';
First of all -- is this the best proper way to include things? Obviously I don't want to use path like '../../subdir/file.php'; because moving the file would break it.
But another interesting issue is that if I run this file through command line then $_SERVER is not created. I can fake it via $_SERVER['DOCUMENT_ROOT'] = '.'; but I'm curious to if this is the best practice. Seems like not.
Edit: Obviously there are many ways to skin this cat, although I think the best practice is to define a variable (or a constant) responsible for the include directory. Such as:
define('INC_DIR', $_SERVER['DOCUMENT_ROOT'].'/../includes');
or
if (PHP_SAPI == 'cli') {
$_includes = '../includes';
} else {
$_includes = $_SERVER['DOCUMENT_ROOT'].'/../includes/');
}
And use the aforementioned variable or constant throughout the code.
I prefer to use a folder definition system in my architectures. Something like this:
define( 'DIR_ROOT',dirname(__FILE__) );
That works both in command line and web mode. Use that in your application entry point (index.php in most cases) and then load the rest of your framework from that file outward. All inbound calls to your application should be routed via .htaccess or other method so that they call index.php?foo=bar etc.
I also hate typing DIRECTORY_SEPARATOR all the time so I usually make the first definition:
define( 'DS' , DIRECTORY_SEPARATOR );
This enables you later to do something like this:
require_once( DIR_ROOT.DS.'myfolder'.DS.'myfile.class.php' );
Alternatively if you don't want or need to modify your php files and you just need a page to be executed normally you could use curl. Most Linux and Unix systems have it installed.
$ curl http://www.example.com/myscript.php &> /dev/null
The &> /dev/null part sends the output into a black hole in the system so you don't have to see the HTML which was returned by the request.
if(PHP_SAPI == 'cli')
{
$_SERVER['DOCUMENT_ROOT'] = '/path/to/webroot';
}
I have a PHP script that creates other PHP files based on user input. Basically, there are files containing language specific constants (define) that can be translated by the user. In order to avoid runtime errors, I want to test newly written files for parse errors (due to "unusual" character sequences). I have read several posts here on SO (like PHP include files with parse errors) and tried a function that uses
$output = exec("php -l $filename");
to determine whether a file parses correctly. This works perfectly on my local machine, but at on the provider's machine, the output of calls to exec("php ...") seems to be always empty. I tried a call to ls and it gives me output, leading me to the assumption that PHP is somehow configured to not react to command line invocations or so. Does anyone know a way around this?
EDIT: I forgot to mention, I had already tried shell_exec and it gives no result, either. In response to sganesh's answer: I had tried that too, sorry I forgot to mention. However, the output (second argument) will always be an empty array, and the return value will always be 127, no matter if the PHP file to test has syntax errors or not.
I had the same problem. The solution that worked for me was found in running-at-from-php-gives-no-output. I needed to add output redirection.
$output = exec("php -l $filename 2>&1");
You can try with exec second and third arguments.
second argument will have the output of the command.
third argument will have the return value.
And exec will return only last line of the command.
$filename = "a.php";
$output = exec("php -l $filename",$op,$ret_val);
print $output."\n";
print $ret_val."\n";
var_dump($op);
By executing shell_exec(), you can see the output as if you executed that file via command line. You can just see if there is an error right here.
<?php
if (strpos(shell_exec('php -l file.php'), 'Syntax Error')) {
die('An error!');
}
There may also be a possibility that shell_exec() or exec() may be disable by your host.
Nice idea to check the file validity :-)!
Now, from the PHP manual for exec():
Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have components in the path to the executable.
Can you check if this is not the case for you?
Also, can you check by providing the full path of the PHP interpreter in the exec() instead of only php. Let me know how you fare.
Pinaki
the correct way is to add >2&1 as tested on a windows system using imagemagick!
I worked around my original problem by using a different method. Here is what I do now:
Write a temporary file with contents <?php include "< File to test >"; echo "OK"; ?>
Generate the correct URL for the temporary file
Perform HTTP request with this URL
Check if result equals "OK". If yes, the file to test parses without errors.
Delete temporary file
Maybe this could be done without the temporary file by issuing an HTTP request to the file to test directly. However, if there is a parse error and errors are suppressed, the output will be empty and not discernible from the output in the case of a file that gives no parse errors. This method is risky because the file is actually executed instead of just checked. In my case, there is only a limited number of users who have access to this functionality in the first place. Still, I'm naturally not entirely happy with it.
Why the exec() approach did not work, I still do not know exactly. pinaki might be right by suggesting to provide the full path to the PHP executable, but I cannot find out the full path.
Thank you everyone for answering, I upvoted you all. However, I cannot accept any of your answers as none of your suggestions really solved my problem.