- Ещё один велосипед: простая библиотека для работы с HTTP-запросами
- Подключение и вызов
- Проверка метода
- Получение ключей
- Получение значений
- Сырые запросы (php://input)
- Работа с заголовками
- # Reading Request Data
- # Reading POST data
- # Reading GET data
- # Handling file upload errors
- # Uploading files with HTTP PUT
- # Passing arrays by POST
- # Remarks
- # Choosing between GET and POST
- # Request Data Vulnerabilities
- francescozanoni / get_raw_http_request.php
Ещё один велосипед: простая библиотека для работы с HTTP-запросами
Работа с API не обходится без взаимодействия с HTTP-запросами. Кто-то не заморачивается и использует глобальные массивы $_GET, $_POST и $_REQUEST. Признаться, сам так делал, но не так давно озадачился мыслью о необходимости какой-нибудь обёртки для удобства использования. Может быть, подобные библиотеки уже и есть, но я их пока не нашёл, кроме как в API Битрикса (возможно, плохо искал), а посему решил написать свою. К тому же согласитесь, что гораздо приятнее использовать свои библиотеки при работе с кодом.
Библиотека работает пока с методами GET и POST, а также с json-стройкой, получаемой из php://input. Ещё умеет делать проверку на https и получать заголовки.
Подключение и вызов
Для подключения библиотеки используйте Composer:
composer require ramapriya/http-request
require __DIR__ . '/vendor/autoload.php'; use Ramapriya\Request\Request;
Проверка метода
Теперь можно пользоваться библиотекой. К примеру, хотите вы узнать тип запроса, вызываете метод GetRequestMethod():
$method = Request::GetRequestMethod(); switch($method) < case 'GET': // ваш код break; case 'POST': // ваш код break; >
Однако обычно тип метода заранее известен, поэтому чтобы не создавать дополнительные переменные, достаточно использовать методы для проверки get и post — isGet() и isPost() соответственно:
if(Request::isPost() !== false) < // ваш код >else if(Request::isGet() !== false) < // ваш код >
Получение ключей
Бывает, что нужно получить список параметров запроса (не значений, а самих ключей), для этого также есть два метода для Get и Post:
$GetParams = Request::GetParams(); if(in_array($needle, $GetParams)) < // ваш код >$postParams = Request::PostParams(); if(in_array($needle, $postParams)) < // ваш код >
Получение значений
Ну и конечно, не обошлось и без методов получения самих значений параметров — Get() и Post(). Самое интересное, что можно получить, как отдельные параметры, так и весь массив целиком (который, кстати, преобразован в объект — не спрашивайте почему, просто мне нравится работать с объектами):
if(!empty(Request::Get('user'))) < $user = Request::Get('user'); >$request = Request::Post(); if(Request::isPost() && !empty($request)) < // ваш код >
Сырые запросы (php://input)
Отдельно стоит остановиться на методах работы с php://input. Это isRaw() — проверяет на сырой запрос, Raw(), возвращающий сконвертированную в объект json-строку и RawParams(), возвращающий ключи запроса. Помню, когда работал с API Sendpulse, приходилось писать примерно так:
$rawRequest = file_get_contents('php://input'); $request = json_decode($rawRequest); if(!empty($request)) < // полезный код >
$request = json_decode(file_get_contents('php://input'));
Но согласитесь, выглядит это достаточно запутанно.
С методами Raw() и isRaw() код уже вызывает больше эстетического удовольствия:
Работа с заголовками
Также в библиотеке есть несколько методов работы с заголовками:
GetAllHeaders() — получение всех заголовков.
$headers = Request::GetAllHeaders();
$domain = Request::GetHostName();
isHttps() — проверка на https
GetUserAgent() — получение юзер-агента. Кому-то это бывает важно.
$userAgent = Request::GetUserAgent();
Библиотека будет дополняться и модифицироваться. Исходный код, как всегда, на гитхабе
# Reading Request Data
Usually data sent in a POST request is structured key/value pairs with a MIME type of application/x-www-form-urlencoded . However many applications such as web services require raw data, often in XML or JSON format, to be sent instead. This data can be read using one of two methods.
php://input is a stream that provides access to the raw request body.
$rawdata = file_get_contents("php://input"); // Let's say we got JSON $decoded = json_decode($rawdata);
$HTTP_RAW_POST_DATA is a global variable that contains the raw POST data. It is only available if the always_populate_raw_post_data directive in php.ini is enabled.
$rawdata = $HTTP_RAW_POST_DATA; // Or maybe we get XML $decoded = simplexml_load_string($rawdata);
This variable has been deprecated since PHP version 5.6, and was removed in PHP 7.0.
Note that neither of these methods are available when the content type is set to multipart/form-data , which is used for file uploads.
# Reading POST data
Data from a POST request is stored in the superglobal
(opens new window) $_POST in the form of an associative array.
Note that accessing a non-existent array item generates a notice, so existence should always be checked with the isset() or empty() functions, or the null coalesce operator.
$from = isset($_POST["name"]) ? $_POST["name"] : "NO NAME"; $message = isset($_POST["message"]) ? $_POST["message"] : "NO MESSAGE"; echo "Message from $from: $message";
$from = $_POST["name"] ?? "NO NAME"; $message = $_POST["message"] ?? "NO MESSAGE"; echo "Message from $from: $message";
# Reading GET data
Data from a GET request is stored in the superglobal
(opens new window) $_GET in the form of an associative array.
Note that accessing a non-existent array item generates a notice, so existence should always be checked with the isset() or empty() functions, or the null coalesce operator.
Example: (for URL /topics.php?author=alice&topic=php )
$author = isset($_GET["author"]) ? $_GET["author"] : "NO AUTHOR"; $topic = isset($_GET["topic"]) ? $_GET["topic"] : "NO TOPIC"; echo "Showing posts from $author about $topic";
$author = $_GET["author"] ?? "NO AUTHOR"; $topic = $_GET["topic"] ?? "NO TOPIC"; echo "Showing posts from $author about $topic";
# Handling file upload errors
The $_FILES[«FILE_NAME»][‘error’] (where «FILE_NAME» is the value of the name attribute of the file input, present in your form) might contain one of the following values:
- UPLOAD_ERR_OK — There is no error, the file uploaded with success.
- UPLOAD_ERR_INI_SIZE — The uploaded file exceeds the upload_max_filesize directive in php.ini .
- UPLOAD_ERR_PARTIAL — The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
- UPLOAD_ERR_NO_FILE — No file was uploaded.
- UPLOAD_ERR_NO_TMP_DIR — Missing a temporary folder. (From PHP 5.0.3).
- UPLOAD_ERR_CANT_WRITE — Failed to write file to disk. (From PHP 5.1.0).
- UPLOAD_ERR_EXTENSION — A PHP extension stopped the file upload. (From PHP 5.2.0).
An basic way to check for the errors, is as follows:
$fileError = $_FILES["FILE_NAME"]["error"]; // where FILE_NAME is the name attribute of the file input in your form switch($fileError) case UPLOAD_ERR_INI_SIZE: // Exceeds max size in php.ini break; case UPLOAD_ERR_PARTIAL: // Exceeds max size in html form break; case UPLOAD_ERR_NO_FILE: // No file was uploaded break; case UPLOAD_ERR_NO_TMP_DIR: // No /tmp dir to write to break; case UPLOAD_ERR_CANT_WRITE: // Error writing to disk break; default: // No error was faced! Phew! break; >
# Uploading files with HTTP PUT
(opens new window) for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:
PUT /path/filename.html HTTP/1.1
Into your PHP code you would then do something like this:
/* PUT data comes in on the stdin stream */ $putdata = fopen("php://input", "r"); /* Open a file for writing */ $fp = fopen("putfile.ext", "w"); /* Read the data 1 KB at a time and write to the file */ while ($data = fread($putdata, 1024)) fwrite($fp, $data); /* Close the streams */ fclose($fp); fclose($putdata); ?>
(opens new window) you can read interesting SO question/answers about receiving file via HTTP PUT.
# Passing arrays by POST
Usually, an HTML form element submitted to PHP results in a single value. For example:
pre> print_r($_POST);?> pre> form method="post"> input type="hidden" name="foo" value="bar"/> button type="submit">Submitbutton> form>
This results in the following output:
However, there may be cases where you want to pass an array of values. This can be done by adding a PHP-like suffix to the name of the HTML elements:
pre> print_r($_POST);?> pre> form method="post"> input type="hidden" name="foo[]" value="bar"/> input type="hidden" name="foo[]" value="baz"/> button type="submit">Submitbutton> form>
This results in the following output:
Array ( [foo] => Array ( [0] => bar [1] => baz ) )
You can also specify the array indices, as either numbers or strings:
pre> print_r($_POST);?> pre> form method="post"> input type="hidden" name="foo[42]" value="bar"/> input type="hidden" name="foo[foo]" value="baz"/> button type="submit">Submitbutton> form>
Which returns this output:
Array ( [foo] => Array ( [42] => bar [foo] => baz ) )
This technique can be used to avoid post-processing loops over the $_POST array, making your code leaner and more concise.
# Remarks
# Choosing between GET and POST
GET requests, are best for providing data that’s needed to render the page and may be used multiple times (search queries, data filters. ). They are a part of the URL, meaning that they can be bookmarked and are often reused.
POST requests on the other hand, are meant for submitting data to the server just once (contact forms, login forms. ). Unlike GET, which only accepts ASCII, POST requests also allow binary data, including file uploads
You can find a more detailed explanation of their differences here
# Request Data Vulnerabilities
Retrieving data from the $_GET and $_POST superglobals without any validation is considered bad practice, and opens up methods for users to potentially access or compromise data through code
(opens new window) . Invalid data should be checked for and rejected as to prevent such attacks.
Request data should be escaped depending on how it is being used in code, as noted here
(opens new window) . A few different escape functions for common data use cases can be found in this answer
francescozanoni / get_raw_http_request.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Get raw HTTP request. |
* |
* Inspired by: |
* — https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 |
* — https://www.php.net/manual/en/function.getallheaders.php#104307 |
* |
* @return string |
*/ |
function get_raw_http_request () |
// Request line |
$ data = sprintf( |
» %s %s %s \r\n», |
$ _SERVER [» REQUEST_METHOD «], |
$ _SERVER [» REQUEST_URI «], |
$ _SERVER [» SERVER_PROTOCOL «] |
); |
// Headers |
foreach ( $ _SERVER as $ name => $ value ) |
if (substr( $ name , 0 , 5 ) === » HTTP_ «) |
$ name = substr( $ name , 5 ); |
$ name = str_replace(» _ «, » «, $ name ); |
$ name = strtolower( $ name ); |
$ name = ucwords( $ name ); |
$ name = str_replace(» «, » — «, $ name ); |
> else if ( $ name === » CONTENT_TYPE «) |
$ name = » Content-Type «; |
> else if ( $ name === » CONTENT_LENGTH «) |
$ name = » Content-Length «; |
> else |
continue ; |
> |
$ data .= ( $ name . » : » . $ value . «\r\n»); |
> |
// Body |
$ data .= («\r\n» . file_get_contents(» php://input «) . «\r\n»); |
return $ data ; |
> |