I have a text that says "My Account" when a session is valid. When the user has already logged in, it should redirect them to AccountPage.html. If the user has not already logged in, it should redirect them to AccountLogin.html instead. I thought I could just add if statements like below but every time it runs to goes straight to login.html
<a <?php
if (empty($_SESSION["UserName"])) {
header("location:AccountLogin.html");
}
else {
header("location:AccountPage");
}?>> My Account </a>
You should study more. What you want is this code:
<?php
session_start();
$url = empty($_SESSION['UserName']) ? 'AccountLogin.html' : 'AccountPage';
?>
My Account
I highly discourage this kind of code where you mix HTML with PHP, the better would be to use some nice template engine like Smarty, Twig, Mustache, etc... You should study them too.
Bonus: location is a function that change the headers sent and instruct the browser to redirect to the specified url, hence it should be used when you need an hard redirect (and should be followed by an exit )
This is the code you're looking for. Ofcouse I can't be sure you're setting up the session somewhere the way you should. But if you do, this will work.
<?php
session_start();
if(!isset($_SESSION['UserName']) || empty($_SESSION['UserName'])){
//Personally I believe header("location") should only be used for hard urls but ok
header("location: AccountLogin.html");
} else {
header("location: AccountPage.html");
}
?>
I think you are setting up the link wrong.
Try this:
<?php
if (empty($_SESSION["UserName"])) {
$url = "AccountLogin.html";
}
else {
$url = "AccountPage.html";
}
?>
My Account
Related
I want to ensure that an HTML page only appears if the user has logged in. I'm trying to do it by setting a session variable from the login page then checking if that variable exists when the HTML page is loaded.
This is my code at the very top of the HTML page:-
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("location: http://localhost/project/fail.php");
}
?>
It doesn't redirect! Nothing happens at all except that the HTML page gets loaded.
Can anyone help please?
Thank you all for your helpful suggestions. The snippet I posted shows the very first lines: i.e. session_start(); is the very first line.
By moving the var check snippet from the session_start() segment and making a separate php check snippet immediately after the body tag, everything works as expected.
You can use header function : https://www.php.net/manual/en/function.header.php
Referring to it :
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("Location: http://localhost/project/fail.php");
}
?>
make sure that session_start() always come at the first line
if(!isset($_SESSION['checks'])){
header('location: fail.php');
}
I believe your problem is on the login page... Although, if I were to talk about this page, consider trying the following code instead of your snippet first. If it gives the desired outcome then you will know that the problem is with your header and not the session:
<?php
session_start();
if (!isset($_SESSION['checks'])) {
echo "not logged in";
}
?>
Do make sure you're referring to the correct session variable if this code doesn't work and feel free to share how you are starting this session on your login page.
I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>
So after a LOT of trial and error, I set up something to test whether my session is set or not, which looks like this :
<?php
session_start();
if (isset($_SESSION['email'])) {
echo "Logged In!";
}
else {
echo "NOT LOGGED IN!";
}
?>
And what I realize is that after Login ( which redirects to the site's homepage) The session is not set until I reload the entire homepagepage.
Has anyone experienced anything like this and/or knows how to get around such a problem?
Thanks in advance!
This snippet of code works for me as a test. Make sure your order of operations matches this. If that does not work, make sure you are allowing cookies in your browser. Failing that, there could be something screwy about your PHP/Apache configuration.
<?php
session_start();
if (!isset($_GET['test']))
{
$_SESSION['email'] = "something ".time();
header('location:?test');
die;
}else{
echo 'Value: "' .$_SESSION['email']. '"';
echo '<br /><br />< Do again';
die;
}
?>
Your pages need to be set up like so in this order (particularly the session_start()):
login.php
<?php
session_start();
// 1) Some code here to check database if username and password check out
// 2) If username and password check out and validation is good
// 3) Redirect to your next page (index.php in this case)
?>
index.php (home page)
<?php
session_start();
?><!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1><?php
if(isset($_SESSION['email'])) { ?>
EMAIL IS SET!! Great job!
<?php } else { ?>
UM...No..<?php } ?></h1>
</body>
</html>
I was having a horrible time with this. I have an index page that loads every time and inside a content div loads specific php scripts via include. I control the navigation of the website in this way by passing GET variables to the index.html, so my index page loads every single time no matter what content you're viewing. The very first line of index.html was:
<?php
session_start();
Some of my php scripts running as includes on the index page would set session variables then redirect to the index page and the session variable would not be there,, or they would not be set to what they should be. It was driving me mad, I could ctrl-F5 and sometimes they would show up and sometimes not. The only thing I can figure was that it was somehow opening different sessions for different urls that were in the address bar (by different urls I mean ones with different GET parameters. Simply putting this at the beginning of my index.html solved all my problems. I assume this causes the same session to open each time:
<?php
session_name('SessName');
session_start();
Thanks for all the help guys, but I found the problem.
Apparently I have to be extremely specific with my url in the redirect file.
I had header('location: http://domain.com');
instead of
header('location: http://www.domain.com');
...facepalm
How to check if $_SESSION['myusername'] is empty and if so redirect them to index.html?
I'm currently using:
<?php
session_start();
/*** begin the session ***/
if(!isset($_SESSION['myusername']))
{
header('Location:index.html');
}
?>
But that lets non-authorized users to stay.
Make use of
<?php
session_start();
/*** begin the session ***/
if(empty($_SESSION['myusername']))
{
header('Location:index.html');;
}
?>
Change your code to this
<?php
session_start();
/*** begin the session ***/
if(!$_SESSION['myusername'])
{
header('Location:index.html');;
}
?>
Maybe you should use a stronger method to control access to your pages, like a RBA system...
Take a look at this, it helped me a lot
Try to like this:
session_start();
if(!isset($_SESSION['blah']) && empty($_SESSION['blah'])) {
header('Location:index.html');
}
exit() or die() after header()
I know this is old; but you did not share the full code.
I know this is from this tutorial here: http://www.phpeasystep.com/phptu/6.html
If you check your logs, you will see that a header cannot be set after HTML tags. If you look at the code from the tutorial, you will notice he has two HTML comments at the top.
Remove those, and PHP will be able to set the header and redirect the user. Otherwise, load the page in the else statement and serve the login form again in the if. Hope this helps.
Also, I am sure you are older and wiser after two years; but this is a poor log in process and (since the code won't work verbatim) a poor tutorial. For example, I can still get the contents of the page with curl http://example.com/protectedpage.php since it will not redirect me, and it will serve the rest of the page.
if(isset($_POST['submit'])){
echo "Success";
}else{
header("location:yoursiteurl");
}
I want to make my php page only accessible from another page redirect and prevent my user from accessing it directly.
I mean, let's say I have a page called "main.php" and another PHP file that I want to prevent direct access to, called "noaccess.php".
I want to make noaccess.php accessible only if I redirect from main.php
Any suggestions?
UPDATE: Session is a good idea, but the problem is I have to use JavaScript to redirect the page, so the question is, can I use ajax to set a PHP session?
UPDATE 2: OK I found the solution, I don't need preventing direct access now, as I can check from mysql whether the page needs to be accessible or not.
What if everytime you were going to redirect you saved a value in the $_SESSION variable. So you have
//code
$_SESSION['fromMain'] = "true";
header("Location: noaccess.php");
Then in noaccess.php put
if($_SESSION['fromMain'] == "false"){
//send them back
header("Location: foo.php");
}
else{
//reset the variable
$_SESSION['fromMain'] = "false";
}
I really don't know if this would work or not, but this is what I would try off the top of my head.
try this
if (!isset($_SERVER['HTTP_REFERER'])){
echo "uh?"; }
else {
// The script
}
I think you're probably coming at the problem from the wrong direction, but if you really want to implement this I'd most likely do it with a session variable. Just have main.php set a flag indicating that they're now able to access noaccess.php and then redirect there. noaccess.php checks for the flag, and only functions if it's been set.
To prevent access to pages, the best practice is to use session variables say $_SESSION['username'] and $_SESSION['password'] to check against your database table record assuming your table name is "users", the fields 'username' and 'password' in order for users to gain access to the page, else they are redirected to the log in page for them to supply the correct username and password through the input field.
Below is an anatomy of Preventing Direct Access to a PHP Page.
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$query="select * from users where username='$_SESSION[username]' and password='$_SESSION[password]'";
$result=mysql_query($query);
if($result)
{
echo "Your login was successful..";// the page you want to go to if login successful
{
else
{
header("Location:index.php?action=login");//any page you want to return to if log in failed
}
I know this has already been answered. Although the answers are good, I was just facing the same situation so I thought I would put my two bit in.
I would not use HTTP_REFERER It is not reliable and not every browser even shows it.
I would not use a session variable as that is stateful and you will have to write more lines of code to check it on every request leading to unnecessary bloat.
Ideally I would create a controller class with two functions main and no access
Or If you dont want to go through that trouble, I would create a variable which is globally accessible in noccess.php with a simple true false.
This is what I would do:
class Access{
protected $access = false;
public function main(){
//Authenticate and set
include_once 'main.php';
$this->access = true;
}
public function no access(){
if($this->access === true){
include_once 'no access'.php;
}else{
header('location: main.php');
}
}
}
Or if you dont want to go through that trouble You could create a simple function or set a simple variable which is accessible from noaccess.php:
//main.php
$access = false;
header('location: noaccess.php');
//noaccess.php
include 'main.php';
if($access){
//Continue
}else{
header('location: main.php');
}
Im sure you could simplify this, but this would be the simplest and safest approach rather than relying on server variables.
I would not use a $_SESSION or $_POST as that means unnecessarily posting a form when all you want to do is secure access
You can use $_SERVER["HTTP_REFERER"]. Put the following code in the beginning of your php file and set $url to be equal of your desired url for example http://a.com/main.php
if ($_SERVER['HTTP_REFERER'] != $url) {
header('Location: noaccess.php');
exit();
}
Why not to just include instead of redirect?
The other folks are right there are issues with $_SERVER["HTTP_REFERER"] so I guess the best way will be to have a variable set into a $_SESSION or $_POST and you will need to check if that variable exists, if not it means it is a direct access.
You tried on this Iva. Below is the code that works:
$url != 'your-url-which-you-do-not-what-direct access';
if ($_SERVER['HTTP_REFERER'] == $url) {
header('Location: otherurl.php'); //redirect to some other page
exit();
}
Ensure this appears at the top of the page where you do not want direct access to.
I think I am late to answer this but my way would be
<?php
$page = basename($_SERVER['PHP_SELF']);//gets current URL
if ($page == "nonaccesspage.php") //any page u don't want to be accessed directly
header('Location:index.php');
else if($page == "nonaccesspage2.php") //page 2 which is not accessible
header('Location:index.php');
?>
If you want to authorize the user for accessing the page (I mean there is a page which is not included but can be accessed with the URL) just use $_POST or $SESSION for authorizing the user with ID and password or something like that.