I have this code here and I noticed when I changed the value to something else. I have to refresh the page not once but twice in order to see the new value.
Is this related to HTTP headers and super globals? or something why do I have to refresh twice to see the new value why is not one refresh? I've tried reading similar questions on other threads but still not clear on this manner as far why? and what's doing. Can someone give me a clear explanation, thank you.
<?php
$name = "test";
$value = "hello";
$expire = time() + (60*60*24*7);
setcookie($name, $value, $expire);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP</title>
</head>
<body>
<?php
$test = isset($_COOKIE["test"]) ? $_COOKIE["test"] : "";
echo $test;
?>
</body>
so If I change the value to say 500 then I have to refresh twice to see the new value on the page.
The answer is here https://stackoverflow.com/a/17085896/2243372 .
Try to refresh your page programmatically. Example:
<?php
if (isset($_COOKIE['test'])) {
echo 'COOKIE = ', $_COOKIE['test'];
} else {
setcookie('test', 'my-cookie-value', strtotime('+1 day'));
if ( ! isset($_GET['setcookie'])) {
header('Refresh: 0; url=?setcookie=done');
} else {
echo 'Your browser does not accept cookies!';
}
}
Related
I am relatively new to php but I am encountering an error that is about to drive me INSANE.
I am working on creating a webpage that lets you browse files on the server.
However, for some reason, the $_SESSION variable keeps itself set, EVEN AFTER BROWSER RESTARTS...
Please, I am begging you, tell me why this happens before I go insane.
This is my code:
<html>
<?php
session_start();
if(!isset($_GET['location'])) {
header('Location: ?location=G:');
session_unset();
}
/* THIS IS WHERE THE BUG OCCURS. THIS VARIABLE SHOULD BE EMPTY ON BROWSER OPEN!!!! ?!?!?!?! I HAVE ADDED NOTHING TO SESSION YET*/
var_dump($_SESSION);
if(!isset($_SESSION['path'])) {
$_SESSION['path'] = array();
$_SESSION['path'][0] = $_GET['location'];
}
echo '<br><br><br><br><br><br>';
//* If user presses back and isn't in home folder, return to previous folder... *//
if(isset($_GET['back']) && $_GET['back'] == true && sizeof($_SESSION['path']) > 0) {
unset($_SESSION['path'][sizeof($_SESSION['path'])-1]);
$_GET['location'] = $_SESSION['path'][sizeof($_SESSION['path'])-1];
header ('Location: ?back=false');
} else {
//*However if user hasn't pressed back make sure that session is properly updated with location *//
if($_SESSION['path'][sizeof($_SESSION['path'])-1] != $_GET['location']) {
array_push($_SESSION['path'], $_GET['location']);
}
}
//*Now build the link from the session path array*//
$full_link = '';
for($i = 0; $i < sizeof($_SESSION['path']); $i++) {
$full_link .= $_SESSION['path'][$i];
$full_link .= '/';
}
//*Get all files from link path*//
$filesbrowsed = glob($full_link . '*');
?>
<head>
<meta charset "utf8">
<title>File Browser</title>
<link href="filebrowserstyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<header>
<ul class = "navigation">
<li>Home</li>
<li>Back</li>
<li></li>
<li></li>
</ul>
</header>
<div class = 'current_files'>
<?php
//* Now display all files in current path *//
for($i = 0; $i < sizeof($filesbrowsed); $i++) {
$filename = substr($filesbrowsed[$i], strlen($full_link), strlen($filesbrowsed[$i]) - strlen($full_link));
echo '<div>' . $filename . '</div>';
}
?>
</div>
</body>
</html>
Thank you all in advance!!!
You should unset session before redirecting user to another location.
<html>
<?php
session_start();
if(!isset($_GET['location'])) {
session_unset();
session_destroy();
header('Location: ?location=G:');
}
/* THIS IS WHERE THE BUG OCCURS. THIS VARIABLE SHOULD BE EMPTY ON BROWSER OPEN!!!! ?!?!?!?! I HAVE ADDED NOTHING TO SESSION YET*/
var_dump($_SESSION);
To delete all data in the session:
$_SESSION = [];
I am trying to detected if a variable is the same as a string. If so the page will refresh. But if the variables aren't the same, then the page loads. But I need a way to keep checking after the page has been loaded if the refresh variable is the same.
Here is some code I have been testing but been unsuccessful with as the page just keeps refreshing.
$Refresh = file_get_contents('Refresh.txt');
do {
header("Refresh:0");
} while ($Refresh == "True");
// HTML WEBPAGE CODE AFTER THIS POINT
If anyone can fix or redo my code that would be very much appreciated
Try to think of it this way:
<?php
$page = $_SERVER['PHP_SELF'];
$sec = 10;
if ($number == $string){
header("Refresh: $sec; url=$page");
}
else
{goto:end;}
end:
?>
<script>
Jquery Code Goes Here for Page Load
</script>
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
Sorry I read some topics about this already..
But it didn't worked or make it clear to me.
I want to make sure that when my MySQL says that maintenance = 1 he redirect with header to maintenance.
In maintenance the same thing happens but then when maintenance = 0 he redirect with header back to the index.
This works fine..
BUT now I want to have an IP whitelist so that when its in maintenance and I visit the page I still will be able to see the website it self.. But this isn't working correctly..
I hope someone could help me and get an light on what I'm doing wrong.
The code of checkmaintenance.php:
<head><link rel="stylesheet" type="text/css" href="../css/style.css"></head>
<?php include('config-connection.php'); ?>
<?php
$whitelist = mysql_query("SELECT * FROM whitelist_ip");
while ($ip = mysql_fetch_assoc($whitelist)) {
$checkip = $ip['ip'];
}
?>
<?php
if($checkip == $_SERVER['REMOTE_ADDR']) {
echo "<center><div class='error'>The website is in maintenance. But your IP has been whitelisted so you can see the website!</div></center>";
}
?>
<?php
if($maintenance == 1){
flush(); // Flush the buffer
ob_flush();
header('Location: maintenance.php');
}else{
echo "";
}
?>
I Know that I'm a noob with PHP and I try to learn and understand it better than I do now..
To make clear what is in maintenance it self I post the part of that code beneath this:
<?php include('config/config-connection.php'); ?>
<?php
$whitelist = mysql_query("SELECT * FROM whitelist_ip");
while ($ip = mysql_fetch_assoc($whitelist)) {
$checkip = $ip['ip'];
}
?>
<?php
if($checkip == $_SERVER['REMOTE_ADDR']) {
flush(); // Flush the buffer
ob_flush();
header('Location: index.php');
}
?>
<?php
if($maintenance == 0){
flush(); // Flush the buffer
ob_flush();
header('Location: index.php');
}else{
echo "";
}
?>
Index only contains this line:
<?php include('config/checkmaintenance.php'); ?>
I would be very happy if someone could explain to me why it doesn't work.
Or how I should do this better than it currently is.
Kind regards,
Brian
You cant't echo text before the header() function!
Try somehting like
echo '<meta http-equiv="refresh" content="0; URL=YOUR URL">';
This is a little script that supposed to redirect if someone came from a different page, but it's does not work.
It keeps redirecting to the form page.
Here's the code
<?php
define('FORM', 'form.html');
$referer = $_SERVER['HTTP_REFERER'];
// this keeps redirecting even when I came by submiting the form to this page
if ( $referer != FORM ) {
header('Location: ' .FORM);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing 123</title>
</head>
<body>
<?php
$name = $_GET['name'];
$surname = $_GET['surname'];
echo 'hello'. $name. 'nice to see you here mr' .$surname;
?>
</body>
</html>
You could test if the user came from the "form page" by checking if a certain $_POST variable has been sent. For example you could try something like
if(isset($_POST['somehiddenvalue']) && $_POST['somehiddenvalue'] == $hiddenVal) {
// ok.
} else {
// redirect
}
The user will still be able to manipulate the Post variables, keep this in mind.
I suppose what is causing you trouble, is that you don't exit the script after calling header():
header('Location: ' . FORM);
exit;
Anyway you should consider checking for the required parameters, instead of relying on $_SERVER['HTTP_REFERER'], as sending the referrer-info may be disabled in the user's browser.
isset($_GET['name']) : $name = $_GET['name'] ? $name = null;
isset($_GET['surname']) : $surname = $_GET['surname'] ? $surname = null;
if (empty($name) || empty($surname)) {
header('Location: ' . FORM);
exit;
}
Additionally you should escape $_GET['name'] and $_GET['surname'] before outputting it!
I have a simple login page but i am having trouble displaying the logged in page. When the form is submitted, the same login page is displayed. I will have to click refresh or F5 before i can see the logged in page. I tried the no-cache (meta tag) but my problem is that the cookies are also gone (i couldn't store state).
By the way, my login uses redirect. The form submit calls a different page doing the validation and then redirects back to the same page but supposedly with different content (login form should not be there anymore).
I believe this is basic but unfortunately couldn't find an answer elsewhere.
Thanks.
Update:
Here are some codes:
Login page has ExtJs Form with submit:
login.getForm().getEl().dom.action='bridge.php/login';
login.getForm().getEl().dom.submit();
bridge.php is a rest client to another server:
snippet:
<?php
//echo $HTTP_SERVER_VARS['PATH_INFO'];
require_once "RESTclient.php";
require_once "http_request.php";
$rest = new RESTclient();
$http_req = new httpRequest();
//$headers = $http_req->headers();
$headers = apache_request_headers();
foreach($headers as $key => $value) {
if($key != "Cookie" && $key != "Content-Type"){
unset($headers[$key]);
}
}
//$headers["Content-Type"] = "";
$inputs = array_merge($_GET, $_POST);
//$inputs = array_merge($inputs, $_);
$url = "http://another_server/rest_service_here";
$path = $HTTP_SERVER_VARS['PATH_INFO'];
$server = $url.$path;
$rest->createRequest("$server",$http_req->method(),$inputs);
$rest->addHeaders($headers);
$rest->setBody($http_req->body());
$rest->sendRequest();
// get the headers now
$responseheaders = $rest->getResponseHeaders();
$responsecookies = $rest->getResponseCookies();
if ($responseheaders != null) {
foreach ($responseheaders as $key => $value) {
header($key.': '.$value);
}
}
if ($responsecookies != null) {
foreach ($responsecookies as $key => $value) {
$name = $value['name'];
$val = $value['value'];
setcookie($name, $val);
}
}
if($path=='/login') {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logging in</title>
<meta HTTP-EQUIV="REFRESH" content="0; url=/new_index.php">
</HEAD>
<BODY>
Redirecting to homepage...
</BODY>
</HTML>
<?php
} else {
$output = $rest->getResponse();
//$output = $output." ".$http_req->method();
// start doing something about the output.
//echo $http_req->body();
//echo $http_req->raw();
echo $output;
//var_dump($headers);
}
?>
As long as you're doing the following...
Always set/delete the login cookie before you output anything
Always re-direct after you've set the cookie. Ideally this should be to a page with a different URL (even if it's only a different query string), but failing that one that isn't cached should work fine.
As soon as you re-direct (via a header('Location: ...'); call) end script processing via exit.
..then all should be well. That said, as #Jon says post some code and we can take a look.