I am working on a plain PHP project where I have some files structures as below.
project_folder
--> .env
--> autoload.php
--> index.php
--> Controllers
--> IndexController.php
Now my files contain the below codes.
.env
# App Constants
APP_ENV = localhost
APP_URL = http://localhost/project_folder
APP_DOMAIN = https://localhost/project_folder
APP_DIR = __DIR__
# Database Connection
DATABASE_HOST = localhost
DATABASE_NAME = test
DATABASE_USER = root
DATABASE_PASSWORD = root
autoload.php
$ENV_filepath = '.env';
$lines = file($ENV_filepath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) {
continue;
}
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
putenv(sprintf('%s=%s', $name, $value));
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
index.php
<?php
session_start();
require_once 'autoload.php';
?>
<form onsubmit="return submitted(this)">
<input type="text" name="UserName" required="" maxlength="200">
<input type="password" name="UserPassword" required="" maxlength="200">
<div id="showGeneralAjaxMsg"></div>
<input type="submit" title="Sign In Now" value="Sign In"/>
</form>
<script type="text/javascript">
function submitted(incomingForm) {
var FD = new FormData(incomingForm);
FD.append("Function", "Login");
var ajx = new XMLHttpRequest();
ajx.onreadystatechange = function () {
if (ajx.readyState == 4 && ajx.status == 200) {
document.getElementById("showGeneralAjaxMsg").innerHTML = ajx.responseText;
}
};
ajx.open("POST", "Controllers/IndexController.php", true);
ajx.send(FD);
document.getElementById("showGeneralAjaxMsg").innerHTML = "LOADING: Server Is Responding.";
return false;
}
</script>
IndexController.php
<?php
echo "This Text Is Showing After Submit At index.php Page Only";
print_r($_ENV);
echo getenv('APP_ENV');
?>
But I am returning empty environment variables. Nothing is showing in the response result and I am only able to see "This Text Is Showing After Submit At index.php Page Only".
Now my question is that what is the scope of environment variables in PHP? Remember I am not using the OOP concept. It's simple programming. Also, I am confused that should I have to load the autoload.php file on each PHP page? If your answer is yes then I have some relative variables set in .env in future that can only be saved from the project root folder and not from any other level.
Waiting for a clarification...
CodePudding user response:
You may use session variables to store data in variables which can be accessed in different pages of the system
- Say if the variable name is var1, then simply use $_SESSION['var1']
- Make sure session_start(); is placed at the top of all the PHP scripts using the session variables
<?php
session_start();
$_SESSION['var1'] = $var1;
// other statements
?>