Come posso rilevare quale tipo di richiesta è stata utilizzata (GET, POST, PUT o DELETE) in PHP?
PATCH?
$_SERVER['REQUEST_METHOD'] === 'PATCH'
Come posso rilevare quale tipo di richiesta è stata utilizzata (GET, POST, PUT o DELETE) in PHP?
PATCH?
$_SERVER['REQUEST_METHOD'] === 'PATCH'
Risposte:
Usando
$_SERVER['REQUEST_METHOD']
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
Per maggiori dettagli, consultare la documentazione per la variabile $ _SERVER .
$_GET['var'].
$_POSTe $_GETsfortunatamente sono chiamati in qualche modo. $_GETcontiene variabili dal componente di query dell'URL, indipendentemente dal metodo HTTP. $_POSTconterrà campi modulo se la richiesta è stata inviata come application/x-www-form-urlencoded.
REST in PHP può essere fatto abbastanza semplice. Crea http://example.com/test.php (descritto di seguito). Utilizzalo per le chiamate REST, ad esempio http://example.com/test.php/testing/123/hello . Funziona con Apache e Lighttpd immediatamente e non sono necessarie regole di riscrittura.
<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
switch ($method) {
case 'PUT':
do_something_with_put($request);
break;
case 'POST':
do_something_with_post($request);
break;
case 'GET':
do_something_with_get($request);
break;
default:
handle_error($request);
break;
}
@davanti $_SERVER['PATH_INFO']?
PHP Notice: Undefined index: PATH_INFOnel caso in cui PATH_INFO non sia presente $_SERVER. Sto aggiungendo subito questo alla mia borsa di trucchi! È un modo di dire "So che potrebbe non esserci una voce chiamata così in questo array, e sono pronto per quello, quindi stai zitto e fai quello che ti dico". :) Grazie ragazzi, sia per aver pubblicato questa risposta sia per avermi rivolto la mia attenzione a quel particolare personaggio.
<?php $request = explode("/", substr(@$_SERVER['PATH_INFO'], 1)); $rest = 'rest_'.strtolower($_SERVER['REQUEST_METHOD']); if (function_exists($rest)) call_user_func($rest, $request); ?>
Il rilevamento del metodo HTTP o cosiddetto REQUEST METHODpuò essere effettuato utilizzando il seguente frammento di codice.
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'POST'){
// Method is POST
} elseif ($method == 'GET'){
// Method is GET
} elseif ($method == 'PUT'){
// Method is PUT
} elseif ($method == 'DELETE'){
// Method is DELETE
} else {
// Method unknown
}
Puoi anche farlo usando a switchse preferisci questo rispetto if-elseall'istruzione.
Se un metodo diverso da GETo POSTè richiesto in un modulo HTML, questo viene spesso risolto utilizzando un campo nascosto nel modulo.
<!-- DELETE method -->
<form action='' method='POST'>
<input type="hidden" name'_METHOD' value="DELETE">
</form>
<!-- PUT method -->
<form action='' method='POST'>
<input type="hidden" name'_METHOD' value="PUT">
</form>
Per ulteriori informazioni sui metodi HTTP, vorrei fare riferimento alla seguente domanda StackOverflow:
Possiamo anche utilizzare input_filter per rilevare il metodo di richiesta e allo stesso tempo fornire sicurezza tramite servizi igienico-sanitari di input.
$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
Poiché si tratta di REST, non è sufficiente ottenere il metodo di richiesta dal server. È inoltre necessario ricevere i parametri di percorso RESTful. La ragione per separare i parametri RESTful e i parametri GET / POST / PUT è che una risorsa deve avere un proprio URL univoco per l'identificazione.
Ecco un modo per implementare percorsi RESTful in PHP usando Slim:
https://github.com/codeguy/Slim
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
E configurare il server di conseguenza.
Ecco un altro esempio usando AltoRouter:
https://github.com/dannyvankooten/AltoRouter
$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in
// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
Puoi usare la getenvfunzione e non devi lavorare con una $_SERVERvariabile:
getenv('REQUEST_METHOD');
Ulteriori informazioni:
È molto semplice, basta usare $ _SERVER ['REQUEST_METHOD'];
Esempio:
<?php
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
//Here Handle GET Request
break;
case 'POST':
//Here Handle POST Request
break;
case 'DELETE':
//Here Handle DELETE Request
break;
case 'PUT':
//Here Handle PUT Request
break;
}
?>
$_SERVER['REQUEST_METHOD'], anche su misura. Ricorda che il metodo è solo una stringa nell'intestazione della richiesta e che è nostro compito verificarne la correttezza.
$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();
In questo modo puoi anche ottenere in zend framework 2. Grazie.
Nel core php puoi fare così:
<?php
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
//Here Handle GET Request
echo 'You are using '.$method.' Method';
break;
case 'POST':
//Here Handle POST Request
echo 'You are using '.$method.' Method';
break;
case 'PUT':
//Here Handle PUT Request
echo 'You are using '.$method.' Method';
break;
case 'PATCH':
//Here Handle PATCH Request
echo 'You are using '.$method.' Method';
break;
case 'DELETE':
//Here Handle DELETE Request
echo 'You are using '.$method.' Method';
break;
case 'COPY':
//Here Handle COPY Request
echo 'You are using '.$method.' Method';
break;
case 'OPTIONS':
//Here Handle OPTIONS Request
echo 'You are using '.$method.' Method';
break;
case 'LINK':
//Here Handle LINK Request
echo 'You are using '.$method.' Method';
break;
case 'UNLINK':
//Here Handle UNLINK Request
echo 'You are using '.$method.' Method';
break;
case 'PURGE':
//Here Handle PURGE Request
echo 'You are using '.$method.' Method';
break;
case 'LOCK':
//Here Handle LOCK Request
echo 'You are using '.$method.' Method';
break;
case 'UNLOCK':
//Here Handle UNLOCK Request
echo 'You are using '.$method.' Method';
break;
case 'PROPFIND':
//Here Handle PROPFIND Request
echo 'You are using '.$method.' Method';
break;
case 'VIEW':
//Here Handle VIEW Request
echo 'You are using '.$method.' Method';
break;
Default:
echo 'You are using '.$method.' Method';
break;
}
?>
È utile notare inoltre che PHP popolerà tutti i $_GETparametri anche quando si invia una richiesta corretta di altro tipo.
Metodi di risposte di cui sopra sono del tutto corrette, se si vuole additionaly controllo per GETi parametri durante la manipolazione POST, DELETE, PUT, ecc richiesta, è necessario controllare la dimensione della $_GETmatrice.
Quando è stato richiesto un metodo, avrà un array. Quindi controlla semplicemente con count().
$m=['GET'=>$_GET,'POST'=>$_POST];
foreach($m as$k=>$v){
echo count($v)?
$k.' was requested.':null;
}
Ho usato questo codice. Dovrebbe funzionare.
function get_request_method() {
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
if($request_method != 'get' && $request_method != 'post') {
return $request_method;
}
if($request_method == 'post' && isset($_POST['_method'])) {
return strtolower($_POST['_method']);
}
return $request_method;
}
Questo codice sopra funzionerà REST callse funzionerà anche conhtml form
<form method="post">
<input name="_method" type="hidden" value="delete" />
<input type="submit" value="Submit">
</form>
È possibile ottenere qualsiasi dato della stringa di query, ad es www.example.com?id=2&name=r
È necessario ottenere i dati utilizzando $_GET['id']o $_REQUEST['id'].
Pubblica dati significa come il modulo <form action='' method='POST'>che devi usare $_POSTo $_REQUEST.