Php construct http request

Making a request

Ready to go? Make sure you have Requests installed and bootstrapped either the Composer autoload.php file, the Requests autoload function or your autoloader, before attempting any of the steps in this guide.

Make a GET Request

One of the most basic things you can do with HTTP is make a GET request.

Let’s grab GitHub’s public events:

$response = WpOrg\Requests\Requests::get('https://api.github.com/events'); 

$response is now a WpOrg\Requests\Response object. Response objects are what you’ll be working with whenever you want to get data back from your request.

Using the Response Object

Now that we have the response from GitHub, let’s get the body of the response.

var_dump($response->body); // string(42865) "[  

Custom Headers

If you want to add custom headers to the request, simply pass them in as an associative array as the second parameter:

$response = WpOrg\Requests\Requests::get('https://api.github.com/events', array('X-Requests' => 'Is Awesome!')); 

Make a POST Request

Making a POST request is very similar to making a GET:

$response = WpOrg\Requests\Requests::post('https://httpbin.org/post'); 

You’ll probably also want to pass in some data. You can pass in either a string, an array or an object (Requests uses http_build_query internally) as the third parameter (after the URL and headers):

$data = array('key1' => 'value1', 'key2' => 'value2'); $response = WpOrg\Requests\Requests::post('https://httpbin.org/post', array(), $data); var_dump($response->body); 
string(503) "< "origin": "124.191.162.147", "files": <>, "form": < "key2": "value2", "key1": "value1" >, "headers": < "Content-Length": "23", "Accept-Encoding": "deflate;q=1.0, compress;q=0.5, gzip;q=0.5", "X-Forwarded-Port": "80", "Connection": "keep-alive", "User-Agent": "php-requests/1.6-dev", "Host": "httpbin.org", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" >, "url": "https://httpbin.org/post", "args": <>, "data": "" >" 

To send raw data, simply pass in a string instead. You’ll probably also want to set the Content-Type header to ensure the remote server knows what you’re sending it:

$url = 'https://api.github.com/some/endpoint'; $headers = array('Content-Type' => 'application/json'); $data = array('some' => 'data'); $response = WpOrg\Requests\Requests::post($url, $headers, json_encode($data)); 

Note that if you don’t manually specify a Content-Type header, Requests has undefined behaviour for the header. It may be set to various values depending on the internal execution path, so it’s recommended to set this explicitly if you need to.

Status Codes

The Response object also gives you access to the status code:

var_dump($response->status_code); // int(200) 

You can also easily check if this status code is a success code, or if it’s an error:

var_dump($response->success); // bool(true) 

Response Headers

We can also grab headers pretty easily:

var_dump($response->headers['Date']); // string(29) "Thu, 09 Feb 2021 15:22:06 GMT" 

Note that this is case-insensitive, so the following are all equivalent:

$response->headers['Date'] $response->headers['date'] $response->headers['DATE'] $response->headers['dAtE'] 

If a header isn’t set, this will give null . You can also check with isset($response->headers[‘date’])

Is something missing in this documentation or did you find something to be wrong?
Please create an issue to help us improve the documentation.

Источник

Как создать GET POST запросы с помощью PHP

Первый метод, позволяющий выполнить PHP POST запрос, заключается в использовании file_get_contents . Второй метод будет использовать fread в сочетании с парой других функций. Оба варианта применяют функцию stream context create , чтобы заполнить необходимые поля заголовка запроса.

Пояснение кода

Переменная $sPD содержит данные, которые нужно передать. Она должна иметь формат строки HTTP-запроса , поэтому некоторые специальные символы должны быть закодированы.

И в функции file_get_contents , и в функции fread у нас есть два новых параметра. Первый из них — use_include_path . Так как мы выполняем HTTP- запрос , в обоих примерах он будет иметь значение false . При использовании значения true для считывания локального ресурса функция будет искать файл по адресу include_path .

Второй параметр — context , он заполняется возвращаемым значением stream context create , который принимает значение массива $aHTTP .

Использование file_get_contents для выполнения POST-запросов

Чтобы в PHP отправить POST запрос с помощью file_get_contents , нужно применить stream context create , чтобы вручную заполнить поля заголовка и указать, какая « обертка » будет использоваться — в данном случае HTTP :

$sURL = "http://brugbart.com/Examples/http-post.php"; // URL-адрес POST $sPD = "name=Jacob&bench=150"; // Данные POST $aHTTP = array( 'http' => // Обертка, которая будет использоваться array( 'method' => 'POST', // Метод запроса // Ниже задаются заголовки запроса 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents;

Использование fread для выполнения POST-запросов

Для выполнения POST-запросов можно использовать функцию fread . В следующем примере stream context create используется для составления необходимых заголовков HTTP-запроса :

$sURL = "http://brugbart.com/Examples/http-post.php"; // URL-адрес POST $sPD = "name=Jacob&bench=150"; // Данные POST $aHTTP = array( 'http' => // Обертка, которая будет использоваться array( 'method' => 'POST', // Request Method // Ниже задаются заголовки запроса 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $handle = fopen($sURL, 'r', false, $context); $contents = ''; while (!feof($handle)) < $contents .= fread($handle, 8192); >fclose($handle); echo $contents;

Как выполнить в PHP GET-запрос

