I was trying to redirect users to the previous page after authentication. It works well with the below codes.
The file login_page.php (the page where users enter login credentials) contains the below code which stores the SOURCE URL and passes it to next page.
<input type="hidden" name="url" value=<?php echo $_SERVER['HTTP_REFERER'] ; ?> />
File do_authentication.php (page which does the authentication) has the code echo "<meta http-equiv='Refresh' content=0;url='$_POST[url]'>"; which redirects to SOURCE URL
In the normal situation it works, but in situations when user enters wrong credentials, the page is redirected to login_page.php and it asks the user to try again with correct credentials. At that time, 'url' value changes to login_page.php.
What is the correct/better logic to solve this?
I've always used the session to retain the original page when doing login. This will not work if the session isn't supported. Then I just send the user to the home page.
A Stack Overflow post discussing this is Redirect to previous page after logging in using PHP.
You should consider using session variables to store the value of the page you want to redirect to. HTTP_REFERRER is not right option.
Just try below:
<input type="hidden" name="url" value=<?php echo pathinfo(__FILE__,PATHINFO_FILENAME ).".".pathinfo(__FILE__,PATHINFO_EXTENSION); ?> />
Use:
header("location: ".$_POST['url']); // Redirects to posted page
exit; // Prevents execution of other code after this
In login_page.php, you could check if you already passed a URL; if so, pass this one instead of the HTTP_REFERER.
<?php if(isset($_POST['url']) ?>
<input type="hidden" name="url" value=<?php echo $_POST['url'] ; ?> />
<?php else ?>
<input type="hidden" name="url" value=<?php echo $_SERVER['HTTP_REFERER'] ; ?> />
Or in a more concise way
<?php $url= (isset($_POST['url'])) ? $_POST['url'] : $_SERVER['HTTP_REFERER']; ?>
<input type="hidden" name="url" value=<?php echo $url; ?> />
Related
I know that I can redirect to a website by using:
<?php header('Location: http://site/'); ?>
but how can I make it redirect to a variable value and make the redirect URI look like:
http://myURL.com/redirect.php?variable=http://redirect.com
Thanks!
Your page that asks a user for the URL:
<form action="redirect.php" method="GET">
<input type="text" name="url" />
<input type="submit" />
</form>
redirect.php
<?php
if(isset($_GET['url'])){
header("Location: http://" . $_GET['url'] . "");
exit();
}
?>
What this does
When a user submits a form on your index page (or wherever you dropped the <form> code they are redirected to http://yoursite/redirect.php and the variable url is appended to the URL as such: http://yoursite/redirect.php?url=THEURL where "THEURL" in this example is the URL that the user typed in on the form.
Please note, this is nowhere near secure enough, not does it do any validation (which you should absolutely do).
I have entered the following code to prevent CSRF but issuing and checking tokens.
The top section goes on the login.php, the second part goes on the landing page. The issuing of the token works, and when I print $_SESSION['token']on the landing page they match up. However, when i substitute the other code in, its says that they don't match and shows 'expired'.
<?php
session_start();
$_SESSION['token'] = $token;
$_SESSION['token'] = uniqid(md5(microtime()), true);
print $_SESSION['token'];
?>
<html>
<head>
<title>My first PHP website</title>
</head>
<body>
<h2>Please login here to see your tour</h2>
<form action= "checklogin.php" method="post">
Enter Username: <input type="text" name="username" required="required"/> <br/>
Enter Password: <input type="password" name="password" required="required" /> <br/>
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" />
<input type="submit" value= "login" />
</form>
</body>
<?php
session_start();
print $_SESSION['token'];
session_start();
if ($_POST['token'] !== $_SESSION['token']) {
die('expired');
}
?>
Following our discussion in the comments of your question I'm posting this answer so the information is summarized.
Your code is basically correct but the issue you're having is because after the redirect to the user's unique landing page you no longer can access the data in $_POST you originally have in your checklogin.php, i.e. after submitting the login form.
So in your checklogin.php script you have among others these options:
Include the token in the URL you're redirecting to and then check the $_SESSION['token'] against $_GET['token'].
Set a flag in the $_SESSION indicating that the use has been allowed access to the system. Something like $_SESSION['loggedIn'] = true; (that's what I would recommend)
NOTE: Here you are facing another issue: you have to think about restricting access of each user to only their own page. Imagine that if a user somehow knows the URL of another user's home page they could easily edit the URL and reach it. My recommendation is to save the user's id in the $_SESSION and then at the top of each user's home page to check whether the currently logged in user is allowed to open the said page.
I hope that makes it more clear!
The form action is login.php so when a user logs in the POST data is submitted to the login.php page. Your question does not explain how the user then gets directed to their landing page.
One option would be to try the following.
Replace:
<form action="login.php" method="post">
With:
<form action="landingpage.php" method="post">
That way on your landing page you will be able to get the value of
$_POST['token']
I am having an issue on how to make it where users who are viewing any page can log in on the page they are viewing and it stays on that page. How would this be accomplished?
Below is a single line I am currently using, however, if on any page and a user logs in, they are redirected to their profile. How can I set this line where it logs the user in, and it stays on that same page they are viewing? So in other words, are not redirected to their profile...
PHP:
header("Location: members.php?id=" . $_SESSION['username']);
If more info is needed, let me know and I can make an edit ;)
Have the login form submit the address of the current page. Then you can simply redirect back to that address when the login succeeds, e.g.
<form>
<input type="hidden" name="curpage" value="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" />
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
if ($login_is_successful) {
header("Location: {$_POST['curpage']}");
}
You could try using the referer, but since that's not sent by all browser, and is not always accurate, you're better off sing alternate "current location" tracking means, such as the above hidden form field.
When they click on the login button you can read the url and save it to a varibale and redirect them to this url.
So instead of
header("Location: members.php?id=" . $_SESSION['username']);
you can use sth. like:
header("Location: $last_page);
Try this
you can create a php file with this code and include into your code like this
session.php
<?php
session_start();
error_reporting(0);
if(isset($_SESSION["usuario"]))
{
$usuario = $_SESSION["usuario"];
else{
header('Location: members.php?id=" . $_SESSION['username']');
}
?>
index.php
<?php
include ('session.php');
?>
to avoid using same code in every page
On page1.php I have a form which sends vars via POST to page2.php.
However, I only want to process the form if it is called from page1.php.
How do I check for this?
Kind regards!
EDIT:
It's a kind of security measure. If i'm a hacker and I copy the form code from the source of the page and run it, I can change crucial vars.
EDIT2:
Ok here is the actual problem:
Users can edit credit to their account. They can choose values from 5EUR to 50EUR.
Eventually they come on a page 'deposit.php' where the final form is sent to a page 'payments.php' which then sends the var to Paypal.
Deposit.php:
<form class="paypal" action="paypal/payments.php" method="post" id="paypal_form" target="_blank">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="BE" />
<input type="hidden" name="currency_code" value="EUR" />
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
<input type="hidden" name="item_number" value="50" / >
<input type="hidden" name="price" value="47.50" / >
<input type="submit" class="uibutton " value="Betaal met Paypal" style="width: 100%; font-size:120%;">
(BTW they get a discount if they add 50EUR)
Well, first of all you have to understand that there is no security measure the way you put it.
And, of course, no method provided by other participants can protect your "crucial vars". They were actually answering other question, one is more familiar to them.
Forms are intended to be filled by client party. So, you can't expect whatever variable be untouched. Everything coming from the client side can be spoofed, no matter what measures you took.
So, whatever "crucial vars" should remain on the server.
While all the data coming from the form should be considered unsafe and treated accordingly.
Depending on the application, you could use $_SERVER['HTTP_REFERER'] and do a check but the problem with it is that not all browsers send it, and it is modifiable by the user. So if this is just for a few people that you know it probably won't be a problem. If this is for the world it isn't recommended.
What I usually do is set a session on page 1, then check for that session on page 2. Every time page 1 loads you need to reset the session.
page1.php
<?php
session_start();
$hash = $_SESSION['hash'] = md5(time().rand(0,100));
?>
<form action="page2.php" meethod="post">
<input type="hidden" name="h" value="<?php echo $hash; ?>" />
Your Name: <input type="text" name="name" />
</form>
page2.php
<?php
session_start();
if($_SESSION['hash'] != $_POST['h']){
header("Location: page1.php");
exit;
}
// process data
I think Adam D response is too weak (Anyone can change that just using firebug). what you want to prevent is users to skip some step or avoid XSRF.
In that case I would say use sessions.
Create a session
Save the current step
Retrieve and validate the current step and halt or continue according to the value
In your form, include a hidden field that you then check for on page2.php. See below:
<form action="post.php" method="POST">
<input type="text" name="fname" id="fname" />
<input type="hidden" name="cameFromPageOne" value="true" />
</form>
Then, on the top of page2.php, check that the hidden variable is set, and if not, redirect back to page1.php
<?php
if(!isset($_POST['cameFromPageOne']) || $_POST['cameFromPageOne'] != 'true') {
header('location: http://www.example.com/page1.php');
exit();
} else {
// ... code to process if they DID come from page1.php
}
?>
There's no reason to overcomplicate it, there's a global variable in PHP which tell's you the url your current script was requested from:
echo $_SERVER["HTTP_REFERER"];
I am having a strange issue of a session variable being empty when I clear it on the same page that I attempt to echo it. Here is a quick type-up of what I am trying to do.
Take this example;
Page A:
$_SESSION['referer'] = 'abc123';
header('Location: http://www.test.com/pageb.php');
exit();
Page B:
function get_referer() {
$referer = '';
if (isset($_SESSION['referer'])) {
$referer = $_SESSION['referer'];
$_SESSION['referer'] = null;
unset($_SESSION['referer']);
}
echo $referer;
}
Now when I do this on page B with the functions...
If I run it all by itself it works:
get_referer();
When I run the echo inside the value attribute of the input (making sure to only run the function once on the page due to it being erased after being called), it didn't echo anything when I view source the page.
<input type="hidden" name="referer" value="<?php get_referer(); ?>" />
However, funny enough, if I make the input type="text" it works fine.
<input type="text" name="referer" value="<?php get_referer(); ?>" />
The issue only occurs on the value attribute for input type="hidden"
You're outputting the content with
<input type="hidden" name="referer" value="<?php get_referer(); ?>" />
you're not viewing it on the same page as you would have if you were using type="text". When using type="hidden", you're most likely right-clicking the window and choosing View Source in your browser. The problem is that same browsers (like Chrome) refresh the page when you do so. This means, that once you load the page, the value attribute actually contains abc123, but when you attempt to see it, the page is refreshed, and therefore the session no longer exists, hence value is empty.
Maybe you are calling the get_referer() twice?
In the first it will echo the referer and unset. When you call in the input, the referer don't exists anymore in the session, so prints nothing.