Php get http method name

Определение типа запроса в 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

Читайте также:  Анимация появления блока css при наведении

Вы должны получить данные с помощью $_GET[‘id’] или $_REQUEST[‘id’] .

Почтовые данные означают, что форма вы должны использовать $_POST или $_REQUEST .

Источник

Detect the request method in PHP

Detecting the request method used to fetch a web page with PHP, routing, HTTP responses, and more.

d

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.

Источник

Определение типа запроса в PHP (GET, POST, PUT или DELETE)

Как я могу определить, какой тип запроса использовался (GET, POST, PUT или DELETE) в PHP?

Ответ 1

Пример:

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’)

// Запрос использует метод POST

>

Ответ 2

REST в PHP можно использовать довольно просто. Создайте http://example.com/test.php (описано ниже). Используйте его для вызовов REST, например, http://example.com/test.php/testing/123/hello. Это работает с Apache и Lighttpd из коробки, и никакие правила перезаписи не нужны.

$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;

>

Ответ 3

Определить метод HTTP или так называемый REQUEST METHOD можно с помощью следующего фрагмента кода :

$method = $_SERVER[‘REQUEST_METHOD’];

if ($method == ‘POST’)

// используется метод POST

> elseif ($method == ‘GET’)

// используется метод GET

> elseif ($method == ‘PUT’)

// используется метод PUT

> elseif ($method == ‘DELETE’)

// используется метод DELETE

> else

// неизвестный метод

>

Вы также можете сделать это с помощью переключателя, если вам больше нравится оператор if-else. Если в HTML-форме требуется метод, отличный от GET или POST, это часто решается с помощью скрытого поля в форме.

Ответ 4

В php вы можете сделать это так:

$method = $_SERVER[‘REQUEST_METHOD’];

switch ($method)

case ‘GET’:

//Здесь обрабатывается GET-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘POST’:

//Здесь обрабатывается POST-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘PUT’:

//Здесь обрабатывается PUT-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘PATCH’:

//Здесь обрабатывается PATCH-запрос

break;

case ‘DELETE’:

//Здесь обрабатывается DELETE-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘COPY’:

//Здесь обрабатывается COPY-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘OPTIONS’:

//Здесь обрабатывается OPTIONS-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘LINK’:

//Здесь обрабатывается LINK-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘UNLINK’:

//Здесь обрабатывается UNLINK-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘PURGE’:

//Здесь обрабатывается PURGE-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘LOCK’:

//Здесь обрабатывается LOCK-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘UNLOCK’:

//Здесь обрабатывается UNLOCK-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘PROPFIND’:

//Здесь обрабатывается PROPFIND-запрос

echo »Вы используете ‘.$method.’ метод’;

break;

case ‘VIEW’:

//Здесь обрабатывается VIEW-запрос

echo ‘Вы используете ‘.$method.’метод’;

break;

Default:

echo »Вы используете ‘.$method.’ метод’;

break;

>

?>

Ответ 5

Я использовал этот код. Он должен работать.

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;

>

Приведенный выше код будет работать с вызовами REST и также будет работать с html-формой:

Ответ 6

Поскольку речь идет о REST, получить метод запроса от сервера недостаточно. Вам также необходимо получить параметры маршрута RESTful. Причина разделения параметров RESTful и параметров GET/POST/PUT заключается в том, что ресурс должен иметь свой собственный уникальный URL для идентификации. Вот один из способов реализации RESTful маршрутов в PHP с помощью Slim:

https://github.com/codeguy/Slim

$app = new \Slim\Slim();

$app->get(‘/hello/:name’, function ($name)

echo «Привет, $name»;

>);

$app->run();

И настройте сервер соответствующим образом. Вот еще один пример с использованием AltoRouter:

https://github.com/dannyvankooten/AltoRouter

$router = new AltoRouter();

$router->setBasePath(‘/AltoRouter’); // (необязательно) поддиректория, в которой находится AltoRouter

// маршруты отображения

$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’);

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Источник

The REQUEST_METHOD superglobal in PHP

It is sometimes useful to know the HTTP request method, and PHP makes this easy via the REQUEST_METHOD super global..

d

PHP article image

To check the request method you may use the $_SERVER[‘REQUEST_METHOD’] variable, the $_SERVER is a PHP superglobal that is available to you at any time, even inside functions and classes.

To use the REQUEST_METHOD variable you could just echo its contents, but it is probably more useful in a switch or if statement.

if ($_SERVER['REQUEST_METHOD'] == 'POST')  echo 'The request was POST'; exit(); > else  http_response_code(405); header('Allow: GET, HEAD'); echo '

405 Method Not Allowed

'
; exit(); >

When to use REQUEST_METHOD

The REQUEST_METHOD variable may be used whenever you need to determine the HTTP request type.

For example, if you know your application only accepts user input via HTTP post requests, it is recommended to block other types of requests, and inform the user that the request is not valid.

It can be used as part of the server-side validation of user input, before attempting to validate the input itself.

The REQUEST_METHOD variable is filled out by PHP based on the HTTP request type, and can therefor be safely used without validation. There should be no risk of injection attacks in this variable.

We can not simply check if $_POST and $_GET is empty, since they are always defined, even if all the HTML form fields are empty.

Источник

Оцените статью