php make get request
http_build_query
http_build_query — Генерирует URL-кодированную строку запроса
Описание
Генерирует URL-кодированную строку запроса из предоставленного ассоциативного (или индексированного) массива.
Список параметров
Может быть массив или объект, содержащий свойства.
Если data массив, то он может быть простой одномерной структурой или массивом массивов (который, в свою очередь, может содержать другие массивы).
Если data объект, тогда только общедоступные свойства будут включены в результат.
Если числовые индексы используются в базовом массиве и этот параметр указан, то он будет добавлен к числовому индексу для элементов только в базовом массиве.
Это позволяет обеспечить допустимые имена переменных, в которые позже данные будут декодированы PHP или другим CGI-приложением.
arg_separator.output используется в качестве разделителя аргументов, но может быть переопределён путём указания этого параметра.
Возвращаемые значения
Возвращает URL-кодированную строку.
Примеры
Пример #1 Простой пример использования http_build_query()
Результат выполнения данного примера:
Пример #2 Пример использования http_build_query() с числовыми индексами элементов.
Результат выполнения данного примера:
Пример #3 Пример использования http_build_query() с многомерными массивами
Результат выполнения данных примеров: (символы перенесены для удобства чтения)
Только числовой индексированный элемент «CEO» в базовом массиве получил префикс. Другие числовые индексы, найденные в pastimes, не требуют строкового префикса, чтобы быть допустимыми именами переменных.
Пример #4 Пример использования http_build_query() с объектом
$parent = new parentClass ();
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 24 notes
Params with null value do not present in result string.
If you need to change the enc_type, use this:
http_build_query($query, null, ini_get(‘arg_separator.output’), PHP_QUERY_RFC3986);
// BAD CODE!
http_build_query($query, null, null, PHP_QUERY_RFC3986);
if you send boolean values it transform in integer :
$a = [teste1= true,teste2=false];
echo http_build_query($a)
//result will be teste1=1&teste2=0
This function makes like this
To do it like this:
As noted before, with php5.3 the separator is & on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.
But if you post to a tomcat java server or something else the & might not be handled properly.
To overcome this specify:
http_build_query($array); //gives & to some servers
It’s not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.
Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.
$post_data = array(‘name’=>’miller’, ‘address’=>array(‘address_lines’=>array()), ‘age’=>23);
echo http_build_query($post_data);
Instead you can make your own simple function if you simply want to pass along the data:
If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.
How to send a GET request from PHP?
I’m planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.
How do I do it in PHP?
8 Answers 8
For anything more complex, I’d use cURL.
For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):
http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.
Remember that if you are using a proxy you need to do a little trick in your php code:
Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )
I like using fsockopen open for this.
In the other hand, using REST API of other servers are very popular in PHP. Suppose you are looking for a way to redirect some HTTP requests into the other server (for example getting an xml file). Here is a PHP package to help you:
So, getting the xml file:
Not the answer you’re looking for? Browse other questions tagged php http get or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How do I send a POST request with PHP?
Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not take any action with GET method.
16 Answers 16
CURL-less method with PHP5:
See the PHP manual for more information on the method and how to add headers, for example:
@Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.
I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That’s why I use http_build_query().
I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.
Installing Guzzle
Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.
Using Guzzle to send a POST request
The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:
I’d like to add some thoughts about the curl-based answer of Fred Tanrikut. I know most of them are already written in the answers above, but I think it is a good idea to show an answer that includes all of them together.
Here is the class I wrote to make HTTP-GET/POST/PUT/DELETE requests based on curl, concerning just about the response body:
Improvements
Example of usage
DELETE
Testing
You can also make some cool service tests by using this simple class.
There’s another CURL method if you are going that way.
PHP GET/POST request
last modified July 9, 2020
PHP GET/POST request tutorial shows how to generate and process GET and POST requests in PHP. We use plain PHP and Symfony, Slim, and Laravel frameworks.
The is an application protocol for distributed, collaborative, hypermedia information systems. HTTP protocol is the foundation of data communication for the World Wide Web.
HTTP GET
The HTTP GET method requests a representation of the specified resource.
HTTP POST
The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.
PHP GET request
In the following example, we generate a GET request with curl tool and process the request in plain PHP.
We start the server.
We send two GET requests with curl.
PHP POST request
In the following example, we generate a POST request with curl tool and process the request in plain PHP.
We start the server.
We send a POST request with curl.
PHP send GET request with Symfony HttpClient
Symfony provides the HttpClient component which enables us to create HTTP requests in PHP.
We install the symfony/http-client component.
We start the server.
We run the send_get_req.php script.
PHP send POST request with Symfony HttpClient
In the following example, we send a POST request with Symfony HttpClient.
We start the server.
We run the send_post_req.php script.
PHP GET request in Symfony
In the following example, we process a GET request in a Symfony application.
A new application is created.
We install the annot and maker components.
We create a new controller.
Inside the HomeController’s index method, we get the query parameters and create a response.
We start the server.
We generate a GET request with curl.
PHP POST request in Symfony
In the following example, we process a POST request in a Symfony application.
We change the controller to process the POST request.
We start the server.
We generate a POST request with curl.
PHP GET request in Slim
In the following example, we are going to process a GET request in the Slim framework.
We get the parameters and return a response in Slim.
The query parameter is retrieved with getQueryParam ; the second parameter is the default value.
We start the server.
We generate a GET request with curl.
PHP POST request in Slim
In the following example, we are going to process a POST request in the Slim framework.
We get the POST parameters and return a response in Slim.
We start the server.
We generate a POST request with curl.
PHP GET request in Laravel
In the following example, we process a GET request in Laravel.
We create a new Laravel application.
We get the GET parameters and create a response.
We start the server.
We send a GET request with curl.
PHP POST request in Laravel
In the following example, we send a POST request from an HTML form.
We validate and retrieve the POST parameters and send them in the response. This example should be tested in a browser.
In this tutorial, we have worked with GET and POST requests in plain PHP, Symfony, Slim, and Laravel.
Detecting request type in PHP (GET, POST, PUT or DELETE)
How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?
13 Answers 13
Example
REST in PHP can be done pretty simple. Create http://example.com/test.php (outlined below). Use this for REST calls, e.g. http://example.com/test.php/testing/123/hello. This works with Apache and Lighttpd out of the box, and no rewrite rules are needed.
Detecting the HTTP method or so called REQUEST METHOD can be done using the following code snippet.
You could also do it using a switch if you prefer this over the if-else statement.
If a method other than GET or POST is required in an HTML form, this is often solved using a hidden field in the form.
For more information regarding HTTP methods I would like to refer to the following StackOverflow question:
We can also use the input_filter to detect the request method while also providing security through input sanitation.
Since this is about REST, just getting the request method from the server is not enough. You also need to receive RESTful route parameters. The reason for separating RESTful parameters and GET/POST/PUT parameters is that a resource needs to have its own unique URL for identification.
Here’s one way of implementing RESTful routes in PHP using Slim: