You have to use exec or passthru and execute the js with Node in PHP to start the JS interpretter...

I just ran this test from the Mac command line

# Made a directory to test in
$ mkdir jsphptest && cd jsphptest

# made a test php file
$ touch test.php

# put some PHP code in the PHP file that tells it to run a javascript file
$ echo '<?php passthru("node test.js"); ?>' > test.php

# create the above references js file
$ touch test.js

# Put some JS code in the new JS file that logs some stuff into the console
$ echo 'console.log("this is javascript");' > test.js

# run the php file
$ php test.php

#outputs: this is javascript
Answer from I wrestled a bear once. on Stack Overflow
Top answer
1 of 3
192

You should check your server configuration files. Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that. Start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(So you can paste/write code in the console.)

php -a

To make it parse a file and output to the console:

php -f file.php

Parse a file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only a small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running Linux then do man php at the console.

If you need/want to run PHP through fpm (FastCGI Process Manager), use cli fcgi:

SCRIPT_NAME="file.php" SCRIPT_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

Where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

2 of 3
3

On SUSE Linux, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (PHP configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.

If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the German module, while the the CLI php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.

You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.

Or, you could find the line that loads the German module in the Apache file and copy/paste just it to the CLI file.

Discussions

How to run my php file from mac terminal - Stack Overflow
Sorry if this is a very novice question - I am a novice - but, I have no clue how to run my php file from the terminal. I type in the mac terminal something like this: php test.php (where test.php... More on stackoverflow.com
🌐 stackoverflow.com
How to execute php block from terminal without saving to a file - Stack Overflow
Say I have a block of code I would like to test like this: How I quickly run this code from terminal without saving it to a file? I tried things like... ... More on stackoverflow.com
🌐 stackoverflow.com
Opening /running PHP files in Mac
php -S localhost:8000 will start a test server using the index.php in your current working directory. https://www.php.net/manual/en/features.commandline.webserver.php More on reddit.com
🌐 r/webdev
6
0
August 9, 2022
How to execute PHP code within JavaScript - Stack Overflow
JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server). If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for. ... If you just want to echo a message from PHP ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-execute-php-code-using-command-line
How to Execute PHP Code using Command Line? - GeeksforGeeks
... To run PHP code interactively, use the -a option. ... If you need to run a PHP script in the background (e.g., for long-running processes), append & to the command: ... This will run the script in the background and free up the terminal.
Published   July 12, 2025
🌐
Quora
quora.com › How-can-we-execute-PHP-script-using-command-line
How can we execute PHP script using command line? - Quora
Save your file with .php extension. Make sure you've php installed and environment variables are set. Assuming you're ready to go simply rum following command. ... It will execute your script. If you want to run script on browser then you need web server installed on your machine.
🌐
TecMint
tecmint.com › home › php › how to use and execute php codes in linux command line – part 1
How to Use and Execute PHP Codes in Linux Command Line - Part 1
July 13, 2015 - 4. You can run a PHP script simply as, if it is a shell script. First Create a PHP sample script in your current working directory. # echo -e '#!/usr/bin/php\n<?php phpinfo(); ?>' > phpscript.php · Notice we used #!/usr/bin/php in the first line of this PHP script as we use to do in shell script (/bin/bash). The first line #!/usr/bin/php tells the Linux Command-Line to parse this script file to PHP Interpreter.
🌐
Educative
educative.io › answers › how-to-execute-php-scripts-on-the-command-line
How to execute PHP scripts on the command line
Lastly, enter the following command into your cmd or terminal to run the script file named prog1.php:
Find elsewhere
Top answer
1 of 2
83

To run PHP commands immediately on Terminal you can pass -a option to your installed PHP:

php -a

Details:

php -a opens an interactive shell which let you type directly PHP commands and view the result on your terminal, As an example, after typing php -a in terminal you can type echo 'Hello World'; and after Press Enter Hello World! will be printed on the screen.

Windows Solution

On windows there is no interactive mode same as Linux but still you can use interactive like mode!, So, open PHP on place you installed it for example if you use XAMPP then your PHP should be is on C:\xampp\php (or add the binary directory to environment variables) and then type php -a, At the end of each line you can view the results by pressing Ctrl+Z and then Enter.

php -a
echo 'hello world!';
^Z
2 of 2
52

Escape the inside double quotes (") that you are using to delimit your string.

php -r "Print \"Hello, World!\";"

Alternatively, use single quotes (') for the PHP string or for the quoting of the PHP code.

If you run php --help you can see a list of commands that the php program accepts.

  -a               Run as interactive shell
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -S <addr>:<port> Run with built-in web server.
  -t <docroot>     Specify document root <docroot> for built-in web server.
  -s               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --rz <name>      Show information about Zend extension <name>.
  --ri <name>      Show configuration for extension <name>.
🌐
PHP
php.net › manual › en › features.commandline.usage.php
PHP: Usage - Manual
The script above includes the Unix shebang first line to indicate that this file should be run by PHP.
🌐
Ecenica Hosting
ecenica.com › support › answer › how-to-run-a-php-script-in-terminal-in-cpanel
How To Run A PHP Script In Terminal In CPanel - Ecenica
July 13, 2015 - For example, if your script is in the public_html directory, you would type: ... Now that you’re in the correct directory, you can run your PHP script. Use the php command followed by the name of your script.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › using the raspberry pi › beginners
[solved] How to execute PHP scripts on command line? - Raspberry Pi Forums
February 17, 2013 - On my Raspberry Pi with Raspbian OS (Debian optimized for Raspberry Pi) I've installed Nginx + MySQL + PHP. Both Nginx + PHP (using php5-fpm) seem to work well as I can retrieve HTML / PHP files correctly using my browser. At another machine with Debian & Apache, I can run PHP scripts from the command line using the command:
🌐
Reddit
reddit.com › r/webdev › opening /running php files in mac
r/webdev on Reddit: Opening /running PHP files in Mac
August 9, 2022 -

Hi all,

I'm learning PHP and I'm having trouble understanding how to open PHP files on my Mac through my browsers. I have downloaded PHP via home-brew, and I can run php files by using the following command on my terminal: php /File/Path/hello.php.

However, I don't know how to open the file through safari or chrome. I have apache installed and running on my Mac. I'm confused where should I save my php files on my computer and how to open them on my browsers?

Top answer
1 of 11
20

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:

alert("<?php echo "asdasda";?>");

don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('.result').html(data);
  }
});

