PHP redirection with code 307 changes method from POST to GET

后端 未结 2 686
没有蜡笔的小新
没有蜡笔的小新 2021-01-22 01:02

In my PHP software I have an self-update feature which sends a HTTP request with the POST method to a certain URL (to a PHP script). Now this URL has changed (I moved the script

相关标签:
2条回答
  • 2021-01-22 01:44

    The W3C HTTP/1.1 specification for 307 states:

    If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

    The point behind this is that it is unsafe for a server to tell a client to POST to a different URL as that may be a malicious attempt to get the client to send data somewhere the user did not intend, so POST redirections are not possible.

    0 讨论(0)
  • 2021-01-22 01:57

    It looks like file_get_contents does not repost the data, possibly for the reason highlighted by @daiscog.

    Curl however will repost to the redirected url:

    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, 'http://localhost/old/long/path/update.php');   
    curl_setopt($ch, CURLOPT_POST, true);    
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
    
    $serverResponse = curl_exec($ch);
    

    However it would make more sense to either handle this at the server level (eg an Apache url rewrite) or to simply include the new file in the old one:

    //old.php
    include('path/to/new.php');
    
    0 讨论(0)
提交回复
热议问题