I'm creating a website which requires a Login. When it logs in the system it creates a Session.
But I don't know how to validate my next page. Because if the user types the name of the second page in the browser, it enters without problem. What I want is to verify if there is any session created, and if there isn't, to redirect to the login page, instead of loading it and have access to it.

I hope somebody can help me,
thanks

Recommended Answers

All 31 Replies

It's been a little while since I've worked on something like this, but the way I used to do it was to have a function called requireLogin(). I would call this function near the top of any page for which the user had to be logged in in order to use. What the function would do is check for a certain key-value pair in $_SESSION. If it found the value, it didn't do anything really. However, if it didn't find the value that indicated the user was logged in, it would redirect to the login page using header("Location: login.php");.

It can be enhanced further by remembering what URL the user was trying to access so that you can redirct them back there following the login. I think I did this by, in requireLogin(), storing the current URL in something like $_SESSION['wantsurl'], and then after the login script runs, it checks for a value in $_SESSION['wantsurl'] and redirects them if there is one. If it's empty, it does whatever the default is (e.g. a message telling them they've been successfully logged in).

I can't even redirect my page when it loads.. I'm trying with this:

` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sistema</title>
    <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
    <script type="text/JavaScript" src="funciones.js"></script> 

    <?php
        header ('Locaction: http://www.google.com'); // -> Just testing if it redirects
    ?>

</head>

<body>
...

`

If that's an exact copy/paste from your code, then check the spelling of "Location" in your header() call.

It still won't work even after correcting that spelling. You can't call the header function when you have already set the headers. You need to move it to the top of document with nothing above it.

<?php
header ('Location: http://www.google.com'); // -> Just testing if it redirects
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sistema</title>
    <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
    <script type="text/JavaScript" src="funciones.js"></script> 

</head>
<body>

Here you have to first check if session variable is set or not,if yes then check if it is not empty string.
If it contains proper value,Perform required task else redirect to error page.

Refer session_start and header

<?php
session_start(); //start session.
?>
<!-- HTML 5 -->
    <!DOCTYPE html>
    <html>
        <head>
            <title>Login Page
            </title>
        </head>
        <body>
        <?php
            if(isset($_SESSION['user']) && $_SESSION['user'] != "")
                {
                    //Task to do
                 }
            else{
                    header('Location: http://www.google.com/'); //redirect URL
                }
        ?>
    </body>
</html>

Again, that won't work. If you do it this way you will just get an error. The call to the header function in PHP has to go before the browser renders any document markup/content. You would have to do it this way.

<?php
session_start(); //start session.
$_SESSION['user'] = NULL;

if(isset($_SESSION['user']) && $_SESSION['user'] != "")
    {
    ?>

<!-- HTML 5 -->
    <!DOCTYPE html>
    <html>
        <head>
            <title>Login Page
            </title>
        </head>
        <body>
        <p>Content</p>
        </body>
    </html>

    <?php 
     }
else{
        header('Location: http://www.google.com/'); //redirect URL
    }
?>
commented: Wrong.Remember that header() must be called before any actual output is sent,not before any rendering. -1

I was setting the session at the top there for testing btw.

Correct me if I wrong, from what I understood is you want to create a session if user logged and in second page check if session found
in login page

<?php
session_start(); #start session.
$_SESSION['user'] = #username or anything you want to set to session.;
?>

and in next page

<?php
session_start(); #start session.
if (isset($_SESSION['user']) && !empty($_SESSION['user']) ) {
# do whatever you want if session found.
} else {
echo ('<meta http-equiv="refresh" content="0; URL=http://www.google.com">');
}

I don't understand whats happening, it doesn't let me redirect my page. I have this
<?php header ('Location: http://www.google.com'); ?>
on the top of my page, before anything else, and it still loads the current page

It works fine for me. Make sure there is no white space anywhere before.

There is no space, nothing above my php code..

<?php
header ('Location: http://www.google.com'); 
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sistema de Pago</title>
    <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
    <script type="text/JavaScript" src="funciones.js"></script> 
</head>
<body>
hello
</body>
</html>

It still loads me the body, insted of redirecting

Again, that won't work. If you do it this way you will just get an error. The call to the header function in PHP has to go before the browser renders any document markup/content.

@pixelsoul:-Read this from manual.You are 100% wrong about this.Please don't misguide others if you are not clear.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

Thanks for the down vote IIM... especially since the line from the manual that just referenced says EXACTLY the same thing I had said... Go test your suggestion. IT DOESN't WORK.

Your reading comprehension is 100% wrong my friend.

@pixelsoul:- Before voting check the php manual.I am sure you are here to help others but your misconceptions might create obstacles for the people who are coming here to learn.
Read this line 5 times then you will learn.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

