简体   繁体   中英

php page to redirect to another

I have a php page which should be included in otherpage but no directly. Lets assume it as 1.php and the other page as 2.php

1.php

<?php
   if($_SERVER['REQUEST_URI'] == "/1.php"){
       header("Location:2.php");
   }
   else
   {
       //some code here
   }
?>

2.php

<?php
   include("1.php");
?>

this worked well on localhost/1.php and have been redirected to localhost/2.php but this had made a problem with localhost/1.php?somegetmethod=data I found that anyone can access this page by typing ?something=something at the end of 1.php url. How to change the code which can redirect all url which starts with localhost/1.php

you could check if a substring is at a given position like this

if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0) {

this checks if the REQUEST_URI starts with /1.php (= is at position 0)

试试吧:

if($_SERVER['SCRIPT_NAME'] == "/1.php")

使用$_SERVER['PHP_SELF']代替$_SERVER['REQUEST_URI']

$_SERVER['REQUEST_URI'] contains URI of requeted page, in yoour case it's 1.php?somegetmethod=data .

Change code like:

if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0){
    header("Location:2.php");
}else{
    //some code here
}

What you often see, for instance in MediaWiki, WordPress and many other such applications, is this:

1.php

if ( !defined( 'YOURAPPCONSTANT' ) ) {
  // You could choose to redirect here, but an exit would make just as much  
  // sense. Someone has deliberately chosen an incorrect url.
  echo "Cannot directly call this file.";
  exit( 1 );
}

2.php

define('YOURAPPCONSTANT', 'It is defined');
include('1.php');

That way, 2.php is the entry of your application, regardless of the url used to reach it. I think this is a much safer and more flexible way, and it is used so often for a reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM