skip to Main Content

I have a PHP script register.php.

Within that file I want to call and run an external JavaScript file, charge.js.

The directory structure is

public/
  index.php
  register.php
  js/
   charge.js     // I want to move from this ...
src/
  register.php
  js/
    charge.js    // ...to this for security reasons

On my Apache webserver public/ is the ROOT directory.

At the end of public/register.php I have the line

<script src="/js/charge.js"></script>

which runs public/js/charge.js and creates the charge element on the registration form, coded in public/register.php.

src/register.php contains other code which completes the registration process.

public/register.php includes the line

`require DIR . ‘/../src/register.php’;)

When I move the line <script src="/js/charge.js"></script> to the end of src/register.php (intending to call src/js/charge.js) nothing happens.

<?php
...
require('js/charge.js');
...
?>

and

<?php
...
?>
<script src="js/charge.js"></script>
<?php
...
?>

with no apparent errors, but (e.g.) console.log() statements in charge.js are not printing to console.

`

2

Answers


  1. I don’t think you can. JS is run on the client browser not on the server like PHP. To run JS on the server you have to install a JS interpreter and run the code using that via the php command exec which is used to execute scripts outside of the PHP environment.

    Login or Signup to reply.
  2. I’m not sure that’s what you want to accomplish there but you can execute a js file with node on server side like this =>

    <?php
    // register.php
    $command = "node charge.js";
    $output = exec($command);
    echo $output; // Output from the JavaScript execution
    ?>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search