Search code examples
javascriptphprequire

Can't use php variables defined in another file


I have three php files, one defines a constant, the other has the html markup and includes a php file wigh renders js content. the third is the php file rendering the js content. the code is as shown below.

the first file named "config.php" :

<?php

define('TESTVAR','test variable');
?>

the second file named "main.php" :

<?php
require_once ('config.php');
?>

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>

<script type="text/javascript" src="script.php"></script>
</body>
</html>

the third file named "script.php" :

alert(<?php echo TESTVAR ?>);

this is what gets loaded as script.php:

<b>Notice</b>:  Use of undefined constant TESTVAR - assumed 'TESTVAR' in <b>C:\xampp\htdocs\trials\testphpinjs\script.php</b> on line <b>2</b><br />
TESTVAR);

it's not that php is not being rendered, if i change the script.php to

alert(<?php echo '\'testing'. 'php' . 'echo\'' ?>);

it works perfectly and the loaded script can be viewed from developer tools as

alert('testingphpecho');

the only problem I have is that I cannot access the variables in pages required or included before


Solution

  • Using <script type="text/javascript" src="script.php"></script>, the browser will issue a new request to load script.php directly. Since PHP is stateless, that request will not be handled in the same context as whatever processing goes on in main.php.

    If you want to use the variables/constants defined in config.php within script.php, you will have to load it in there:

    <?php require_once('config.php'); ?>
    alert("<?php echo TESTVAR; ?>");
    

    Note that I've added quotation marks, since TEST_VAR is a string value in your example.

    If your Javascript code relies on more than just config.php and its behavior depends on pre-processing that's done in main.php, it might be better to load it as an inline script instead:

    <?php
    require_once ('config.php');
    ?>
    
    <!doctype html>
    <html lang="en">
    <head>
        <title>Document</title>
    </head>
    <body>
    
    <script type="text/javascript">
    <?php include('script.php'); ?>
    </script>
    </body>
    </html>
    

    This way, PHP is loading the script.php file within the same context as main.php, and all constants and variables defined there will (should) be available for use by the code that's outputting your Javascript.