Php code in linux

Php how to write php code in linux

Different CLI options are used in PHP, and the way of executing PHP script from the command line is described in this tutorial. You can get the list of all CLI options by running the PHP command with the -h option if you want to know more about the PHP CLI.

How to use PHP through command-line

PHP is mainly used to develop web applications, but it can also be used for other purposes. One of the useful features of PHP is the support of SAPI (Server Application Programming Interface) type named CLI (Command Line Interface). The CLI SAPI is released in PHP 4.2.0 version for the first time . The –enable-cli option is used to enable this feature, and this option is enabled in the new version of PHP by default . Furthermore, the –disable-cli option is used to disable this feature.

Different CLI options are used in PHP, and the way of executing PHP script from the command line is described in this tutorial.

CLI options:

Some mostly used CLI options. They are explained below:

Option Description
-r It is used to execute PHP script without using PHP delimiter ().
-f It is used to execute the PHP file.
-i It is used to display the output of phpinfo().
-l It is used to check the syntax of the given PHP file.
-w It is used strip comments and whitespaces from the given file.
-a It is used to run in an interactive shell environment.
-h It is used to display all available options with an explanation of CLI.
-v It is used to display the PHP CLI version information.

Uses of CLI options:

You have to install PHP on your operating system to check the CLI options of PHP. No web server is required to run the PHP script from the terminal. So, you can run the PHP command from any location, and the PHP file can be stored in any location.

The uses of different CLI options are shown in this part of this tutorial.

Example-1: Check the version of CLI using –v

Run PHP command with -v option from the terminal.

The following output shows CLI version 7.4.3 installed on the system.

Example-2: Display the output of phpinfo() using -i

Run PHP command with -i option from the terminal.

The following output shows the detailed information returned by the phpinfo() function.

Example-3: Execute a simple PHP script without PHP delimiter using -r

Run PHP command with -r option and a script from the terminal.

The following output will appear after running the script. The string value is printed with a newline here.

Example-4: Execute PHP script from a file using -f

Create a PHP file named cli1.php with the following script. Here, STDIN is defined at the beginning of the script to take the input from the user. Next, two string values will be taken from the user where the input value can be a maximum of 5 characters. Then, the values will be converted into integer values, and their sum will be stored in a variable that will be printed later.

Читайте также:  Telegram clients for linux

#!/usr/bin/php -q

