PHP If Statement doing the wrong thing once [duplicate] - php

This question already has answers here:
Force users to access website from the homepage
(4 answers)
Closed 11 months ago.
I've been tasked to make a new login page that forces clients to touch the home page first each time they visit. It was recommended to me to try out HTTP_REFERER, to check where the client was coming from. My first pass on the page looked something like this...
<body>
<?PHP
if($_SERVER['HTTP_REFERER'] != "https://www.homepage.com/"){
header('Location: https://www.homepage.com/');
exit;
} else { ?>
//html code for login page
</body>
<?PHP } ?>
The issue I keep running into, is that... when clicking the 'login' button on the home page to enter this new login page, the new login page will seemingly run the header portion of code, and boot back to the homepage on each FIRST attempted. Clicking 'login' button a second time on the homepage won't boot back, and will instead load the page as expected. If I clear the site data from my browser (Chrome), and click login, it will boot back the first time again.
Since it didn't seem to effect people using Safari, I speculated that maybe it's Chrome loading the page before the HTTP_REFERER was setup. So I included a line of sleep(3);. This didn't help at all.
I then speculated that maybe it's HTTP_REFERER's fault, and I have since switched over to using a SESSION variable instead for the job. No good, same issue.
The last thing I tried was reorganizing the if statement to have the fail state second in order on the page. Perhaps as expected, this didn't matter either.
I feel like I must be missing something, and would appreciate any insight. Thank You.

Referer is not a safe option for testing. If the first_login session is not assigned and the requested page is not the homepage, the code below sets a cookie named first_login and redirects to the homepage.
This process is valid as long as the browser session exists.
<?php
ob_start();
session_start();
if(!isset($_SESSION['first_login']) and $_SERVER['SCRIPT_URI']!='https://www.homepage.com/')
{
$_SESSION['first_login'] = 'success';
header('Location: https://www.homepage.com/');
exit;
}
?>

Related

redirection to login page ERROR localhost redirected you too many times

Using PHP 7.1, MySQL, HTML5 Using localhost at present, I wanted to set-up a redirect from each webpage if the user is not logged in, to return to the login page login.php.
So I added the following include header.php to all of my PHP files
<!-- header.php
on all webpages, checks if user logged in, redirects to login.php if NOT
https://stackoverflow.com/questions/29202153/how-to-redirect-users-to-login-page-if-they-havent-logged-in
-->
<?php
session_start();
if(empty($_SESSION["username"])){ /* IF NO USERNAME REGISTERED TO THE SESSION VARIABLE */
header("LOCATION:login.php"); /* REDIRECT USER TO LOGIN PAGE */
}
?>
I am now getting the error
localhost redirected you too many times.
Having cleared all my cookies as recommended and rebooted my system, and I have removed the call to header.php from about 40 php files, it is still a problem.
I should say that it worked 100% until I edited my approximately 40th PHP file to add
<?php require('header.php'); ?>
Then the error was displayed in the chrome browser as follows.
This page isn’t working
localhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
I can add the header.php to less files in the future i.e. by adding to a higher level php file.
how do I fix the error so I can continue to develop and
what change do I make to the code to prevent the error in the future.
I assume the system is now in an infinite loop, which needs to be cleared
I am desperate for a quick solution so any help would be much appreciated, I will continue looking for a solution in the meantime.
Many Thanks in advance, Colin
The code after header('Location: login.php') is still being executed unless you know what you are doing always exit() after a Location header as this is much more secure.
Also, you can change the require to avoid a double include (that would cause this problem)
<?php require_once('header.php'); ?>
However this more of a patch than a code logic fix.
A better solution would be to do something like the following:
#header.php
if(!defined('TO_LOGIN')){
define('TO_LOGIN', true);
header("Location: login.php");
exit();
} else {
trigger_error('Another request to "login.php". debug: <pre>' . print_r(debug_backtrace(), true) . '</pre>');
}
Because if a client does not have cookies enabled, this would never cause the code to loop.
I have solved the problem, my file header.php (used to check if user logged in and call login.php if NOT logged in) was calling login.php
header.php
called login.php
called header-loginregister.php
called header.php
so it was creating an infinite loop, I need to be careful where I place the include header.php call to avoid this mistake in the future.
So indirectly login.php was calling itself via header-loginregister.php and header.php
Thanks for all the comments on how to improve the code which I will implement.

