Rilevamento tipo di richiesta in PHP (GET, POST, PUT o DELETE)
Domanda
Come posso rilevare che tipo di richiesta è stato utilizzato (GET, POST, PUT o DELETE) in PHP?
Soluzione
Utilizzando
$_SERVER['REQUEST_METHOD']
Esempio
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
Per maggiori informazioni si prega di consultare la documentazione per la variabile $ _SERVER .
Altri suggerimenti
REST in PHP può essere fatto piuttosto semplice. Creare http://example.com/test.php (descritta di seguito). Usare questo per le chiamate REST, per esempio http://example.com/test.php/testing/123/hello . Questo funziona con Apache e Lighttpd fuori dalla scatola, e non sono necessari 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;
}
Rilevare il metodo HTTP o cosiddetta REQUEST METHOD
può essere fatto 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
}
Si potrebbe anche farlo utilizzando un switch
se si preferisce questo il if-else
comunicato.
Se un metodo diverso GET
o POST
è richiesto in forma html, questo è spesso risolto utilizzando un campo nascosto nella forma.
<!-- 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:
Dal momento che si tratta di REST, solo per il metodo di richiesta dal server non è sufficiente. È inoltre necessario per ricevere parametri del percorso RESTful. La ragione per separare i parametri riposante e ottenere i parametri / POST / PUT è che una risorsa ha bisogno di avere il proprio URL univoco per l'identificazione.
Ecco un modo di attuare percorsi RESTful in PHP utilizzando 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 di utilizzo 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');
È possibile utilizzare la funzione getenv
e non c'è bisogno di lavorare con un $_SERVER
variabili:
getenv('REQUEST_METHOD');
Più informazioni:
Si può anche utilizzare il input_filter per rilevare il metodo di richiesta fornendo allo stesso tempo la sicurezza attraverso servizi igienico-sanitari di ingresso.
$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
E '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;
}
?>
$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();
In questo modo è anche possibile ottenere in Zend Framework 2 anche. Grazie.
Nel core di PHP si può fare in questo modo:
<?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;
}
?>
Quando è stato richiesto un metodo, avrà un array
. Così semplicemente verificare 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 qui sopra funziona con REST calls
e funziona anche con html form
<form method="post">
<input name="_method" type="hidden" value="delete" />
<input type="submit" value="Submit">
</form>
È possibile ottenere qualsiasi cioè dati query string www.example.com?id=2&name=r
È necessario ottenere dati utilizzando $_GET['id']
o $_REQUEST['id']
.
Dati post mezzi come forma <form action='' method='POST'>
è necessario utilizzare $_POST
o $_REQUEST
.