PHP 标头函数工作


php header function working

我编写了以下代码来刷新页面并打印随机数,但我不明白它的逻辑。

<!DOCTYPE html>
<html>
<head>
    <title>Random Refresh</title>
</head>
<body>
<h1>Random refresh</h1>
<p>page is refreshed every 5 seconds </p>
<br> </br>
<p>Radom number between 10 to 100 is : 
<?php  
echo(rand(10,100));
header("Refresh: 5; url=randomRefresh.php");  
?>
</p>

</body>
</html>

据我所知,php是一种服务器端语言,因此php块中的代码应该执行一次。

那么标题功能如何刷新/重定向页面?

php文件的输出HTML页面是否使用隐式Ajax请求?

引擎盖下发生了什么?

"Refresh: 5; url=randomRefresh.php"函数在浏览器端执行。php headers()函数在服务器端执行

PHP 中的header()仅设置一个额外的或现有的标头,该标头在页面加载时发送到客户端的浏览器,但Refresh: 5; url=randomRefresh.php由客户端的浏览器解释为在 5 秒后刷新页面。标头的其他示例类似于可以是 200、301、302、404 的status

它在页面加载时执行一次,但有一个代码作为

header("Refresh: 5; url=randomRefresh.php"); 

它在 5 秒后重新加载页面,然后再次在服务器端执行该 PHP 块。

您可以使用<meta http-equiv="refresh" content="5; url=randomRefresh.php" />

header("Refresh: 5; url=randomRefresh.php"); 

如果在调用之前页面中打印了任何内容,则会通过错误。

因此,如果您的页面名称是refresh_page_every_5_second.php那么您的代码将如下所示

<!DOCTYPE html>
<html>
<head>
    <title>Random Refresh</title>
    <meta http-equiv="refresh" content="5; url=refresh_page_every_5_second.php" />
</head>
<body>
<h1>Random refresh</h1>
<p>page is refreshed every 2 seconds </p>
<br> </br>
<p>Radom number between 10 to 100 is : 
<?php  
echo(rand(10,100));
//("Refresh: 5; url=randomRefresh.php");  
?>
</p>
</body>
</html>