Теперь мы уделим внимание использованию fread и file_get_contents для загрузки контента из интернета через HTTP и HTTPS . Чтобы использовать методы, описанные в этой статье, необходимо активировать опцию fopen wrappers . Для этого в файле php.ini нужно установить для параметра allow_url_fopen значение On .

Выполнение POST и GET запросов PHP применяется для входа в систему на сайтах, получения содержимого веб-страницы или проверки новых версий приложений. Мы расскажем, как выполнять простые HTTP-запросы .

Использование fread для загрузки или получения файлов через интернет

Помните, что считывание веб-страницы ограничивается доступной частью пакета. Так что нужно использовать функцию stream_get_contents ( аналогичную file_get_contents ) или цикл while , чтобы считывать содержимое меньшими фрагментами до тех пор, пока не будет достигнут конец файла:

  fclose($handle); echo $contents; ?>

В данном случае обработки POST запроса PHP последний аргумент функции fread равен размеру фрагмента. Он, как правило, не должен быть больше, чем 8192 ( 8*1024 ).

Имейте в виду, что он может быть больше или меньше, а также может быть ограничен настройками системы, на которой запускается PHP .

Использование file_get_contents для получения URL-адреса сайта

Еще проще использовать этот метод при считывании файла по HTTP , так как вам не придется заботиться о считывании по фрагментам — все обрабатывается в PHP .

Источник

GET, POST, and HEAD requests with PHP’s build-in functions

How to send HTTP requests using the build-in file functions of PHP.

d

PHP article image

There are a few ways to perform HTTP requests in PHP, in this tutorial we will show how to send a POST and GET request by using the file- functions in combination with stream_context_create.

While using a library like cURL is probably one of the most popular ways to perform HTTP requests, you can also use functions such as file_get_contents and fopen.

While the name of these functions do not exactly indicate that they can also be used for HTTP requests, they do actually work quite well for this, and they are also fairly easy to use.

The stream_context_create function mentioned before is used to gain finer control over various options related to a request.

There should be no disadvantage to using the build-in functions instead of cURL, and unlike what is often claimed, they can be used for both POST and GET requests. However, some hosting companies might disable allow_url_fopen, which will break scripts relying on these methods.

GET Requests

To perform a simple get request, we will first create a $handle variable. We can use this to reference the request when storing the downloaded data in the $contents variable using stream_get_contents.

$handle = fopen("https://beamtic.com/", "rb"); $contents = stream_get_contents($handle); fclose($handle); 

The stream_get_contents function automatically downloads a file or web page, however, if you wish to do it manually, for finer control over the process, you may use a while loop in combination with fread:

$handle = fopen("https://beamtic.com/", "rb"); $contents = ''; while (!feof($handle))  $contents .= fread($handle, 8192); > fclose($handle); echo $contents; 

In this case the last argument in the fread function is equal to the chunk size, this is usually not larger than 8192 (8*1024). Keep in mind that this can be larger or smaller, but may also be limited by the system PHP is running on. You can optimize your PHP scripts by not using a larger chunk-size than that of your storage device.

One of the simplest ways to download a file, is to use file_get_contents. It requires far less code than using the other methods, but it also offers less control over the process.

$homepage = file_get_contents('https://beamtic.com/'); echo $homepage; 

POST Requests

Sending a POST request is not much harder than sending GET. We just have to use the stream_context_create function to add the necessary headers to perform the request.

Again, we can do this both with file_get_contents and fopen; but let us just use file_get_contents for now:

$sURL = "https://beamtic.com/Examples/http-post.php"; // The POST URL $sPD = "name=Jacob&bench=150"; // The POST Data $aHTTP = array( 'http' => // The wrapper to be used array( 'method' => 'POST', // Request Method // Request Headers Below 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents; 

The $sURL variable contains the POST URL.

The $sPD variable contains the data you want to post. Formatting should match the content-type header.

The $aHTTP array has all of the options, including headers, which will be passed on to stream_context_create.

You can also perform POST requests with the fread function.

$sURL = "http://beamtic.com/Examples/http-post.php"; // The POST URL $sPD = "name=Jacob&bench=150"; // The POST Data $aHTTP = array( 'http' => // The wrapper to be used array( 'method' => 'POST', // Request Method // Request Headers Below 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $handle = fopen($sURL, 'r', false, $context); $contents = ''; while (!feof($handle))  $contents .= fread($handle, 8192); > fclose($handle); echo $contents; 

Request Headers

If you got multiple headers, remember to separate them with \r\n

The content-type header tells the server how the posted data is formatted. The application/x-www-form-urlencoded content-type is often used by web applications, but you can also encounter multipart/form-data. If an application does not support the content-type you specify, the POST will usually just fail.

The content header contains the actual data that you want to post. This should be formatted in accordance with the content-type you are using.

Alternatively, you may also add options and headers as shown below, this time adding a referer header:

$aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: https://beamtic.com/\r\n"; 

Additional request headers will be added in the same way; do this by adding a single Carriage return (\r), and a line feed (\n) at the end of each header, followed by whatever header you want to add. Once you have added all the headers, you should end up with something like the below (full script):

$sURL = "https://beamtic.com/api/request-headers"; // The POST URL $aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: https://beamtic.com/\r\n"; $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents; 

Tools:

You can use the following API endpoints for testing purposes:

https://beamtic.com/api/user-agent
https://beamtic.com/api/request-headers

Источник

Читайте также:  Python вычислить среднее значение
Оцените статью