I've recently been tackling a project that involves executing a JavaScript redirect to a specific page. This is achieved by establishing a session variable in PHP through an AJAX request, and then confirming that the session has been properly set. Once the session check is successful, the redirect URL is generated in JavaScript and the redirection process is executed.
Here's what I've managed to put together so far:
<?php
$v_ip = $_SERVER['REMOTE_ADDR'];
$hash = md5($v_ip);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.ajax({
type : 'POST',
url : './session.php',
dataType: "json",
data: "<?php echo $hash; ?>",
success : function(data){},
error : function(){}
});
</script>
<script>
<?php
if(isset($_SESSION['allow'])) {
echo "var url = \"url-here/?token=\";
var token = \"token\";
var redirect = url.concat(token);";
}
?>
window.location.replace(redirect);
</script>
</head>
</html>
Below is the PHP code responsible for setting the variable:
<?php
session_start();
$v_ip = $_SERVER['REMOTE_ADDR'];
$hash = md5($v_ip);
if(isset($_POST["$hash"])) {
$_SESSION['allow'] = true;
}
?>
Upon the initial visit to the page, all processing is correctly executed up to the point of the redirect. The session variable is successfully set, the JS code is appropriately outputted in the page's code, however, the window.location.replace function fails to activate for some unknown reason. The page simply remains blank - although upon inspection of the source code, everything appears to be in order, the redirect does not transpire. Strangely, if I revisit the page, the redirect functions as expected.
Furthermore, if I alter the name of the session variable in both files, requiring it to be reset, the same issue arises - the redirect is not processed upon first visit, even though everything leading up to it is handled accurately.
What could be causing this irregular behavior?