How to make a redirect in PHP?

2018-12-30 22:07发布

Is it possible to redirect a user to a different page through the use of PHP?

Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Possible?

This could even protect my pages from unauthorized users.

标签: php redirect
28条回答
与君花间醉酒
2楼-- · 2018-12-30 22:50

header( 'Location: http://www.yoursite.com/new_page.html' );

查看更多
ら面具成の殇う
3楼-- · 2018-12-30 22:51

You can use session variables to control access to pages and authorize valid users as well.

<?php

session_start();

if ( !isset( $_SESSION["valid_user"]) )
{
    header("location:../");
   die();
}

// Page goes here
?>

http://php.net/manual/en/reserved.variables.session.php.

Recently, I got cyber attacks and decided, i needed to know the users trying t access Admin Panel or reserved part of the web application.

so, I added a log access IP and user sessions in a text file because I don't want to bother my database.

查看更多
旧人旧事旧时光
4楼-- · 2018-12-30 22:51

You can attempt to use the php header function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.

ob_start();
header("Location: ".$website);
ob_end_flush();
查看更多
浅入江南
5楼-- · 2018-12-30 22:52

Use header() function to send HTTP Location header:

header('Location: '.$newURL);

Contrary to some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution.

example.php:

<?php 
header('Location: static.html');
$fh = fopen('/tmp/track.txt','a');
fwrite($fh, $_SERVER['REMOTE_ADDR'].' '.date('c')."\n");
fclose($fh);
?>

Result or 3 executions:

bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00

Resuming — obligatory die()/exit() is some urban legend, that has nothing to do with actual PHP. Has nothing to do with client "respecting" Location: header. Sending header does not stop PHP execution, regardless of client used.

查看更多
登录 后发表回答