PHP in command line - php

Using Python I can test my code in the terminal / command line by typing
python
python> print "hello world"
I would like to do this with PHP too, but when typing:
php
echo "hello world";
it does not work.. Is this possible? what should I do?
A quick search on the internet gives a lot of results that call an actual .php file to run. I only want to test a single sentence if possible, without creating files and stuff.

Try
php -a
which starts an interactive PHP shell. Be aware that this requires PHP to be built with --with-readline (which is not the case if you're using the bundeled PHP with Mac OS X e.g.).
Alternatively, if you don't require the interactivity of a separate shell, use
php -r 'print_r(get_defined_constants());'
to execute a PHP snippet (this doesn't require the readline support).

php -r "echo 'hello world';"

If you run php without the -a option, don't forget the <?php at the start

Related

PHP command in Bash does not execute code

Ok, so I have a problem with this thing I found on a MacBook Air. It's called terminal and you can do crazy stuff on it. So anyways, when I enter the command "php" it gives me a multiline console but it doesn' do anything when I run a line of php! For instance, I type echo "Hello World" but it just returns it like a typewriter and nothing happens! Can someone please tell me what is going on, and is there a way to exit this?
Firstly check if you have php properly installed:
type in console:
php -v
you should see version of installed php for ex.:
PHP 7.3.3 ...
to run single line of code from console you do it this way:
php -r 'echo "\nHello World\n";'
where \n is new line character.
to enter interactive mode and run multiple lines of code:
php -a
and once you see:
Interactive mode enabled
php >
type:
echo "\nHello World\n";
and hit [Enter] key.
that's it.
to leave interactive mode type:
exit
note lack of ; at the end.
If you want to run from console a php code that you have in a file:
php -f <path-to-the-file>
but this is a default behavior of php so if you miss flag -f and just type:
php
it will do nothing, expecting you providing it a path to file after the php like in the example with flag -f:
php <path-to-file>
So if a programmer intention is to enter an interactive mode but he types only php without any flags, the php will not warn about missing path to the file so programmer may have the impression he's into php interactive mode as he wanted but this is not true.
to see all possible options in php cli, type:
php --help
I believe if you just type php into the terminal it will start a php server process on the local mac. If you want to run a script you have to cd in to to the working directory and type php filename.php.
If you want to use PHP code directly you must enter php -a without a flag you will just enter in php environment.
When running the php command directly from your command line, it behaves as it is reading a .php from the command line
You noticed that it just echo's back any thing you write toward it, this is the same as it is executing a .php file, its echoíng any html back to the browser
Example:
$ php
sss
<?PHP
echo 'Hello!';
?>
More data!
ctrl + d (to signal that the end of the filehas reached)
Output:
sss
Hello!More data!

Executing SASS script from PHP and getting output

I have this PHP script (test.php):
<?php
$cmd = "/usr/bin/sass --watch file1.scss";
system($cmd);
?>
Now I call my PHP script from CLI this way:
/usr/bin/php test.php
And I get no output (it should print SASS is watching for changes).
If I call the SASS command directly from the shell, it outputs correctly.
Why?
Info: I'm using the PHP 5.3.6 version on OS X Lion
Edit: Please, note that this command watches for changes, it seems to behave differently to a regular command.
Edit2: The command works, it compiles correctly. The only thing lacking is the output (I want to debug and see errors :)
Some command line utilities like sass, manipulate the output pipe in some way that PHP can't use.
So, in this particular case, there is no solution.
system() returns a string. Just echo it.
According to http://se.php.net/system you need to pass in a second argument to system() and the return value of the command will be set in that variable:
<?php
system($command, $return);
echo $return;

Running PHP code/scripts on the command line

I just began learning PHP. I've installed php5 on Linux and wrote very simple code just to get going.
How can I run scripts? I tried using the -f option, but it works as a cat command and just spits out the code to standard output.
The interactive interpreter option works fine. Is a web browser the only way to execute a PHP script?
A simple:
php myScript.php
… should do the job.
If it is acting like cat, then you probably forgot to switch out of template mode and into script mode with <?php
Shorter way for command line:
php -r 'echo "Hello "; echo "Jay";'
OR
php -r 'echo dirname("parent/child/reply") . "\n";'
As already mentioned, you can execute your PHP with the following.
php myScript.php
If you wish to pass an argument(s), you can simply do so like this:
php myScript.php Apples
In your PHP file you can use this argument by accessing the $argv array like this:
<?php
echo 'I like ' . $argv[1];
?>
The above would print our "I like Apples".
Note the array index is 1 and not 0. 0 is used for script name. In this case $argv would be "myScript.php"
For more information, check out my blog post Running PHP from the Command Line - Basics.
Actually, PHP's main purpose is to generate web pages, but there are at least two other options:
command line (CLI) script execution,
interactive shell - which is actually the variant of the previous option,
The first one can be achieved in many ways (eg. by giving proper permissions to the file and calling script by providing its URI, eg. ./index.php), the second one can be invoked by php -a command (as stated in the documentation mentioned above).

Tab autocompletion in bash using php

I'm writing a simple script to autocomplete when I press TAB.
The php script contains a simple "echo".
In this case, the autocomplete works but a "tab" is appended to the output
making it useless
Code from the script
scriptPath='/home/hassen/workspace/scripts/bin/test.php'
_dda()
{
local cur
COMPREPLY=()
unset COMP_WORDS[0] #remove "j" from the array
cur=${COMP_WORDS[*]}
IFS=$'\n\n' read -d '' -a COMPREPLY < <($scriptPath --completion "$cur")
return 0
}
complete -F _dda dda
alias dda=$scriptPath
Code from php script
<?php
echo "hello";
?>
Here is the annoying part:
If I print the echo in Python or Ruby, it works like a charm -- ie each time I press TAB, it calls the scripts and output hello.
Is this a bug with PHP or my code?
They seem to disagree at http://bugs.php.net/bug.php?id=52755
It works as desired here, are you very sure the PHP file itself doesn't hold a tab, possibly after the ?>?
Versions: PHP 5.3.2, GNU bash version 4.1.5
CLIFramework provides a command helps you generate the bash completion script by your command definitions, so you don't have to write the completion script by hands:
https://github.com/c9s/CLIFramework
The screencast:
p.s. it also works for zsh
There is a known problem in PHP that is documented here that prevents this from working.
https://bugs.php.net/bug.php?id=53040
Use /usr/bin/php-cgi instead of /usr/bin/php for running the script and it should work.
I had the same issue, not directly with a custom bash completion, but through Makefile bash completion.
Workaround at Makefile bash autocompletion issue with PHP generated targets

Bizarre php shell script behavior

It may help if you are on a Mac and use TextMate, though not entirely necessary.
My php location:
$which php
/opt/local/bin/php
The script:
#!/opt/local/bin/php
<?php
shell_exec("echo -n 'my-string' > out.txt");
?>
The -n to echo suppress the newline that is automatically added to all shell echo commands.
If I run the above php code from the shell:
chmod u+x myfile.php
./myfile.php
I end up with 'out.txt', the contents of which being:
-n my-string
If I run the exact same code within TextMate, the contents of 'out.txt' will be correct:
my-string
I can't figures out what php is up to with putting the literal string '-n' in the output. I really wonder why TextMate does the correct thing. I have checked that both are using the same php, php -i shows mostly the same stuff, of course there are differences as one is run within TextMate, the other in the shell, so one output has pointers to the file whereas the other doesn't. As far as I can tell, $PATH and $ENV are the same.
I have tried a handful of different methods to work around this none of which are working. I actually will not be able to use a workaround, as this has been distilled down to a simple case for posting to SO. My use case for this pipes to pbcopy, which I believed was a Mac OS X only feature, so I used >> redirection here because that is universal.
Ultimately, I want a result on my clipboard that does not have a trailing newline, which is dangerous as pasting that in a shell will execute whatever preceded it.
Thanks
Is it possible that php is calling a different echo than your shell built in echo? Many versions of echo do not support -n and will output it as part of your string.
You could try shell_exec("which echo"); to find out which it is running.
Note that printf will not display the new line unless you explicitly add it. So you can use which printf to figure out where this resides and call it instead.
shell_exec("/usr/local/bin/printf '%s' 'mystring' > out.txt");
PHP just defers the call to popen in Unix platforms. See the manual page for Mac OS X:
The command argument is a pointer to a null-terminated string containing a shell command line. This
command is passed to /bin/sh, using the -c flag; interpretation, if any, is performed by the shell.
So it should be the same as running /bin/sh -c "echo -n 'my-string' > out.txt"

Categories