I have a script which can be called both from browser and CLI. It produces output, so adding a new line is a must. But, if youre viewing from a browser, the .php should use <br> while watching from CLI its the \r\n or PHP_EOL:
echo 'output1';
if $browser
{
echo '<br>';
}
else
{
echo "\r\n";
}
echo 'output2';
Isnt there any universal character?
Versions of PHP binaries could vary, for example on servers that have fastcgi the php binary might point to
php-cgi.
So to test cli in an interface independent manner checking the contents of the $_SERVER variable for example is a more preferred way.
I think this would handle all the checks from whether the script is run from
Command line
As a cron job
PHP binary
Browser
function is_cli() {
return ((empty($_SERVER['REMOTE_ADDR']) and ! isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) ||defined('STDIN')) ? true : false;
}
echo 'output1';
if (is_cli()) {
echo "\r\n";
} else {
echo '<br>';
}
echo 'output2';
Related
I've been looking up how I can debug PHP code in Chrome or Firefox but I can;t really find a solution. This is my PHP:
<?php
if(isset($_POST["data"]))
{
$var = $_POST["data"];
print "your message: " . $_POST["data"];
if(!empty($_POST['ip.data'])){
$data = $_POST['ip.data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
}
?>
I want to be able to see the output of print "your message: " . $_POST["data"]; or any errors in Chrome or Firefox. I've tried Firefox Quantum that should be able to debug php? Anyways, how can I console log this?
The first step is to recognize that PHP, which is generally a server side language is a completely different context than the browser's console, which is fundamentally Javascript. Thus, to show messages to the browser's console from the server, you will need to find some way to communicate those messages (e.g., errors) to the browser.
At that point, you might consider something as simple as embedding a script tag with your PHP:
function debugToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.debug( \"PHP DEBUG: $msg\" );</script>";
}
function errorToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.error( \"PHP ERROR: $msg\" );</script>";
}
function warnToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.warn( \"PHP WARNING: $msg\" );</script>";
}
function logToBrowserConsole ( $msg ) {
$msg = str_replace('"', "''", $msg); # weak attempt to make sure there's not JS breakage
echo "<script>console.log( \"PHP LOG: $msg\" );</script>";
}
# Convenience functions
function d2c ( $msg ) { debugToBrowserConsole( $msg ); }
function e2c ( $msg ) { errorToBrowserConsole( $msg ); }
function w2c ( $msg ) { warnToBrowserConsole( $msg ); }
function l2c ( $msg ) { logToBrowserConsole( $msg ); }
if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {
if ( isset( $_POST['data'] ) ) {
d2c( "Your message: {$_POST['data']}"
e2c( "This is an error from PHP" );
w2c( "This is a warning from PHP" );
l2c( "This is a log message from PHP" );
...
}
}
But this will be a fundamentally weak and brittle approach. I would suggest instead tailing your log files on the server directly. If you are after some color, consider using clog, lwatch, or grc:
$ grc tail -f /var/log/syslog
echo "console.log( 'Debug Objects: " . $output . "' );";
I ran through the same problem recently, just couldn't find a simple enough way without installing some large external package.
I first tried the obvious way:
<?php echo "<script>console.log(".$myVar.")<script>" ?>
but it only works with scalar types. For example:
<?php
$arr = [ 'x' => 42 ];
echo "<script>console.log(".$arr.")</script>";
?>
will output to the html
<script>console.log(Array)</script>
a solution to this is to use json_encode on the variable in the php side, then JSON.parse it in the javascript and finally console.log.
However this approach fails to capture non public properties of objects:
<?php
class Test {
private $x = 42;
public $y = 13;
}
$obj = json_encode(new Test());
echo "<script>console.log(JSON.parse('".$obj."'))</script>";
?>
will output to the browser console:
{y: 13}
Because private/protected fields can't be accessed by json_encode.
The solution here is either to add a __toString method to your class where you properly expose those fields as strings, or use some hack like calling var_export then process the output string to make it json_encode-able.
I ended up writing a small helper using the latter approach, and an output prettifier in the javascript side
Leaving the link here if anyone wants to use it.
If you want to see errors on an Ubuntu machine and you run an Apache server, you can constantly monitor and output changes to the error.log file in the apache folder with this command:
tail -f /var/log/apache2/error.log
If you have a server running on apache then this will output any errors occurred.
The tail command simply outputs the last 10 lines of a file and updates when new data is piped into the file.
I hope will help:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Try this
<?php
function temp()
{
if(isset($_POST["data"]))
{
$var = $_POST["data"];
print "your message: " . $_POST["data"];
if(!empty($_POST['ip.data'])){
$data = $_POST['ip.data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
}
}//function
?>
<script>
console.log(".<?php temp(); ?>.");
</script>
On Chrome, you can use phpconsole which works quite well.
If anybody knows of something similar for Firefox Quantum please comment.
I want to create my own little control panel for my minecraft server,
I got problems with executing commands in php.
So if I want to execute a .sh file in PHP It works, I tried to do an output with
echo "xyz"
This works, but if I try to start a server, it doesnt..
My Server-Start-File:
echo "$1 's Server is starting with $2 MB of RAM"
screen -AmdS $1 java -Xmx$2M -jar spigot1649.jar
My PHP-Script:
<?php
$x = shell_exec('./start.sh test 512');
if($x) {
echo "Started";
echo "" . shell_exec('./start.sh test 512');
} else {
echo "Failed";
}
?>
My first time to deploy matlab exec in php and i need ur help.
I have a matlab script compiled as sampleExe.exe (standalone app) with a single argument 'IdNo' to processes images. When i call it thru command line using sampleExe 2014000, the program runs and gives the desired output. However, I am having trouble when deploying/calling sampleExe.exe file from php as it gives me no output at all. :(
Here's the code i tried based on this: Call matlab exe from php is not working well
<?php
define("EVAL_IMAGE","sampleExe.exe");
$target=isset($_REQUEST['IdNo'])?trim($_REQUEST['IdNo']):"";
if($target==""){
echo "No folder name is passed";
exit();
}
passthru(EVAL_IMAGE." ".$target);
?>
Any help is very much appreciated. Btw, I tried running it in a localhost and sampleExe.exe is also save in c:/wamp/www
<?php
try {
define("EVAL_IMAGE","mainProg1.exe");
$target=isset($_REQUEST['IdNo'])?trim($_REQUEST['IdNo']):"";
if($target==""){
echo "No folder name is passed";
exit();
}
set_time_limit(300);
$return = exec(EVAL_IMAGE." ".$target);
echo "return = " .$return;
}catch (Exception $e) {
echo 'Message: ' .$e->getMessage();
}
exit(0); ?>
how can I check if a php ping returned succesfull or failed using php exec, I have in mind something with a while loop but I'm not sure if ts the best approach, I tried:
exec('ping www.google.com', $output)
but I would have to do a var_dump($output); to see the results, I want for each line the ping command returns to check it
$i = 2;
while(exec('ping www.google.com', $output)) {
if($output) {
echo 'True';
} else {
echo 'False';
}
}
I know this code is WRONG but its kind of what I need, if any of you could give me a head start on how to do it or suggestions I would really appreciate it....THANKS!!
This should do it:
if(exec('ping http://www.google.com')) {
echo 'True';
} else {
echo 'False';
}
I suggest you could use CUrl See Manual but that all depends upon what you are trying to achieve.
Provide more data if needed.
NOTE
You are to use http:// before google.com as that's needed in order to make the ping.
It's probably faster and more efficient and just do it within PHP, instead of exec'ing a shell
$host = '1.2.3.4';
$port = 80;
$waitTimeoutInSeconds = 1;
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){
// It worked
} else {
// It didn't work
}
fclose($fp);
Also some servers will have EXEC disabled for security reasons, so your method won't work on every server setup.
How can you mimic a command line run of a script with arguements inside a PHP script? Or is that not possible?
In other words, let's say you have the following script:
#!/usr/bin/php
<?php
require "../src/php/whatsprot.class.php";
function fgets_u($pStdn) {
$pArr = array($pStdn);
if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
return FALSE;
} elseif ($num_changed_streams > 0) {
return trim(fgets($pStdn, 1024));
}
}
$nickname = "WhatsAPI Test";
$sender = ""; // Mobile number with country code (but without + or 00)
$imei = ""; // MAC Address for iOS IMEI for other platform (Android/etc)
$countrycode = substr($sender, 0, 2);
$phonenumber=substr($sender, 2);
if ($argc < 2) {
echo "USAGE: ".$_SERVER['argv'][0]." [-l] [-s <phone> <message>] [-i <phone>]\n";
echo "\tphone: full number including country code, without '+' or '00'\n";
echo "\t-s: send message\n";
echo "\t-l: listen for new messages\n";
echo "\t-i: interactive conversation with <phone>\n";
exit(1);
}
$dst=$_SERVER['argv'][2];
$msg = "";
for ($i=3; $i<$argc; $i++) {
$msg .= $_SERVER['argv'][$i]." ";
}
echo "[] Logging in as '$nickname' ($sender)\n";
$wa = new WhatsProt($sender, $imei, $nickname, true);
$url = "https://r.whatsapp.net/v1/exist.php?cc=".$countrycode."&in=".$phonenumber."&udid=".$wa->encryptPassword();
$content = file_get_contents($url);
if(stristr($content,'status="ok"') === false){
echo "Wrong Password\n";
exit(0);
}
$wa->Connect();
$wa->Login();
if ($_SERVER['argv'][1] == "-i") {
echo "\n[] Interactive conversation with $dst:\n";
stream_set_timeout(STDIN,1);
while(TRUE) {
$wa->PollMessages();
$buff = $wa->GetMessages();
if(!empty($buff)){
print_r($buff);
}
$line = fgets_u(STDIN);
if ($line != "") {
if (strrchr($line, " ")) {
// needs PHP >= 5.3.0
$command = trim(strstr($line, ' ', TRUE));
} else {
$command = $line;
}
switch ($command) {
case "/query":
$dst = trim(strstr($line, ' ', FALSE));
echo "[] Interactive conversation with $dst:\n";
break;
case "/accountinfo":
echo "[] Account Info: ";
$wa->accountInfo();
break;
case "/lastseen":
echo "[] Request last seen $dst: ";
$wa->RequestLastSeen("$dst");
break;
default:
echo "[] Send message to $dst: $line\n";
$wa->Message(time()."-1", $dst , $line);
break;
}
}
}
exit(0);
}
if ($_SERVER['argv'][1] == "-l") {
echo "\n[] Listen mode:\n";
while (TRUE) {
$wa->PollMessages();
$data = $wa->GetMessages();
if(!empty($data)) print_r($data);
sleep(1);
}
exit(0);
}
echo "\n[] Request last seen $dst: ";
$wa->RequestLastSeen($dst);
echo "\n[] Send message to $dst: $msg\n";
$wa->Message(time()."-1", $dst , $msg);
echo "\n";
?>
To run this script, you are meant to go to the Command Line, down to the directory the file is in, and then type in something like php -s "whatsapp.php" "Number" "Message".
But what if I wanted to bypass the Command Line altogether and do that directly inside the script so that I can run it at any time from my Web Server, how would I do that?
First off, you should be using getopt.
In PHP it supports both short and long formats.
Usage demos are documented at the page I've linked to. In your case, I suspect you'll have difficulty detecting whether a <message> was included as your -s tag's second parameter. It will probably be easier to make the message a parameter for its own option.
$options = getopt("ls:m:i:");
if (isset($options["s"] && !isset($options["m"])) {
die("-s needs -m");
}
As for running things from a web server ... well, you pass variables to a command line PHP script using getopt() and $argv, but you pass variables from a web server using $_GET and $_POST. If you can figure out a sensible way to map $_GET variables your command line options, you should be good to go.
Note that a variety of other considerations exist when taking a command line script and running it through a web server. Permission and security go hand in hand, usually as inverse functions of each other. That is, if you open up permissions so that it's allowed to do what it needs, you may expose or even create vulnerabilities on your server. I don't recommend you do this unless you'll more experienced, or you don't mind if things break or get attacked by script kiddies out to 0wn your server.
You're looking for backticks, see
http://php.net/manual/en/language.operators.execution.php
Or you can use shell_exec()
http://www.php.net/manual/en/function.shell-exec.php