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;
});
});
Related
I am working with a login system. Here is my code to redirect some other page after successful login. I just want to go back to the previous page instead of redirect some specific page.
Code: login.php
<?PHP
require_once("./include/membersite_config.php");
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("login-home.php");
}
}
?>
In the previous page
add these:
session_start();
require_once("./include/membersite_config.php");
if (!$fgmembersite->CheckLogin())
{
$_SESSION['redirect_url'] = $_SERVER['PHP_SELF'];
header('Location: login.php');
exit;
}
login page
session_start();
require_once("./include/membersite_config.php");
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$redirect_url = (isset($_SESSION['redirect_url'])) ? $_SESSION['redirect_url'] : '/';
unset($_SESSION['redirect_url']);
header("Location: $redirect_url", true, 303);
exit;
}
}
In PHP you can get the previous page using $_SERVER variable. By this $_SERVER['HTTP_REFERER'], which contains the page URL from the current page is being called.
But sometimes there is an option in the browser which some users can
disable to send this information.
So beware to use this option.
Alternate to this option is to set a value in form and send it along with other data, that is still vulnerable as this can be changed by user easily.
You can try this approach:
In your login page:
$comingFrom = $_SERVER['HTTP_REFERER'];
if(isset($_POST['submitted']))
{
//or you can store it in session also.so that you can redirect it from anywhere.
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL($comingFrom);
}
}
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
In my website i have used ajax at many places... But the problem is that the file, lets say some_ajax_file.php, is visible in the source code... I want that other users dont just type this in the url and go to this page... If they do so, they will then be redirected to another page...
I tried following code on that ajax page:
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$cur_page=curPageName();
and checked it
if($cur_page=="some_ajax_file.php")
//then redirect...
it is working if the type some_ajax_file.php in the url...but the problem is that the the ajax function where i used this some_ajax_file.php is not working....plz help me ....i m stuck....
You must have to search for $_SERVER['HTTP_X_REQUESTED_WITH']
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
// I'm AJAX!
}
else
{
header();
die();
}
Create a Session at the time of Login
<?php
session_start();
// store session data
$_SESSION['Username']= Userid;
?>
and check the Session Available on that Page...
session_start();
if(empty($_SESSION['Username'])) {
//Redirect them to common page....
}
if the session availed then Show the page
Otherwise redirect them to login page....
I am wondering if it is possible to call a script through a redirect. I have a contact form using PHP mail that echos a redirect back to the home page, like so;
...
header("Location: ../index.php");
...
Is it possible to add an onload event that gets passed to the redirected page? So when "index.php" is loaded from the redirect it calls a pop up thank you or something like that.
If you're sending them to the next page like this, you could either append some instructions to the end of the url, or you could store them in a session variable and check that upon the next page load - or even a combination of both.
session_start();
$_SESSION["redirect_url"] = "options.html";
header("Location: ../index.php?redirected=1");
And perform some type of check on the new landing page:
session_start();
if ( $_GET["redirected"] && $_SESSION["redirect_url"] ) {
echo "<script>
window.onload = function(){
var myWin = window.open( '" . $_SESSION["redirect_url"] . "' );
};
</script>";
}
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>
}