and test.php would be:

<?php 
  echo 'asdasda';
?>

it would write the contents of test.php to whatever element has the result class.

2 of 11
6

Interaction of Javascript and PHP

We all grew up knowing that Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.

But -- good news; it can be made to work and here's how.

The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.

First, to clarify the DHTML usage I'll cite this DHTML example:

<script type="text/javascript">

function updateContent() {
 var frameObj = document.getElementById("frameContent");
 var y = (frameObj.contentWindow || frameObj.contentDocument);

 if (y.document) y = y.document;
 y.body.style.backgroundColor="red";  // demonstration of failure to alter the display

 // create a default, simplistic alteration usinga fixed string.
 var textMsg = 'Say good night Gracy';

 y.write(textMsg);

 y.body.style.backgroundColor="#00ee00";  // visual confirmation that the updateContent() was effective

}
</script>

Assuming we have an html file with the ID="frameContent" somewhere, then we can alter the display with a simple < body onload="updateContent()" >

Golly gee; we don't need PHP to do that now do we! But that creates a structure for applying PHP provided content.

We change the webpage in question into a PHTML type to allow the server side PHP access to the content:

**foo.html becomes foo.phtml**

and we add to the top of that page. We also cause the php data to be loaded into globals for later access - - like this:

<?php
   global $msg1, $msg2, $textMsgPHP;

function getContent($filename) {
    if ($theData = file_get_contents($filename, FALSE)) {
        return "$theData";
    } else {
        echo "FAILED!";
        }
}
function returnContent($filename) {

  if ( $theData = getContent($filename) ) {
    // this works ONLY if $theData is one linear line (ie remove all \n)
    $textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
    return "$textPHP";
  } else {
    echo '<span class="ERR">Error opening source file :(\n</span>';  # $filename!\n";
  } 
}

// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 =       returnContent('dummy_frame_data.txt');
$msg2 =       returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');

?>

Now our javascripts can get to the PHP globals like this:

// by accessig the globals var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';

In the javascript, replace

var textMsg = 'Say good night Gracy';

with: // using php returnContent()

var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';

Summary:

  • the webpage to be modified MUST be a phtml or some php file
  • the first thing in that file MUST be the < ? php to get the dynamic data ?>
  • the php data MUST contain its own css styling (if content is in a frame)
  • the javascript to use the dynamic data must be in this same file
  • and we drop in/outof PHP as necessary to access the dynamic data
  • Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data

To be resolved: calling updateContent() with a filename and using it via onClick() instead of onLoad()

An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it

🌐
Envato Tuts+
code.tutsplus.com › home › php › php scripts
How to Run a PHP File - Code - Envato Tuts+
February 2, 2024 - Today, we’re going to discuss how you can run PHP files. If you're new to PHP programming, this article will help you learn how to run PHP scripts. PHP is a server-side scripting language which is...
🌐
Team Treehouse
teamtreehouse.com › community › hey-guys-i-am-a-bit-confused-about-php-how-come-i-can-run-php-script-on-the-terminal-when-it-is-a-serverside-script
Hey guys, I am a bit confused about PHP. How come I can run PHP script on the terminal when it is a server-side script? (Example) | Treehouse Community
May 5, 2018 - Once I had an excel spreadsheet that I wanted to convert to JSON, just another form of data but one that I could then reference a lot easier in code. I used PHP to do that and ran the script I had to do this with the PHP command-line interface. The terminal is able to run PHP scripts because the computer's operating system is able to read and interpret PHP code (perhaps with some configuration beforehand).
🌐
Quora
quora.com › How-do-I-can-execute-command-line-in-PHP
How to can execute command line in PHP - Quora
Answer (1 of 7): Hmm ... just be careful, what you will show to beloved public. Also, on many hosting sites running shell commands through web server/php is disabled because of security reasons. If that will be the case, you can generate safe content in the background (cron jobs) and write conte...