开发者

How to redirect a page to the same page in php

I have two files; the logic is such that if session is started i've to run a piece of code and if its not set then i have to run the else part. In any case i need to throw the page onto itself. H开发者_如何学运维ere's my first file

First File (file1.php)

<?php
require_once('file2.php');
if(isset($_SESSION))
        echo '<br>Session set!';
else
{
    //echo '<br>Session NOT set...';
    sessStart();
    header("Location:file1.php");
}
?>

Second File (file2.php)

<?php
function sessStart()
{
    session_start();

    //some other code here but nothing that echo's
}
?>

What I do here is call sessStart() method to initialize the session in the else part the first time it is run. The next time it should not go into the if section but else part.

Somehow the code doesn't redirect the file to the same file and the part where the session is set doesn't initialized. If i store something in the session in 2nd file i can retrive it in the first file so the session is started successfully but how to redirect?

What's wrong that i am doing?


Ok firstly its pointless what your doing.

kjy112's answer does absolutely nothing apart from cause the page to constantly refresh.

you should never need to do a check on _session, you just need to make sure that before any usage of $_SESSION or any content sent out you call session_start().

I would recommend that you restructure your current code into something a little more like this.

require_once "includes/startup.php";

and within startup.php

//Load primary includes
require_once "libraries/session.php";
require_once "libraries/input.php";
require_once "libraries/output.php";
//etc

if(!session_id())
{ 
    session_start();
    session_regenerate_id();

    //Other session bits
}

That's basically all you need you do.


I was trying to do something like below code but use of session in my example made you guys think am messing up session initialization :) It was more of a header problem. The below code is NOT POSSIBLE

//filename [1.php]
<?php
$x = 'n';

if($x == 'y')
    echo 'entered top';
else
{
    $x = 'y';
    header('1.php');
}
?>

You cannot redirect a page to itself using the header(); it will constantly get redirected.


You can't do the header redirect after you have echo'd anything.

Your example would work if you didn't echo "not set" before you redirected. When did you expect to see this message if redirecting immediately after it.

Personally I wouldn't put the session start functionality in a function, I would include a file that ran session_start() in every script you need it in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