Cody Raspien Cody Raspien - 1 month ago 7
PHP Question

php - header location - wrong url opening

Script:

https://example.com/docs/index.php


In index.php, I have the following code:

header('Location: page2.php');


However, instead of opening page2.php, the following URL is opened:

https://example.com/docs/index.php/page2.php


If I put an absolute URL, everything works.


  1. Why is this happening?

  2. Is there any workaround so that I don't have to use an absolute URL?


Answer
<?php
/* Redirect to a different page in the current directory that was requested */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>

http://php.net/manual/en/function.header.php