简体   繁体   English

在 php 中运行两个标头?

[英]Run two headers in php?

Is there a solution for executing two headers in php?是否有在 php 中执行两个标头的解决方案? The first header is to execute a php script and the second header is to reload the current php page.第一个 header 是执行 php 脚本,第二个 header 是重新加载当前的 ZE1BFD4ZZACEE366 页面。 If not, is there another way?如果没有,还有其他方法吗? With a button press, the submitGen function is called.按下按钮,调用submitGen function。 Is there a delay that can be added between two header functions so they can run from same script?是否可以在两个 header 函数之间添加延迟,以便它们可以从同一个脚本运行?

<?php
if (isset($_POST['submitGen'])) {
    header('Location:Page2.php');
    header('Refresh: 0');
}
?>

...
<tr>
    <form action="" method="post" role="form">
        <td>
            <input type="submit" name="submitGen" class="btn btn-primary" value = "Gen">
        </td>
    </form>
</tr>

Not possible, the header function sends an HTTP response.不可能,header function 发送 HTTP 响应。 You can only send 1 response per 1 request, that's how the HTTP protocol works (for the most part).每个请求只能发送 1 个响应,这就是 HTTP 协议的工作原理(大部分情况下)。 A client requests 1 asset/document/something and the server provides 1 response for that call.客户端请求 1 个资产/文档/某物,服务器为该调用提供 1 个响应。

If you want to refresh the current page after the client triggers an event, consider using Javascript to perform the current page's refresh with something like location.reload() on the form submission event.如果您想在客户端触发事件后刷新当前页面,请考虑使用 Javascript 在表单提交事件上使用location.reload()之类的方法执行当前页面的刷新。

I would recommend a two-step workaround.我会推荐一个两步的解决方法。

The idea is to send the redirect during the first request, and then set a session variable, so the refresh is sent during the second request.思路是在第一次请求时发送redirect,然后设置一个session变量,所以在第二次请求时发送刷新。

<?php
session_start();
if(isset($_POST['submitGen']))
    {
        $_SESSION['do'] = 'refresh';
        header('Location:Page2.php');
    }
if($_SESSION['do'] == 'refresh')
    {
        unset($_SESSION['do']);
        header("Refresh: 0");
    }

?>

It's not really clear what Page2.php does, but consider:目前还不清楚 Page2.php 做了什么,但请考虑:

1) Page2.php is server-code only - nothing to output to client: 1) Page2.php 仅是服务器代码 - output 对客户端没有任何影响:

<?php
if(isset($_POST['submitGen']))
    {
        //header('Location:Page2.php');
        //header("Refresh: 0");
        require 'Page2.php';
    }

?>

...

2) Page2.php has output that needs to be sent to client (cookies, javascript etc) 2) Page2.php 有 output 需要发送到客户端 (cookies, javascript 等)

<?php
if(isset($_POST['submitGen']))
    {
        header('Location:Page2.php?autoreturn=true');
        //Catch the autoreturn argument in Page2.php
        //die die die always after a header location..
        die();
    }

?>

When the form is submitted, run a Javascript function that fetches Page2.php and reloads when it's done.提交表单后,运行 Javascript function 获取Page2.php并在完成后重新加载。

Here's a proof-of-concept that I just tested on my server and works exactly as you asked for.这是我刚刚在我的服务器上测试过的概念验证,并且完全按照您的要求工作。 When the user clicks the submit button, Javascript loads Page2.php in the background and then reloads Page1.php :当用户点击提交按钮时, Page2.php在后台加载 Page2.php 然后重新加载Page1.php

Page1.php:第1页.php:

<script>
function do_submit() {
        fetch('Page2.php')
        .then(function() {
                console.log('Got Page2.php! Reloading...');
                location.reload()
        })
        .catch(function() {
                console.log('Page2.php failed')
        });

        return false;
}
</script>

<table>
<tr>
<form action="" method="post" role="form" onsubmit="return do_submit()">
<td>
    <input type="submit" name="submitGen" class="btn btn-primary" value = "Gen">
</td>
</form>
</tr>
</table>

Page2.php:第2页.php:

$fp = fopen( 'log.txt', 'a' );
if ( $fp ) {
        fwrite( $fp, date("Y-m-d h:i:si\n") );
        fclose($fp);
        echo "Done!\n";
} else {
        echo "Error opening file\n";
}

Note that log.txt must be writable by the web server, otherwise the script won't be able to open it for writing.注意log.txt必须是 web 服务器可写的,否则脚本将无法打开它进行写入。

