WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / PHP

HTTP-Anfrage und -Antwort

Trenne Methode und Eingabe der Anfrage von Status, Headern und Antwortkörper.

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

Syntax

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

Trenne Methode und Eingabe der Anfrage von Status, Headern und Antwortkörper. Status und Medientyp vor der Ausgabe wählen. Eine Route nur für GET kann andere Methoden mit 405 und Allow beantworten. Das CGI-Beispiel liest die Methode aus der Anfrageumgebung und gibt eine Antwort aus. Bei 405 muss der Ursprungsserver ein Allow-Feld mit den aktuell unterstützten Methoden der Zielressource erzeugen (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"}]

Beispiele

<?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)]);

Ergebnis

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

Quellen