New http request php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A simple HTTP Request class for PHP. Works with cURL and fsockopen.

benastan/HTTPRequest

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.markdown

Easy HTTP Requests with PHP

HTTPRequest simplifies cURL and fsockopen requests around Object-Oriented concepts. It serves as a superb foundation for PHP-based API integrations and allows a range of customization of headers, query parameters and automatically degrades to fsockopen when cURL is unavailable.

$http = new HTTPRequest('www.google.com'); $http -> execute(); echo $http -> getResponseText(); $http -> close(); 

Basic Google Maps Geocoding API Request

HTTPRequest is also great for making calls to 3rd-party APIs. Here’s a Geocoding request to Google Maps:

$http = new HTTPRequest('maps.googleapis.com', '/maps/api/geocode/json'); $params = array( 'address' => 'The Moon', 'sensor' => false ); $http -> setQueryParams($params); $http -> execute(); echo $http -> getResponseText(); $http -> close(); 

And we get back some pretty JSON:

In this case, the constructor took a second parameter (the uri) in addition to first property (which was the host name). The constructor can also take the port number, a boolean directing whether or not to use cURL if possible and the timeout in seconds.

public function __construct($host = null, $uri = '/', $port = 80, $useCurl = null, $timeout = 10) 

Many of the HTTPRequest class’ methods return the instance itself, enabling chaining (if you please).

$http = new HTTPRequest('maps.googleapis.com', '/maps/api/geocode/json'); $params = array('address'=>'The Moon','sensor'=>false); echo $http -> setQueryParams($params) -> execute() -> getResponseText(); $http -> close(); 

HTTPRequest also supports HTTPS/SSL for both cURL and fsockopen. For example, you can make calls to the Trello API in a snap:

$http = new HTTPRequest('api.trello.com', '/1/boards/4d5ea62fd76aa1136000000c', 443); $params = array( 'key' => '[YOUR_DEVELOPER_KEY]' ); $http -> setQueryParams($params); $http -> execute(); echo $http -> getResponseText(); $http -> close(); 

We get back some info about the Trello development board:

Читайте также:  Двумерные массивы матрицы питон

Источник

Overview

With this package, one can easily perform HTTP request from within PHP scripts. It support GET/POST/HEAD/TRACE/PUT/DELETE, Basic authentication, Proxy, Proxy Authentication, SSL, file uploads etc.

Because of the above mentioned features HTTP_Request makes it possible to mimic big parts of web browsers such as the widely-known Mozilla browser in PHP applications. Possible application areas are:

  • Checking the validity of WWW links with the help of getResponseCode.
  • Grabbing remote web pages and parsing the result.
  • etc.

A few examples

Fetches yahoo.com and displays it

Fetching two website in a row

In this example, two websites are fetched and displayed. To the first one a POST parameter is passed. The POST data stack is cleared before the second website is fetched.

