Nave Tseva
Nave Tseva

Reputation: 878

Redirect function doesn't work well - PHP

Hi I have the following PHP code:

 function redirect()
 {
     header("Location: index.php");
 }
 session_start();

 if(isset($_SESSION['userName'] ))
    redirect();


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

The problem is that the function redirect works only in the following condition:

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

Why and how can I fix it?

Thanks!

Upvotes: 0

Views: 81

Answers (3)

Javier Neyra
Javier Neyra

Reputation: 1239

it works in that condition becuase you are calling it in that condition... maybe if you use some tabs you can see why

take a look

//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();
}

Upvotes: 0

Haudegen
Haudegen

Reputation: 498

What happens otherwise? Is there any error? Something, that happens there?

We need more Information!

This should help:

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

Upvotes: 0

Krish R
Krish R

Reputation: 22741

Can you try this,

    session_start();
    function redirect()
    {
        header("Location: index.php");
    }

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

Upvotes: 4

Related Questions