How to execute PHP code from the command line?

0 votes
I would like to execute a single php statement like if(function_exists("my_func")) echo 'function exists'; directly with the command line without having to use a seperate php file.

How is it possible ?
Oct 1 in PHP by kartik
• 35,620 points
51 views

1 answer to this question.

0 votes

Hello @kartik,

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

-r <code>        Run PHP <code> without using script tags <?..?>
-R <code>        Run PHP <code> 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

HOpe it helps!!

Thank you!!

answered Oct 1 by Niroj
• 77,360 points

Related Questions In PHP

0 votes
1 answer

How to retrieve or obtain data from the MySQL database using PHP?

Hello kartik,  Actually there are many functions that  ...READ MORE

answered Mar 27 in PHP by Niroj
• 77,360 points
158 views
0 votes
0 answers
0 votes
1 answer

How to get a list of user accounts using the command line in MySQL?

Hello @kartik, Use this query: SELECT User FROM mysql.user; Which ...READ MORE

answered Aug 17 in PHP by Niroj
• 77,360 points
56 views
0 votes
1 answer

How to execute a MySQL command from a shell script?

Hello @kartik, You need to use the -p flag to ...READ MORE

answered Aug 20 in PHP by Niroj
• 77,360 points
106 views
0 votes
1 answer

jQuery AJAX fires error callback on window unload - how do I filter out unload and only catch real errors?

Hello, In the error callback or $.ajax you have three ...READ MORE

answered Apr 27 in Java-Script by Niroj
• 77,360 points
445 views
0 votes
1 answer

How do I pass command line arguments to a Node.js program?

Hello @kartik, If your script is called myScript.js ...READ MORE

answered May 5 in Java-Script by Niroj
• 77,360 points
690 views
0 votes
1 answer

Error:Issue when trying to use IN() in wordpress database

Hello @kartik, Try this code : // Create an ...READ MORE

answered May 8 in PHP by Niroj
• 77,360 points
91 views
+2 votes
1 answer

How do I debug Node.js applications?

Hello @kartik, Use node-inspector  from any browser supporting WebSocket. Breakpoints, ...READ MORE

answered Jul 8 in Node-js by Niroj
• 77,360 points
87 views
0 votes
1 answer

How to find the php.ini file from the command line?

Hello @kartik, You can get a full phpinfo() using : php ...READ MORE

answered May 19 in PHP by Niroj
• 77,360 points
1,413 views
0 votes
1 answer

How To Run PHP From Windows Command Line in WAMPServer

Hello @kartik, Try using batch file Open notepad type php -S ...READ MORE

answered Oct 27 in PHP by Niroj
• 77,360 points
27 views