重定向功能没有';不太好用——PHP


Redirect function doesn't work well - PHP

嗨,我有以下PHP代码:

 function redirect()
 {
     header("Location: index.php");
 }
 session_start();
 if(isset($_SESSION['userName'] ))
    redirect();

 if($_SERVER['REQUEST_METHOD'] == 'POST')
 {   //more code goes here...
   redirect();
  }

问题是函数redirect仅在以下条件下工作:

if($_SERVER['REQUEST_METHOD'] == 'POST')

为什么以及如何修复?

谢谢!

你能试试这个吗,

    session_start();
    function redirect()
    {
        header("Location: index.php");
    }
    if(isset($_SESSION['userName'])){
        redirect();
    }elseif($_SERVER['REQUEST_METHOD'] == 'POST'){   
     //more code goes here...
     redirect();
    }

否则会发生什么?有什么错误吗?发生了什么事?

我们需要更多信息!

这应该会有所帮助:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

它在该条件下工作,因为您在该条件中调用它。。。也许如果你使用一些标签,你可以看到为什么

看看

//your function
function redirect(){
    header("Location: index.php");
}
//here your function end
//this is not part of the function
session_start();
if(isset($_SESSION['userName'] ))
    redirect();
if($_SERVER['REQUEST_METHOD'] == 'POST') {   
    //more code goes here...
   redirect();
}