how to redirect wrong entered url

My current url is http://domain.com/example.php/link=eg But if someone plays with url and puts url as http://domain.com/example.php/abcdefgh97654 - anything, my all functions all links from that page become inactive.
I tried using <?=HTTP_SERVER;?> before all links in my php files but as my website has user registration and sign in, when user signs in and clicks on any menu (link from php script). It throws on index.php page. But if user logs in again it works perfectly. In short user needs to log in twice to work everything perfect.
Basically I want two solutions one I want to redirect www dot
domain dot com/example dot php/abcdefgh97654 - anything (wrong url
page) to errorpage (I already done this in htaccess) but does not
work for above type.
List item
And want to solve two time log in problem.
If anyone has solution for this will be appreciated.
For you to do this, you have to know what values are supposed to be passed via $_GET variable to your page. Then you can create filter for the values and user header(); function.
Here is my suggestion:
<?php
$var=$_GET['val']
//get expected length if you need.
if(strlen($var)>9 or strlen($var)) {
$redirect=true;
}
//if you know what you are expecting
$vals=array('val1', 'val2, 'val3');
if(!in_array($var, $vals)){
$redirect=true;
}
//continue or replace your filters in this manner and asign your value to $redirect
if($redirect==true) {
header("Location:url"); // do this before anything else is printed to the page or else it will say headers already sent.
}
?>

How do i redirect after login? php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP login then redirect
I've just made a php login page. Upon entering their data, the information is submitted back to the same page where validation occurs.
I'm just not sure how i go to my content page after this is done.
Do i use a require statement that only runs if validation is successful?
I read a similar post on SO and the solution was:
public void redirect(mixed $url, boolean $terminate=true, integer $statusCode=302)
But im not really sure what im supposed to put where, and which of those terms i literally enter versus which terms are placeholder values that im supposed to fill with something. Also not sure if $url can be filled with a relative url like memberpage.php.
Some clarification would be greatly appreciated.
edit:
Wait...public void... isnt that java terminology?
On successful login, set whatever $_SESSION variables you need (if appropriate), then redirect using:
header ("Location: mypage.php");
Remember, you need to send this header before outputting (echoing) anything.
You could try to add a redirect in your header. Code would be something like this:
login_validator.php
validation code
if(isvalid(login)){
header('Location: loggedin/welcome.php');
}else{
some other handler;
}
So, if I'm getting this right, you have a user input information, and hit submit - that form then posts to itself where you have php at the top that says something like
<?PHP
if(isset($_POST[name]){
//input everything
}
?>
If this is true, you can just put a line that say something like this:
header('Location: http://www.yoursite.com/new_page.html') ;
inside, at the very bottom of that previous if statement.

How to access offsite referer (and first page visited on site) via PHP on Wordpress site

I'm trying to get three things into a hidden form field in a Wordpress page:
The last "offsite" page visited before someone visited any page on my site (e.g., quite possibly a Google page)
The first page they visited on my site
The last page on my site before they went to the form page
The third one is easy (just use ), but the first two are giving me problems.
I'm trying to save #1 and #2 by using session variables, so that on every page, in the header, I have the following code:
<?php
session_start();
if (! isset($_SESSION['offsite_referer'])) {
$_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER'];
}
if (! isset($_SESSION['first_page'])) {
$_SESSION['first_page'] = $_SERVER['REQUEST_URI'];
}
?>
Then further down I have, as test code (to be changed to input type=hidden etc. later):
<p>offsite_referer: <?= $_SESSION['offsite_referer'] ?></p>
<p>first_page: <?= $_SESSION['first_page'] ?></p>
(FWIW, I also have session_start() at the top of my wp-config.php. Yes, my site has register_globals turned off.)
For some reason, $_SESSION['offsite_referer'] always ends up as my home page, even when I hit the form page (/free-reports) directly via link from another site. Similarly, first_page always shows up as /
Yes, I'm clearing all my cookies etc. between attempts, to force a new session to be created.
This code used to work fine on my pre-Wordpress site, so I can only think it has something to do with WP, specifically perhaps WP's redirection (WP's mod_rewrite stuff in .htaccess)
I tried changing $_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER'] to wp_get_original_referer() but it seemed to have no effect.
Incidentally, if I access my form page (at /free-reports/) as the first page on my site (after clearing cookies etc.) and printing $_SERVER['HTTP_REFERER'], it correctly shows the last offsite page - even though $_SESSION['offsite_referer'] doesn't.
I'm pretty perplexed, and have spent a fair amount of time trying to figure it out on my own, so any help to solve this would be appreciated.
Chances are, you can't really get the referer URL since some browsers don't send that and some people disable that, but here's how you could do that and I'll give you some extra tips here:
//first of all, initialize the session
session_start();
//Now call logvisit() to log where the user is coming from
logvisit();
function logvisit() {
$_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER']);
$browser = $_SERVER['HTTP_USER_AGENT']; //Gets the browser the user is using
//If you want to test it (disable the code below if you don't want to print that information):
echo "Offsite referer: $_SESSION['offsite_referer']<br>";
echo "Browser: $browser<br>";
}
Then to destroy the session you can use unset($_SESSION['offsite_referer']);
This is how I usually do it, and it's often a tidy way to do it.
I believe scunliffe had the key to this, as I was using IE to do the testing.
It works fine now, which I attribute to actually closing and restarting IE (apparently just deleting cookies doesn't do it, as you'd think, even though that works fine in Firefox).
I also changed what I was doing slightly to just save the full in-site browse history in a session variable, rather than only first and last page on the site.
The code I ended up with was the following, which is just at the top of my theme's header.php file:
<?php
session_start();
if (! isset($_SESSION['site_history'])) {
$_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER'];
$_SESSION['site_history'] = '';
}
$_SESSION['site_history'] .= ($_SERVER['REQUEST_URI'] . ';');
?>
I originally had session_start() also in wp-config.php when I was trying to figure this out, but was able to remove it (leaving just the above code in header.php) and things still work fine.
In case anyone finds this page wanting to do something similar, I was able to access this info in my WP page by adding the following to my theme's functions.php:
function get_offsite_referer() { return $_SESSION['offsite_referer']; }
add_shortcode('offsite-referer', 'get_offsite_referer');
function get_site_history() { return $_SESSION['site_history']; }
add_shortcode('site-history', 'get_site_history');
and then to pass the info on my Wordpress page/form:
<input type="hidden" name="offsite_referer" value="[offsite-referer]" />
<input type="hidden" name="site_history" value="[site-history]" />
scunliffe, if you'd posted your comment as a "reply" I would have "accepted" it, since it was what most closely led me in the right direction, but as a comment I could only upvote it so that's what I did. Thanks!

PHP Login System problem... Sending errors from page to page

I have a login form in every page of a website so the user can login from everywhere. I have a login.php file that I refer to it from the form (using 'action').
I use $_SERVER['HTTP_REFERER'] to redirect the user to the same page he logged in from when he succesfully log in or when he logs out.
But if there was a problem logging in, how can I send an error to the same page he is trying to log in?? I have tried sending the error using $_GET, like this:
// process the script only if the form has been submitted
if (array_key_exists('login', $_POST)) {
// Login code goes here...
// If there was a problem, destroy the session and prepare error message
else {
$_SESSION = array();
session_destroy();
header('Location: '.$_SERVER['HTTP_REFERER'].'?error');
exit;
}
But the problem is that a lot of pages in the website are like this details.php?mid=0172495. They already recive information from the $_GET method and for security reasons I cant use another $_GET method...
So, How can I pass the error???
Thanks...
Since you're already using sessions, after you destroy the session why not create a new one with $_SESSION['error'] or something similar set? Or alternatively simply don't delete the session at all but set the error which you can immediately check in other pages?
To add to what Chad Birch said...
In your login script where you redirect, check the HTTP_REFERER value for the character '?'. If it is present, append '&error' to the HTTP_REFERER and redirect to that. Otherwise append '?error' to the HTTP_REFERER and redirect to that.
I'm not sure what exactly you mean by "for security reasons I cant use another $_GET method", but in the case that there's already something in the query string, you just need to append another variable to it, instead of replacing it.
That is, if the address is like details.php?mid=0172495, you should be sending them to details.php?mid=0172495&error, whereas if it was just details.php, you send them to details.php?error.
Another way of doing what you need is to include your login.php file in every page that has the login form and just post to that same page. So you won't need any redirection at all.
This maybe is not a good scalable and maintainable solution, but it is simple. It all depends what kind of app you are writing. But you are saying that you are new to php so you can start like this. You can always go fancy later...

Categories