$req =& new HTTP_Request ( «http://www.php.net» );
$req -> setMethod ( HTTP_REQUEST_METHOD_POST );
$req -> addPostData ( «Foo» , «bar» );
if (! PEAR :: isError ( $req -> sendRequest ())) $response1 = $req -> getResponseBody ();
> else $response1 = «» ;
>

$req -> setMethod ( HTTP_REQUEST_METHOD_GET );
$req -> setURL ( «http://pear.php.net» );
$req -> clearPostData ();
if (! PEAR :: isError ( $req -> sendRequest ())) $response2 = $req -> getResponseBody ();
> else $response2 = «» ;
>

echo $response1 ;
echo $response2 ;
?>

Источник

PHP GET/POST request

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.

$ php -v php -v PHP 8.1.2 (cli) (built: Aug 8 2022 07:28:23) (NTS) .

HTTP

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.

  • should only be used to request a resource
  • parameters are displayed in the URL
  • can be cached
  • remain in the browser history
  • can be bookmarked
  • should never be used when dealing with sensitive data
  • have length limits

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.

  • should be used to create a resource
  • parameters are not displayed in the URL
  • are never cached
  • do not remain in the browser history
  • cannot be bookmarked
  • can be used when dealing with sensitive data
  • have no length limits
Читайте также:  Python подключить файл txt

PHP $_GET and $_POST

PHP provides the $_GET and $_POST superglobals. The $_GET is an associative array of variables passed to the current script via the URL parameters (query string). The $_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

PHP GET request

In the following example, we generate a GET request with curl tool and process the request in plain PHP.

 $message = $_GET['message']; if ($message == null) < $message = 'hello there'; >echo "$name says: $message";

The example retrieves the name and message parameters from the $_GET variable.

$ php -S localhost:8000 get_req.php
$ curl 'localhost:8000/?name=Lucia&message=Cau' Lucia says: Cau $ curl 'localhost:8000/?name=Lucia' Lucia says: hello there

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.

 $message = $_POST['message']; if ($message == null) < $message = 'hello there'; >echo "$name says: $message";

The example retrieves the name and message parameters from the $_POST variable.

$ php -S localhost:8000 post_req.php
$ curl -d "name=Lucia&message=Cau" localhost:8000 Lucia says: Cau

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.

$ composer req symfony/http-client

We install the symfony/http-client component.

request('GET', 'http://localhost:8000', [ 'query' => [ 'name' => 'Lucia', 'message' => 'Cau', ] ]); $content = $response->getContent(); echo $content . "\n";

The example sends a GET request with two query parameters to localhost:8000/get_request.php .

$ php -S localhost:8000 get_req.php
$ php send_get_req.php Lucia says: Cau

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.

request('POST', 'http://localhost:8000', [ 'body' => [ 'name' => 'Lucia', 'message' => 'Cau', ] ]); $content = $response->getContent(); echo $content . "\n";

The example sends a POST request with two parameters to localhost:8000/post_req.php .

$ php -S localhost:8000 post_req.php
$ php send_post_req.php Lucia says: Cau

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.

$ symfony new symreq $ cd symreq

A new application is created.

$ composer req annot $ composer req maker --dev

We install the annot and maker components.

$ php bin/console make:controller HomeController

We create a new controller.

) */ public function index(Request $request): Response < $name = $request->query->get('name', 'guest'); $message = $request->query->get('message', 'hello there'); $output = "$name says: $message"; return new Response($output, Response::HTTP_OK, ['content-type' => 'text/plain']); > >

Inside the HomeController’s index method, we get the query parameters and create a response.

$name = $request->query->get('name', 'guest');

The GET parameter is retrieved with $request->query->get . The second parameter of the method is a default value which is used when no value was retrieved.

$ curl 'localhost:8000/?name=Lucia&message=Cau' Lucia says: Cau

We generate a GET request with curl.

Читайте также:  Python условие не равен

PHP POST request in Symfony

In the following example, we process a POST request in a Symfony application.

) */ public function index(Request $request): Response < $name = $request->request->get('name', 'guest'); $message = $request->request->get('message', 'hello there'); $output = "$name says: $message"; return new Response($output, Response::HTTP_OK, ['content-type' => 'text/plain']); > >

We change the controller to process the POST request.

$name = $request->request->get('name', 'guest');

The POST parameter is retrieved with $request->request->get . The second parameter of the method is a default value which is used when no value was retrieved.

$ curl -d "name=Lucia" localhost:8000 Lucia says: hello there

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.

$ composer req slim/slim $ composer req slim/psr7 $ composer req slim/http

We install slim/slim , slim/psr7 , and slim/http packages.

get('/', function (Request $request, Response $response): Response < $name = $request->getQueryParam('name', 'guest'); $message = $request->getQueryParam('message', 'hello there'); $output = "$name says $message"; $response->getBody()->write($output); return $response; >); $app->run();

We get the parameters and return a response in Slim.

$name = $request->getQueryParam('name', 'guest');

The query parameter is retrieved with getQueryParam ; the second parameter is the default value.

$response->getBody()->write($output);

We write the output to the response body with write .

$ php -S localhost:8000 -t public
$ curl 'localhost:8000/?name=Lucia&message=Cau' Lucia says: Cau

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.

post('/', function (Request $request, Response $response): Response < $data = $request->getParsedBody(); $name = $data['name']; $message = $data['message']; if ($name == null) < $name = 'guest'; >if ($message == null) < $message = 'hello there'; >$output = "$name says: $message"; $response->getBody()->write($output); return $response; >); $app->run();

We get the POST parameters and return a response in Slim.

$data = $request->getParsedBody();

The POST parameters are retrieved with getParsedBody .

$ php -S localhost:8000 -t public
$ curl -d "name=Lucia" localhost:8000 Lucia says: hello there

We generate a POST request with curl.

PHP GET request in Laravel

In the following example, we process a GET request in Laravel.

$ laravel new larareq $ cd larareq

We create a new Laravel application.

query('name', 'guest'); $message = $request->query('message', 'hello there'); $output = "$name says $message"; return $output; >);

We get the GET parameters and create a response.

$ curl 'localhost:8000/?name=Lucia&message=Cau' Lucia says Cau

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 have a POST form in a Blade template. Laravel requires CSRF protection for POST requests. We enable CSRF protection with @csrf .

); Route::post('/process_form', function (Request $request) < $request->validate([ 'name' => 'required|min:2', 'message' => 'required|min:3' ]); $name = $request->input('name'); $message = $request->input('message'); $output = "$name says: $message"; return $output; >);

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.

Источник

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