Three Methods to Implement Page Redirection in PHP

This article explains three PHP techniques for page redirection—using the header() function, outputting a JavaScript location.href script, and inserting a META refresh tag—each with code examples and explanations of how they work and when to use them.

php Courses
php Courses
php Courses
Three Methods to Implement Page Redirection in PHP

Page redirection is needed when moving pages or adjusting a website to avoid losing traffic; it redirects requests to a new location.

Method 1: Header redirect

<?php
$url = "http://php.cn";
if (isset($url)) {
    header("Location:$url");
} else {
    echo "没有跳转的地址!";
}
?>

The script defines $url, checks its existence, and uses header() to send an HTTP Location header; otherwise it outputs a message.

Method 2: JavaScript redirect

<?php
$url = "http://php.cn";
if (isset($url)) {
    echo "<SCRIPT language='JavaScript'>location.href='$url'</SCRIPT>";
} else {
    echo "没有跳转的地址!";
}
?>

This method echoes a script tag that sets location.href to the target URL after confirming the URL exists.

Method 3: HTML meta refresh

<?php
$url = "http://php.cn";
if (!isset($url)) {
    exit("没有跳转的地址!");
}
?>
<HTML>
<head>
    <meta HTTP-EQUIV="REFRESH" CONTENT="3; URL='<?php echo $url; ?>' ">
</head>
<body>
</body>
</HTML>

The script checks $url and then uses a <meta http-equiv="refresh"> tag to refresh the page after 3 seconds to the new URL.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptPHP
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.