// Define STDIN to read data from PHP
if ( ! defined ( «STDIN» ) ) <
define ( «STDIN» , fopen ( ‘php://stdin’ , ‘r’ ) ) ;
>

//Take two numeric values as input
echo «Enter the value of a: » ;
$number1 = fread ( STDIN , 5 ) ;
echo «Enter the value of b: » ;
$number2 = fread ( STDIN , 5 ) ;

//Convert the string data to number and calculate sum
$sum = ( int ) $number1 + ( int ) $number2 ;

//Print the result of the summation
printf ( «The sum of %d and %d is %d \n » , $number1 , $number2 , $sum ) ;
?>

Run the PHP file from the terminal using the PHP command with -f option. You have to mention the path of the PHP file properly in the command.

In the following output, 30 and 70 are taken as input, and 100 is printed as output.

Example-5: Check the syntax of PHP file using -l

Create a PHP file named cli2.php with the following script. Here, STDIN is defined at the beginning of the script to take the input from the user. Next, a string value will be taken from the user and that is printed after formating.

#!/usr/bin/php -q

// Define STDIN to read data from PHP
if ( ! defined ( «STDIN» ) ) <
define ( «STDIN» , fopen ( ‘php://stdin’ , ‘r’ ) ) ;
>

echo «What is your favorite color? \n » ;
//Take input from the user
$color = fread ( STDIN , 10 ) ;
//Print the input value
printf ( «Your selected color is: %s \n » , $color ) ;
?>

Run the above script with the -l option to check the syntax error. If the script contains any syntax error, then the output will display the error with a line number. Otherwise, it will print the value ‘ No syntax error detected’ . It is better to check the script, whether contains any syntax error or not, before executing the script.

The following output shows that the script has no syntax error. For example, if any semicolon(;) is omitted after any line, then it will display the error with line number.

Example-6: Display PHP script from a file by omitting comments and whitespaces using -w

You can check the use of the -w option by creating any PHP script file with comments and whitespaces. Create a PHP file named cli3.php with the following code that contains two comments and many whitespaces. The output will show the full script by removing comments and whitespaces.

//Assign a numeric value
$num = 78 ;

//Check the number is less than 100 or not
if ( $num < 100 )
<
echo «The value $num is less than 100 \n » ;
>
else
<
echo «The value $num is more than or equal to 100 \n » ;
>

Run the above script with -w option using PHP command.

The following output will appear after running the script.

Conclusion

You can test the PHP script without using any web server by using the CLI feature. Many other options exist for PHP CLI for different purposes. You can get the list of all CLI options by running the PHP command with the -h option if you want to know more about the PHP CLI. The most commonly used CLI options are explained in this tutorial, with examples, to let the readers know more about this PHP feature.

Читайте также:  Установка qt5 astra linux

PHP script newline on linux, I usually use PHP to create dynamic web pages, now I need to write a script on linux that is similar to an old one I wrote for my website

How to Execute PHP Codes in Linux through Command Line

This video explains how to Execute PHP Codes through Command Line. PHP is designed for Duration: 6:04

How to run php code on ubuntu, how to run php on linux

how to run php code on ubuntu, how to run php on linux, setup web development environment
Duration: 3:00

How To Run PHP Without Setting Up Server In Ubuntu Linux

How can I execute PHP code from the command line?

If you’re going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It’s a lot more fun.

Anyway, the php command offers two switches to execute code from the command line :

-r Run PHP without using script tags -R Run PHP for every input line 

You can use php 's -r switch as such:

php -r 'echo function_exists("foo") ? "yes" : "no";' 

The above PHP command above should output no and returns 0 as you can see:

>>> php -r 'echo function_exists("foo") ? "yes" : "no";' no >>> echo $? # print the return value of the previous command 0 

Another funny switch is php -a :

-a Run as interactive shell 

It's sort of lame compared to phpsh , but if you don't want to install the awesome interactive shell for php made by Facebook to get tab completion, history, and so on, then use -a as such :

>>> php -a Interactive shell php > echo function_exists("foo") ? "yes" : "no"; no php > 

If it doesn't work on your box like on my box es ( tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken . If you run this command:

You should see:

Server API => Command Line Interface 

If you don't , this means that maybe another command will provides the CLI SAPI . Try php-cli; maybe it's a package or a command available in your OS.

If you do see that your php command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.

Another couple of examples, just to make sure it works on my boxes:

>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";' no >>> php -r 'echo function_exists("print_r") ? "yes" : "no";' yes 

Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files , e.g., /etc/php/cli/php.ini vs. /etc/php/cgi/php.ini vs. /etc/php/apache/php.ini on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini .

Using PHP from the command line

Use " instead of ' on Windows when using the CLI version with -r :

Correct
Incorrect
 PHP Parse error: syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1 

Don't forget the semicolon to close the line (otherwise, the result is "PHP Parse error: syntax error, unexpected end of file, expecting ';' or ',' in Command line code on line 1" ).

The short tag " < ?= " can be helpful too:

The closing tag "?>" is optional, but don't forget the final ";"!

Quickstart: Create a PHP web app, Get the sample repository · To run the application locally, use the php command to launch the built-in PHP web server. Bash Copy. php -S

Can't write file with PHP on Linux Server

In the Linux server, it may be a file permission issue try this command below in your directory. I am assuming your directory is /var/www/html if not replace this with your directory path and run commands.

chown -R www-data:www-data /var/www/html

How to use PHP through command-line, Run PHP command with -r option and a script from the terminal. $ php -r 'echo "Welcome to Linux Hint\n";'. The following output will appear

Run php program from /var/www folder

Edit httpd.conf file and add DocumentRoot "/var/www" for modifying root directory, put your file there and restart server

You can keep your php files in apache2 DocumentRoot i.e /var/www/html by default and start apache2 service provided it has php supported modules. You would be able to open the page on browser by localhost and also by ipaddress of the linux ubuntu box.

https://help.ubuntu.com/community/ApacheMySQLPHP -> This link would be helpful.

Thanks & Regards,
Alok Thaker

Make sure that you have Apache configured to serve PHP pages and that Apache config is setup correctly.

What happens when you hit localhost/file.php ? Does anything happen, or does it download the file?

What is PHP? The PHP Programming Language Meaning Explained, PHP is mostly used for making web servers. It runs on the browser and is also capable of running in the command line. So, if you don't feel like

Источник

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?

If you are here (from a search engine hit) looking for a way to run PHP source directly from the command line (like a Perl one-liner), then go to Stack Overflow question How can I execute PHP code from the command line?. (It is the -r option)

4 Answers 4

If it is acting like cat, then you probably forgot to switch out of template mode and into script mode with

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.

If you wish to pass an argument(s), you can simply do so like this:

In your PHP file you can use this argument by accessing the $argv array like this:

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"

Actually, PHP's main purpose is to generate web pages, but there are at least two other options:

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).

Источник

Оцените статью
Adblock
detector