I tested this on my web server and it does exactly what you asked for: it executes Page2.php (as evidenced by the date/time written to log.txt , and then reloads Page1.php in the browser.我在我的 web 服务器上对此进行了测试,它完全符合您的要求:它执行Page2.php (由写入log.txt的日期/时间证明,然后在浏览器中重新加载Page1.php

Probably no way to send two headers as mentioned above, but.可能没有办法像上面提到的那样发送两个标头,但是。

If you need to reload after Page2.php shown and there is no Javascript/user input on Page2.php, you can just add如果您需要在显示 Page2.php 之后重新加载,并且 Page2.php 上没有 Javascript/用户输入,您可以添加

echo "<script>location.reload()</script>";

at the end of the Page2.php - it's a js code which will reload the page when reached.Page2.php的末尾 - 这是一个 js 代码,它会在到达时重新加载页面。 Works even in IE, but needs JS to be enabled.即使在 IE 中也可以使用,但需要启用 JS。

Have the form load its contents into an <iframe> .让表单将其内容加载到<iframe>中。 Use JS to detect when the <iframe> has loaded , and then reload the main page:使用 JS 检测<iframe>何时加载,然后重新加载主页面:

<form action="" method="post" role="form" onsubmit="return doIt()">
  <input type="submit" name="submitGen" class="btn btn-primary" value = "Gen">
</form>

<iframe id="dest" src=""></iframe>

The script to handle form submit:处理表单提交的脚本:

function doId() {
  var iframe = document.getElementById('dest')
  iframe.addEventListener('load', function() {
    location.reload(); // reload current page
  })
  iframe.src = 'Page2.php'
  return false; // Prevent form from submitting
}

There's one way you can send that you can do two task in a single header as有一种方法可以发送,您可以在单个 header 中执行两项任务

header("Refresh:0;url=Page2.php");

Here what happens is the page that you are currently on gets refreshed first and then the second part of the header is been done which redirects you to the another webpage as mentioned.这里发生的情况是您当前所在的页面首先被刷新,然后 header 的第二部分完成,它将您重定向到提到的另一个网页。

Note : It is not a good idea to send multiple header() to the webpage because if they are are of the same type only the last mentioned header will be executed.注意:向网页发送多个header()不是一个好主意,因为如果它们属于同一类型,则只会执行最后提到的header

This IS the correct way to set multiple headers for 1 request:为 1 个请求设置多个标头的正确方法:

<?php
    if(isset($_GET['submit'])) {
        header("Location:Page2.php");
        header("Refresh:0");
    }
?>           

Note: In this sample we are redirecting to Page2.php due to that the Refresh:0 is useless!注意:在这个示例中,我们重定向到Page2.php因为Refresh:0无用的!

Saying useless does not mean that Page1.php will not output the header: Refresh:0 .说没用并不意味着Page1.php不会 output header: Refresh:0

NEVER USE: Location + Refresh for same request unless you know what you are doing.从不使用: Location + Refresh相同的请求,除非您知道自己在做什么。


Page1 will output both headers but you will not notice any difference from a regular web browser. Page1 将 output 两个标题,但您不会注意到与常规 web 浏览器有任何区别。

If you debug in Chrome you will see this code sets both Headers for Page1:如果您在 Chrome 中进行调试,您将看到此代码为 Page1 设置了两个标题: 在此处输入图像描述


Is there a solution for executing two headers in php?是否有在 php 中执行两个标头的解决方案?

Yes, as shown below you can set as many header as you like:是的,如下所示,您可以根据需要设置任意数量的 header:

<?php
    if(isset($_GET['submit'])) {

        if(isset($_GET['count'])) {
            if($_GET['count'] === '5') {
                header("Location:Page2.php");
            } else {
                sleep(1); // HERE Instead of SLEEP run your magic code!
                $count = $_GET['count'] + 1;
                header("Location:Page1.php?submit=1&count=$count");
            }
        } else {
            header("Location:Page1.php?submit=1&count=1");
        }
    }

    header("Connection:Close");
    header("Content-Type:Unknown Cyborg Coding");
    header("Keep-Alive:timeout=60, max=300");
    header("X-Powered-By:Cyborg-Powered MAGIC Servers");
    header("Language:Chineeeeese");
    header("Bots:Are my Friends!");
    header("Hacks:Are COOL!");
    header("Knowledge:Is GOOD!");
    header("StackOverflow:Is GOOD");
    header("Refresh:5"); // This header will be SET but will not make any difference since we use Location Redirect!
    // Refresh Header AND Location Header SHOULD NOT be set for same request unless you KNOW what you are doing. 

    echo "This lines will never been seen UNLESS you use cURL or other approch to DISABLE FOLLOW-REDIRECTS!<br/>\n";
    echo "Enjoy Coding!";
?>

Again, Header Refresh here will not make any difference.同样,Header 在这里Refresh不会有任何区别。 But after 5 Reloads of Page1 it will redirect to Page2!但是在第 1 页重新加载 5 次后,它将重定向到第 2 页!

See this headers and requests:请参阅此标头和请求:

在此处输入图像描述


The first header is to execute a php script and the second header is to reload the current php page.第一个 header 是执行 php 脚本,第二个 header 是重新加载当前的 ZE1BFD4ZZACEE366 页面。

For that you dont need to set 2 header, but if you want to reload Page1 multiple times till you get some results from other script, and thereafter go to Page2 when results are success from script then just change the if conditions in code above.为此,您不需要设置 2 header,但是如果您想多次重新加载 Page1 直到您从其他脚本获得一些结果,然后当脚本的结果成功时将 go 设置为 Page2,那么只需更改上面代码中的 if 条件。

Code Sample:代码示例:

<?php
    if(isset($_GET['submit'])) {
        $results = shell_exec("curl -k 'https://api4.eu'"); // here set the script you want.
        if (strpos($results, 'Realtime API Exchange') !== false) { header("Location:Page2.php"); }
        else { sleep(3); header("Location:Page1.php?submit=1"); }
    }
?>

Or better avoid sleep and use:或者更好地避免sleep和使用:

<?php
    if(isset($_GET['submit'])) {
        $results = shell_exec("curl -k 'https://api4.eu'"); // here set the script you want.
        if (strpos($results, 'Realtime API Exchange') !== false) { header("Location:Page2.php"); }
        else { header("Refresh:3"); }
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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