Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

HTTP request and response models

Separate request method and input from response status, headers and body.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

http_response_code($status); header($field); echo $body;

Separate request method and input from response status, headers and body. Decide status and media type before emitting bytes. A route that accepts only GET can respond to another method with 405 and an Allow header. The CGI example obtains the method from the request environment and emits a real response. For a 405 response the origin server must generate an Allow field listing the methods currently supported by the target resource (RFC 9110 §15.5.6).

if(PHP_SAPI==="cgi-fcgi"){if($_SERVER["REQUEST_METHOD"]!=="GET"){http_response_code(405); header("Allow: GET");}header("Content-Type: application/json");echo json_encode(["method"=>$_SERVER["REQUEST_METHOD"]]);exit;}
$env=["REDIRECT_STATUS"=>"1","REQUEST_METHOD"=>"POST","SCRIPT_FILENAME"=>__FILE__];$p=proc_open([PHP_BINDIR."/php-cgi"],[1=>["pipe","w"]],$pipes,null,$env);$response=stream_get_contents($pipes[1]);fclose($pipes[1]);proc_close($p);[$headers,$body]=preg_split("/\\r?\\n\\r?\\n/",$response,2);echo json_encode([str_contains($headers,"405"),str_contains($headers,"Allow: GET"),json_decode($body,true)]);
[true,true,{"method":"POST"}]

Examples

<?php
if(PHP_SAPI==="cgi-fcgi"){if($_SERVER["REQUEST_METHOD"]!=="GET"){http_response_code(405); header("Allow: GET");}header("Content-Type: application/json");echo json_encode(["method"=>$_SERVER["REQUEST_METHOD"]]);exit;}
$env=["REDIRECT_STATUS"=>"1","REQUEST_METHOD"=>"POST","SCRIPT_FILENAME"=>__FILE__];$p=proc_open([PHP_BINDIR."/php-cgi"],[1=>["pipe","w"]],$pipes,null,$env);$response=stream_get_contents($pipes[1]);fclose($pipes[1]);proc_close($p);[$headers,$body]=preg_split("/\\r?\\n\\r?\\n/",$response,2);echo json_encode([str_contains($headers,"405"),str_contains($headers,"Allow: GET"),json_decode($body,true)]);

Result

[true,true,{"method":"POST"}]

Sources