- Определение типа запроса в PHP (GET, POST, PUT или DELETE)
- пример
- PHP: Detect if request type is POST or GET.
- Detecting request type in PHP (GET, POST, PUT or DELETE)
- Detect the request method in PHP
- Disallowing certain request types
- 405 Method Not Allowed
- 405 Method Not Allowed
- HTTP request types:
- Routing
- Handle all requests from a single PHP script
Определение типа запроса в PHP (GET, POST, PUT или DELETE)
Как я могу определить, какой тип запроса был использован (GET, POST, PUT или DELETE) в PHP?
пример
if ($_SERVER['REQUEST_METHOD'] === 'POST') < // The request is using the POST method >
Для получения дополнительной информации см. Документацию для переменной $ _SERVER .
REST в PHP можно сделать довольно просто. Создайте http://example.com/test.php (см. Ниже). Используйте это для вызовов REST, например http://example.com/test.php/testing/123/hello . Это работает с Apache и Lighttpd из коробки, и никаких правил перезаписи не требуется.
Обнаружение метода HTTP или так называемого метода REQUEST METHOD может быть выполнено с использованием следующего фрагмента кода.
$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 >
Вы также можете сделать это, используя switch если вы предпочитаете это над оператором if-else .
Если в форме html требуется метод, отличный от GET или POST , это часто решается с помощью скрытого поля в форме.
Для получения дополнительной информации о методах HTTP я хотел бы обратиться к следующему вопросу StackOverflow:
HTTP-протокол PUT и DELETE и их использование в PHP
Поскольку это относится к REST, просто получить метод запроса с сервера недостаточно. Вам также необходимо получить параметры маршрута RESTful. Причина разделения параметров RESTful и GET / POST / PUT заключается в том, что для идентификации ресурса должен быть свой собственный уникальный URL.
Вот один из способов реализации маршрутов RESTful в PHP с использованием Slim:
$app = new \Slim\Slim(); $app->get('/hello/:name', function ($name) < echo "Hello, $name"; >); $app->run();
И настройте сервер соответственно.
Вот еще один пример использования 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');
Очень просто использовать $ _SERVER [‘REQUEST_METHOD’];
Вы можете использовать функцию getenv и не должны работать с переменной $_SERVER :
$request = new \Zend\Http\PhpEnvironment\Request(); $httpMethod = $request->getMethod();
Таким образом, вы также можете достичь и в zend framework 2. Благодарю.
Мы также можем использовать input_filter для обнаружения метода запроса, а также обеспечения безопасности посредством входной санитарии.
$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
Когда запрос был запрошен, он будет иметь array . Поэтому просто проверьте с count() .
$m=['GET'=>$_GET,'POST'=>$_POST]; foreach($m as$k=>$v)
Вы можете получить любые данные строки запроса, например www.example.com?id=2&name=r
Вы должны получить данные с помощью $_GET[‘id’] или $_REQUEST[‘id’] .
Почтовые данные означают, что форма вы должны использовать $_POST или $_REQUEST .
PHP: Detect if request type is POST or GET.
In this guide, we will show you how to detect the HTTP request type using PHP.
For example, is the user sending a GET or POST request? Or are they using another HTTP method such as PUT and DELETE?
Take a look at the following example:
//Get the request method from the $_SERVER $requestType = $_SERVER['REQUEST_METHOD']; //Print the request method out on to the page. echo $requestType;
As you can see, PHP will store the HTTP request method in the $_SERVER array.
Therefore, you can easily access it by referencing the “REQUEST_METHOD” element.
Knowing the request type is useful for a number of reasons:
- You can restrict certain URLs to specific request types. If they fail to use the correct method, then you can respond with a 405 code. For example, if you have a page that receives form data, then you might want to restrict that script to POST requests or PUT requests.
- It allows you to implement REST, which is a popular software architectural style that allows you to organize interactions between independent systems.
Take a look at the following code, in which we handle different methods:
//Get the request method. $requestType = $_SERVER['REQUEST_METHOD']; //Switch statement switch ($requestType) < case 'POST': handle_post_request(); break; case 'GET': handle_get_request(); break; case 'DELETE': handle_delete_request(); break; default: //request type that isn't being handled. break; >
As you can see, PHP and its $_SERVER array make it pretty easy for us.
Detecting request type in PHP (GET, POST, PUT or DELETE)
In PHP, you can use the $_SERVER[‘REQUEST_METHOD’] superglobal to detect the request type. This superglobal will contain the request method used by the client, which can be one of GET , POST , PUT , or DELETE .
Here’s an example of how you can use this superglobal to detect the request type:
if ($_SERVER['REQUEST_METHOD'] === 'GET') < // handle GET request > elseif ($_SERVER['REQUEST_METHOD'] === 'POST') < // handle POST request > elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') < // handle PUT request > elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') < // handle DELETE request >
You can also use a switch statement to handle the different request types:
switch ($_SERVER['REQUEST_METHOD']) < case 'GET': // handle GET request break; case 'POST': // handle POST request break; case 'PUT': // handle PUT request break; case 'DELETE': // handle DELETE request break; >
Detect the request method in PHP
Detecting the request method used to fetch a web page with PHP, routing, HTTP responses, and more.
PHP makes it easy to detect the request method via the $_SERVER[‘REQUEST_METHOD’] superglobal, which is useful for URL mapping (routing) purposes; to do so, you just need to compare values using a if statement, so, to check if the request is a POST:
if ($_SERVER['REQUEST_METHOD'] === 'POST') echo 'Dealing with a POST request.'; exit(); >
And, if you want to check if the request is a GET request:
if ($_SERVER['REQUEST_METHOD'] === 'GET') echo 'Dealing with a GET request.'; exit(); >
Disallowing certain request types
You can accept or deny the request depending on whether the used request method is allowed for the requested path.
If you deny a request, then it is important to send an appropriate response code in order to adhere to the HTTP protocol; for example, an accurate status code to send if a used request method is not allowed would the 405 Method Not Allowed. E.g:
http_response_code(405); header('Allow: GET, HEAD'); echo '405 Method Not Allowed
'; exit();
You can keep a list of allowed methods in an Associative Array that you can check the $_SERVER[‘REQUEST_METHOD’] against. E.g:
$allowed_methods = ['GET', 'HEAD']; if (!in_array($_SERVER['REQUEST_METHOD'], $allowed_methods)) http_response_code(405); header('Allow: '. implode(", ", $allowed_methods)); echo '405 Method Not Allowed
'; exit(); >
The same technique, with Associative Arrays, can also be used to compare the requested path with a list of mapped URLs, but you probably also want to match patterns, which is slightly more complex.
HTTP request types:
Routing
If you are trying to create a URL mapper (router), then it will often make more sense to make a single script or class that handles all HTTP requests for your application; in order for that to work, you will first need to point all requests to the relevant script (E.g. index.php), and then parse the path from within your application.
The path is contained in the $_SERVER[‘REQUEST_URI’] variable, which also contains the query string, and therefor it needs to be parsed before you can use it. E.g:
$parsed_url = parse_url($_SERVER['REQUEST_URI']); if ($parsed_url['path'] === '/my/unique-path') if ($_SERVER['REQUEST_METHOD'] === 'POST') echo 'Dealing with a POST request.'; exit(); > >
Note. the query string is the part after the question mark in the URL. E.g: /some-user?user_name=Henrik&category=employees.
Ideally, this should be created in a much more dynamic way, so that the script automatically loads the feature that corresponds with the path and/or used URL parameters included in the request.
Handle all requests from a single PHP script
It is possible to direct all HTTP requests to go through a single PHP script, how to do this will depend on the web server software you are using; if you are using the Apache HTTP server, then you just need to add the following to your VHOST or .htaccess configuration:
RewriteEngine on RewriteCond % !-f RewriteCond % !-d RewriteRule ^.*$ index.php [QSA,L]
This will make all requests go through your index.php file unless a physical file exists in the sites web folder; if you also want to serve physical files through PHP, then you will need to use a slightly different configuration:
RewriteEngine on RewriteCond % -f [OR] RewriteCond % !-f RewriteRule ^.*$ index.php [QSA,L]
Note. You can use Beamtic’s file handler class to serve static files through PHP, more info is found here.