I am new to cookies, and tried to search for my problem, but couldn't find it.
My code:
index.php
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
When you open the page in the browser, the bottom part of the php code is executed, there shouldn't be a cookie 'time' so the body will be echoed with the onload="toggleoverlay()". This all works fine.
then when i click on the submit button to accepts the cookies, the page is reload, and the upper part of my php code is executed, a cookie named 'time' is created with the current time.
then the bottom part should be executed, but it still echos the body with the onload, even though i just created the cookie.
i also get the error when i'm trying to echo the cookie (saying the cookie does not exist). when i reload the page again manually then it works. But this is very frustrating since you need to accepts the cookie. then the page gets reloaded, and the overlay opens again.
I think this is because it takes some time creating the cookie and by then the other code has already been executed, but does anyone know how to fix this?
Thanks in advance.
The cookie is not set until the response is sent back to the client (browser). It is not available in your PHP until the next request from the client after that.
You could do next.
<?php
$cookie_set = isset($_COOKIE['time']);
if (!$cookie_set && isset($_GET['submit']) {
setcookie('time', date('Y/m/d H:i:s'), time() + 3600);
$cookie_set = true;
}
if ($cookie_set) {
echo '<body>';
} else {
echo '<body onload="toggleOverlay(0)">';
}
I have found a semi-solution, if the page is submitted, the page is reloaded, then after the cookie is created, i reload the page again en change the index.php?submit to index.php
like this
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
header("Refresh:0; url=index.php");
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
Like this it works, but it is not the best solution.
Related
I work in PHP. I want to redirect page after login to the last page that i want to visit, but I'm still stack at here in 5 hours and I still don't make it yet. This is the schema, I have 3 php file.
newest.php (before login),
signin.php (before login),
thread.php (after login).
I'm using cookies for this redirecting. First i went to the newest.php, then i clicked the button (go to thread.php). Then thread.php saw that you haven't loggin yet, then redirected to signin.php. After i fill the signin form then, i clicked the submit button (the signin.php), then I'm stack at signin.php (not going anywhere) even after I've loggin in, it should be go to thread.php automatically.
this is my code in newest.php & thread.php (not in signin.php):
$coopage='coopage';
$current_page='http://'.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
setcookie($coopage, $current_page,time()+86400,'/');
submit button in newest.php (it goes to thread.php):
echo "<center><button onclick=\"window.location='/thread/form'\">add new thread</button></center>";
in signin.php (after i clicked the submit button or in submit area, because form and after submit i made in the same page) (in the bottom of the page):
if(isset($_COOKIE[$coopage])){
$url=$_COOKIE[$coopage];
unset($_COOKIE[$coopage]);
header('location:'.$url);
}
note: in signin.php i also have another cookie setup before this cookie, is that the cause of this? or does it matter if i have 2 cookies setup in one page? Another cookie setup is like this (at the top of the page)
$cooval2='juna';
setcookie($coousername, $cooval2, time() + (3600 * 24 * 365), "/"); // 1 year
I would not use cookies at all.
Method 1
A possible way could be to store the link visited into a session variable and then when the user reaches the login.php page, provide a header redirect to $url given by the session variable.
Paste this code into all your pages on your website or the main container.
<?php
session_start();
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
For the login page you can have:
<?php
session_start(); // needed for sessions.
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "student_account.php";
header("Location: http://example.com/$url");
Method 2
A simpler solution by far is simply to have:
<hidden name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
Then redirect to that address once they log in.
However, this is only good if you have a login box on every page.
$_SERVER['REQUEST_URI'] will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER'].
So save the HTTP_REFERER in a hidden element on your form, but also take note on that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.
Method 3
Another common way to do this is to pass the user's current page to the Login form via a $_GET variable.
change your script so that is also tells the login page to remember where you are:
Note: $_SERVER['REQUEST_URI'] is your current page
header("Location:login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
Now check if it is populated, then send the user to this:
login.php
echo '<input type="hidden" name="location" value="';
if(isset($_GET['location'])) {
echo htmlspecialchars($_GET['location']);
}
echo '" />';
// Will show something like this:
// <input type="hidden" name="location" value="previousPage.php" />
login-check.php
session_start();
// our url is now stored as $_POST['location'] (posted from login.php). If it's blank, let's ignore it. Otherwise, let's do something with it.
$redirect = NULL;
if($_POST['location'] != '') {
$redirect = $_POST['location'];
}
if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) {
$url = 'login.php?p=1';
// if we have a redirect URL, pass it back to login.php so we don't forget it
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location: " . $url);
exit();
}
elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) {
$url = 'login.php?p=2';
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location:" . $url);
exit();
}
elseif(isset($_SESSION['id_login'])) {
// if login is successful and there is a redirect address, send the user directly there
if($redirect)) {
header("Location:". $redirect);
} else {
header("Location:login.php?p=3");
}
exit();
}
Your new cookie => local storage, make sure to have this code on every page you what to log the url on except for the login page otherwise it will redirect you back to the login page.
var currentPage = window.location.href;
localStorage.lastPageVisited = currentPage
This is then the code for the submit button and it will redirect the user to the last page he visited.
$(document).ready(function() {
$('button').click(function() {
window.location.href = localStorage.lastPageVisited;
});
});
My question is may be foolish. But I want to know, if there is any code that prevent the page opening if tried with link but opens only after . if it's link is from another page.
for example, if i have a form on page contact.php and user gets redirected to page contact_success.php.
Now I want, if anybody tried to open contact_success.php page directly from browser address bar, it should not be get opened. It should be get opened only after form submission from contact.php page..
A simple way is just to use an if check on the contact_success.php page like
if($_SERVER['REQUEST_METHOD'] = "POST"){
//display page
} else {
echo 'You cannot view this page.';
//add redirect, if you like
}
Set a session or a cookie for the user in the contact.php, and then in the contact_sucess.php you can check if it exists.
for exmaple:
contact.php:
<?php
$_SESSION['visited_login'] = 'yes';
?>
contact_sucess.php:
<?php
if (isset($_SESSION['visited_login']) && $_SESSION['visited_login']=="yes") {
// output tanks
} else {
echo "go away";
die;
}
?>
You can use session for that example:
let say when you submit the contact form there is a page where in you will process the user input and i will use(refer to the #1)
contact_process.php
$_SESSION['success'] = 'success';
(this code will create a session)
then once success in processing the user input there is another page like(refer to # 2)
contact_success.php
if(isset($_SESSION['success'])
{
//Output if it is success
}
else{
header('location:contact.php');
}
(this code will check if session is existing if yes the desired output will show and if not it should turn back to contact.php)
you can easily learn session here http://www.w3schools.com/php/php_sessions.asp
why my echo doesn't work here in this code?It goes directly to the function header().
if($result){
echo("<script> alert('User Successfull Added')</script>");
header('location:home.php');
}
In order to make your code example work, you need to put it inside an if/else condition like so, if you want it to work, but since I only see what you posted as code, am putting this in as an example:
<?php
if($result){
echo("<script>alert('User Successfully Added')</script>");
echo("<script>window.location = 'home.php';</script>");
}
else {
header('Location: elsewhere.php');
}
Actually thy echo is working. but we cant see the message because at the same time the page redirects to the home.php page.
If you want to alert to display the alert message use jquery post. or php session variable
Assuming you want to both display the alert & redirect to home.php, why don't you just try setting a SESSION (or other global variable) and then check if it's set at the start of the redirected page?
Such as:
<?php
session_start();
$_SESSION['usercreated']="Y";
header('Location: elsewhere.php');
?>
and then on home.php at the start of your php code:
<?php
session_start();
if(isset($_SESSION['usercreated'])){
echo("<script> alert('User Successfully Added')</script>");
}
//....
?>
Sorry, I can't add comment here. But I think what you want to do needs Java and replace alert() with confirm()
var r=confirm("User Successfull Added")
if (r==true) // if user click OK
{
window.location.assign("home.php")
}
else // user click Cancel
{
}
While designing sign up page I wish to reload page if user has submitted anything wrong in the fill up boxes. How can I reload page after the user presses submit button with a wrong entry ? (while verifying expected content through php)
You can use header() plus some _GET variables for telling the original page there were errors.
Form submit page:
<?php
//.... lots of code validation
if ($failed) {
header('Location: http://path.com/to/your/site/original_form.php?error=1');
}
?>
Form page:
<?php
if (isset($_GET['error']) {
echo "there was an error! Please fix it!";
}
?>
Try the following -
if (validation_failed) {
header("Location: http://yourserver.com/signup.php");
} else {
header("Location: http://yourserver.com/welcome.php");
}
PHP Header function
I have a page action.php on which I run an SQL query through the code, so that whenever the page is viewed the query runs like its like counting page views
<?php
mysqli_query("UPDATE ****");
?>
The problem is when the page is refreshed, the query is run & PAGE REFRESH is counted as a PAGE VIEW which I want to avoid.
Question: How to avoid it ?
What I am looking for is a simple solution so that I can check
if( page was refresh ) //some condition
{
do
}
I found this snippet here, and it worked perfectly for me:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageWasRefreshed ) {
//do something because page was refreshed;
} else {
//do nothing;
}
Best way to Detect Page Refresh. or Not ?(Ctrl+F5,F5,Ctrl+R, Enter)
$pageRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&($_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0' || $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache');
if($pageRefreshed == 1){
echo "Yes page Refreshed";
}else{
//enter code here
echo "No";
}
You can't directly detect a page refresh, but you can use a cookie to simulate what you want:
if (isset($_COOKIE['action'])) {
// action already done
} else {
setcookie('action');
// run query
}
Depending on your requirements, you also need to decide when to remove the cookie and/or perform the action again.
If you just want to run it once for a user, I would set a session cookie and then use an if() statement.
<?php
session_start();
if (!$_SESSION['loaded'])
{
// insert query here
}
$_SESSION['loaded'] = true;
?>
i have solved the problem ... HURRAHHH with no session & no cookies
the solution is a combination of PHP : AJAX : JavaScript
the query that you want to run on Page Load & not on page Refresh run it as via AJAX call lets say my function for doing that is
function runQUERY()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","doIT.php",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
and i can simply check with Javascript that the page is a fresh load or its a refresh by doing the following
<head>
<script type="text/javascript">
function checkRefresh()
{
if( document.refreshForm.visited.value == "" )
{
// This is a fresh page load
alert ( 'Fresh Load' );
document.refreshForm.visited.value = "1";
..call you AJAX function here
}
else
{
// This is a page refresh
alert ( 'Page has been Refreshed, The AJAX call was not made');
}
}
</script>
</head>
<body onLoad="checkRefresh()">
<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>
</body>
</html>
and in your doIT.php simple add your PHP code which you were going to put in the normal page
<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>
//here you get the url behind the domain.
$currentPage = $_SERVER['REQUEST_URI'];
//if the session current page is not set.
if(!isset($_SESSION['currentPage'])){
//set the session to the current page.
$_SESSION['currentPage'] = $currentPage;
}
//check if the session is not equal to the current page
if($_SESSION['currentPage'] != $currentPage){
// if it's not equal you set the session again to the current page.
$_SESSION['currentPage'] = $currentPage;
//set the query you want to use
}
This can work in your scenario:
if(isset($_GET["token"])) {
$view_token = $_GET["token"];
} else {
$new_views = $views + 1;
// UPDATE VIEWS
$view_token = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
header("Location: ?token=$view_token");
}
If the user has a token in the URL, the view count will not update. Therefore, if the user tries to refresh, it will not update the view count. When the user does not have a token in the URL, the view count updates and refreshes the page WITH a token. It is thinking outside of the box but it works!
You can save a cookie that will be associated with the present page and if any link is clicked, update the cookie with the new page name.
Assuming the above is done in Javascript, you can send this updateCookie information to the server to notify about a new page hit.
Or another approach could be, you can specify a HTTP HEADER that specifies after how much time the cache expires on a page and that way, the browser wont even send you a request about page load/refresh.
See http://www.mnot.net/cache_docs/#IMP-SCRIPT for information about CACHING
Also , check out Etag vs Expires in HTTP - ETag vs Header Expires
if( $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
{
$_SESSION['status'] = null;<br>
}