Backend Development 3 min read

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>
    &lt;meta HTTP-EQUIV="REFRESH" CONTENT="3; URL='&lt;?php echo $url; ?&gt;' "&gt;
</head>
<body>
</body>
&lt;/HTML&gt;

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

BackendJavaScriptPHPheaderMeta RefreshPage Redirection
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

login 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.