It will be better for your future and for others who have misconceptions about it.Refer this.

Just run the example i have given above.If it gives header already set error than i will stop coding.You have to learn a lot.

commented: stop coding. "Just run the example i have given above.If it gives header already set error than i will stop coding.You have to learn a lot." -1

Go test your suggestion IIM....

lol... my first down vote comes from someone elses incompetence. Sad.

i know pretty well where to give suggestion .just check the code above and then argue.

I have tested (not that I needed to) your code and it does not work. Do you want to know WHY it does not work IIM? You see, it doesn't work because of the reason I said it does not work. Someone else said the same thing I did also... it was the PHP Manual!

It works for me quite well.I am not sure about your exact reason why it is not working for you.

If it is creating problem for you then i suggest you to use something like this:-

if (headers_sent()) {
    die("Redirect failed. Please click on this link: <a href=...>");
}
else{
    exit(header("Location: /user.php"));
}

OR

<?php
  ob_start();

  // code 

 ob_end_flush();
?> 

So, back to someone that actually can be helped...

@GeorgeGVD, try this

<?php
flush();
header('Location: http://www.google.com'); 
exit;
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sistema de Pago</title>
    <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
    <script type="text/JavaScript" src="funciones.js"></script> 
</head>
<body>
hello
</body>
</html>

I am not sure what you have actually placed.So for your reference i uploaded my code in one of my test server .Check out http://adityagoyal.web44.net/test1234.php

<?php
session_start(); //start session.
if(!isset($_GET['name'])){//added this to check if name is sent
?>
<!-- HTML 5 -->
    <!DOCTYPE html>
    <html>
        <head>
            <title>Login Page
            </title>
        </head>
        <body>
        <?php
            if(isset($_SESSION['user']) && $_SESSION['user'] != "")
                {
                    //Task to do
                 }
            else{
                    header('Location: test1234.php?name=test'); //redirect URL
                }
        ?>
    </body>

</html>
<?php
}
else
{
echo "passed header test";
}
?>

I am pretty much sure about my code.

Dude, you should just drop it now. I put you code up exactly like you have it on your original suggestion and it doesn't work. I didn't need to test it because I know how the PHP header function works, but I did it for arguments sake. This is probably the most pathetic conversation/debate I have ever had on a forum concerning PHP. You even went as far to quote something from the PHP manual that said the exact same thing that I had said (seriously??). It is very obvious that you just don't get it. I can prove all day long why you are wrong, but I can't teach you how to learn. I really can't talk about this anymore, the rediculousness of it is hurting my brain. Hopefully though, someone else finds it an entertaining read.

I just showed you my code and link where i have uploaded.And for the php manual,read it again.I don't want to say anything.I only want to convey the right thing,taking it or not is your problem.

IIM, you are wrong. Pixelsoul is 100% correct. You quoted from the manual the exact reason which counters your argument.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

So by placing any html, php, and/or whitespace before header() will cause the page to fail. I don't know why you say it works, because it definitely does not work by normal PHP standards.

All of Pixelsoul's suggestions were correct and I stand by his answer, which I upvoted.

Just as an FYI: You are coming across as someone who is 1) Puffed up with an ego problem. 2) Can't admit to being wrong. 3) Flat out thinks he's better than everyone else. Probably is not the case nor your intentions, but you should really be careful of your word choice. 90% of communication is through facial reactions or tone of voice, you can only understand flat text so much.

Member Avatar for diafol

We could all do without this sort of handbag throwing. It doesn't help the OP. It's not to say that you shouldn't argue your case, but as Caeon states, there are ways to communicate on a public help forum.

For the record, my take:

For use of header - whitespace, static html or php-derived output or in simple terms (not a complete description), anything that could remotely be seen in the browser 'view source' should NOT be placed before it.

It is good practice to follow up with an exit().

@IIM
I can't see how your header routine should work as you have html output before calling it. Anyway, it's good practice to run php above the DTD if you insist on including php routines with html in the same file. Mixing up php code (other than things like simple variable output) with html is rarely a satisfactory situation.

For use of header - whitespace, static html or php-derived output or in simple terms (not a complete description), anything that could remotely be seen in the browser 'view source' should NOT be placed before it.

I just want to add one less obvious item to this list, a Unicode file containing a BOM marker can also cause issues.

Member Avatar for diafol

I just want to add one less obvious item to this list, a Unicode file containing a BOM marker can also cause issues.

Good shout.

I didn't need to keep responding to it, so that was my bad. I should of just walked away.

Please don't misguide others if you are not clear.

This got a little under my skin though.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.