0

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.

`

Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37
  • 2
    JS is literally a differerent programming language, and will run _in your user's browser, on their computer_, not on your server. By the time JS can even run, PHP has already done its job, and died server-side, with the the page code not anywhere _near_ your server anymore. What would you even expect this to do? As for "no apparent errors": no of course not, you generated the HTML source code for a script element. That's literally what PHP was born to do: generate HTML code =) – Mike 'Pomax' Kamermans Jul 08 '23 at 04:44
  • We can't see what is in charge.js, so we don't know what it's likely to do. Provide a [mre] of the issue if you need more help. Thanks – ADyson Jul 08 '23 at 08:33
  • See this question is closed: will read the referenced FAQ, thanks. I realized I can leave the JS file in `public/js/charge.js` as no sensitive information there; keep an associated PHP file (not mentioned) in `src/` and echo a needed JS variable (return of client secret key from server to client) as an echoed "global" $VAR (https://stackoverflow.com/q/23740548/1904943), picked up by `public/charge.js` – Victoria Stuart Jul 08 '23 at 15:10

2 Answers2

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.

A. Onder
  • 134
  • 6
0

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
?>
kevP-Sirius
  • 93
  • 1
  • 9