duanjiu1950 2016-08-03 07:08
浏览 27
已采纳

如果使用PHP直接访问页面,如何重定向页面?

I have 2 php pages. 1st, is for login form and the 2nd php page is the information.

I want the 2nd php page only accessible if the user redirect from the 1st page redirect and prevent the user from accessing it directly.

Let's say the 1st php file called "form.php" and the 2nd php file that I want to prevent direct access called "info.php".

Any suggestions?

So far, see my code below (my code is not working) I got white blank page

Form.php

if(isset($_POST['submit'])){
    if((isset($_POST['username']) && $_POST['username'] != '') && (isset($_POST['email']) && $_POST['email'] != '')){
        $_SESSION["username"] = $_POST['username'];
        $_SESSION["email"] = $_POST['email'];

    $loginform = (strlen($_SESSION["username"])>0 && strlen($_SESSION["email"])>0);
     if($loginform){
       $_SESSION['login'] = 1;
       echo("<script>location.href = '/info/';</script>");
     }
   }
}

info.php

if(!isset($_SESSION['login']){
    echo("<script>location.href = '/login/';</script>");
}
  • 写回答

3条回答 默认 最新

  • doudou130216 2016-08-03 07:14
    关注

    Start session at login.php page if login success and set a session variable just befor the header in login.php.

    login.php
    
    <?php
    session_start();// at top of page
    ..... after login means all your query running
    if(querysuccess){
    $_SESSION['loggedIn'] = 1;
    header('location:info.php');
    
    }
    
    
    info.php// here check if session variable not 1 then redirect again to login.php
    
    
    <?php
    session_start();
    if(!SESSION['loggedIn']){
    header('location:login.php');
    }
    
    else{
    
    // just do whatever you want
    }
    ?>
    

    updated answer

    start session at top of form page

    <?php
    session_start();// should be at top
    if(isset($_POST['submit'])){
        if((isset($_POST['username']) && $_POST['username'] != '') && (isset($_POST['email']) && $_POST['email'] != '')){
            $_SESSION["username"] = $_POST['username'];
            $_SESSION["email"] = $_POST['email'];
    
        $loginform = (strlen($_SESSION["username"])>0 && strlen($_SESSION["email"])>0);
         if($loginform){
           $_SESSION['login'] = 1;
           echo("<script>location.href = '/info/';</script>");
         }
       }
    }
    

    you forget to close isset in info.php. Also start session also here

    <?php 
    session_start();
    if(!isset($_SESSION['login'])){
        echo("<script>location.href = '/login/';</script>");
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?