PHP code example of popphp / pop-http

1. Go to this page and download the library: Download popphp/pop-http library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

popphp / pop-http example snippets


use Pop\Http\Client;

$response = Client::get('http://localhost/');

use Pop\Http\Client;

$client   = new Client('http://localhost/');
$response = $client->get();

use Pop\Http\Client;

$client   = new Client('http://localhost/', ['method' => 'GET']);
$response = $client->send();

$content = $response->getParsedResponse();

use Pop\Http\Client;

$response = Client::post('http://localhost/post', [
    'data' => [
        'foo' => 'bar',
        'baz' => 123
    ]
]);

use Pop\Http\Client;

$client = new Client('http://localhost/post', [
    'data' => [
        'foo' => 'bar',
        'baz' => 123
    ]
]);
$response = $client->post();

use Pop\Http\Client;

$client = new Client('http://localhost/post', [
    'method' => 'POST',
    'data'   => [
        'foo' => 'bar',
        'baz' => 123
    ]
]);
$response = $client->send();

use Pop\Http\Client;

$responsePut    = Client::put('http://localhost/put', ['data' => ['foo' => 'bar']]);
$responsePatch  = Client::patch('http://localhost/patch', ['data' => ['foo' => 'bar']]);
$responseDelete = Client::delete('http://localhost/delete', ['data' => ['foo' => 'bar']]);

use Pop\Http\Auth;
use Pop\Http\Client;

$response = Client::post('http://localhost/auth', Auth::createBasic('username', 'password'));

use Pop\Http\Auth;
use Pop\Http\Client;

$response = Client::post('http://localhost/auth', Auth::createBearer('MY_AUTH_TOKEN'));

use Pop\Http\Auth;
use Pop\Http\Client;

$response = Client::post('http://localhost/auth', Auth::createKey('MY_API_KEY')));

use Pop\Http\Auth;
use Pop\Http\Client;

$response = Client::post(
    'http://localhost/auth',
    Auth::createDigest(
        new Auth\Digest('realm', 'username', 'password', '/uri', 'SERVER_NONCE')
    )
);

use Pop\Http\Auth;
use Pop\Http\Client;

$response = Client::post(
    'http://localhost/auth',
    Auth::createDigest(
        Auth\Digest::createFromWwwAuth($wwwAuthHeader, 'username', 'password', '/uri')
    )
);

use Pop\Http\Client;
use Pop\Http\Client\Request;

$client    = new Client(['base_uri' => 'http://localhost']);
$response1 = $client->get('/page1'); // Will request http://localhost/page1
$response2 = $client->get('/page2'); // Will request http://localhost/page2
$response2 = $client->get('/page3'); // Will request http://localhost/page3

use Pop\Http\Client;
use Pop\Http\Client\Request;

$client = new Client('http://localhost/post', [
    'data'   => [
        'foo' => 'bar',
        'baz' => 123
    ],
    'type' => Request::JSON // "application/json"
]);

$response = $client->post();

use Pop\Http\Client;
use Pop\Http\Client\Request;

$client = new Client('http://localhost/post', [
    'method' => 'POST',
    'files' => [
        '/path/to/file/image1.jpg',
        '/path/to/file/image2.jpg',    
    ],
    'type' => Request::MULTIPART // "multipart/form-data"
]);

$response = $client->send();

$content = $response->getParsedResponse();

use Pop\Http\Client;

// Returns an array
$data = Client::get('http://localhost/')->json();

use Pop\Http\Client;

// Returns an instance of Pop\Utils\Collection
$data = Client::get('http://localhost/')->collect();

use Pop\Http\Client;
use Pop\Http\Client\Request;

$client = new Client('http://localhost/', ['auto' => true]);
$data   = $client->get(); // Returns an array

$clientResponse = $client->getResponse();

use Pop\Http\Client;
use Pop\Http\Client\Request;

$request = new Request('http://localhost/', 'POST');
$request->createAsJson();
$request->addHeaders([
    'X-Custom-Header: Custom-Value',
]);
$request->setData([
    'foo' => 'bar',
    'baz' => 123
]);

$client = new Client($request);
$response = $client->send();

use Pop\Http\Client\Request;

$requestJson  = Request::createJson('http://localhost/', 'POST', $data);
$requestXml   = Request::createXml('http://localhost/', 'POST', $data);
$requestUrl   = Request::createUrlForm('http://localhost/', 'POST', $data);
$requestMulti = Request::createMultipart('http://localhost/', 'POST', $data);

$request->createAsJson();
$request->createAsXml();
$request->createAsUrlEncoded();
$request->createAsMultipart();

use Pop\Http\Client;

$client = new Client('http://localhost:8000/files.php', [
    'method' => 'POST',
    'data'  => [
        'foo' => 'bar'
    ],
    'headers' => [
        'Authorization' => 'Bearer 123456789',
    ],
    'type' => Request::URLFORM
]);
echo $client->render();

use Pop\Http\Client;

$response = Client::post('http://localhost/post', [
    'data' => [
        'foo' => 'bar',
        'baz' => 123
    ]
]);

echo $response->getCode();                      // 200
echo $response->getMessage();                   // OK
var_dump($response->getHeaders());              // An array of HTTP header objects
var_dump($response->hasHeader('Content-Type')); // Boolean result
var_dump($response->getBody());                 // A body object than contains the response content

// i.e., 'application/json'
var_dump($response->getHeaderValueAsString('Content-Type'));
// Get actual content of the body object
var_dump($response->getBodyContent());

var_dump($response->getParsedResponse());

$response->isSuccess();              // Bool on 100/200/300-level responses
$response->isError();                // Bool on 400/500-level responses
$response->isContinue();             // Bool on 100-level response
$response->isOk();                   // Bool on 200 response
$response->isCreated();              // Bool on 201 response
$response->isAccepted();             // Bool on 202 response
$response->isNoContent();            // Bool on 204 response
$response->isRedirect();             // Bool on 300-level response
$response->isMovedPermanently();     // Bool on 301 response
$response->isFound();                // Bool on 302 response
$response->isClientError();          // Bool on 400-level response
$response->isBadRequest();           // Bool on 400 response
$response->isUnauthorized();         // Bool on 401 response
$response->isForbidden();            // Bool on 403 response
$response->isNotFound();             // Bool on 404 response
$response->isMethodNotAllowed();     // Bool on 405 response
$response->isNotAcceptable();        // Bool on 406 response
$response->isRequestTimeout();       // Bool on 408 response
$response->isConflict();             // Bool on 409 response
$response->isLengthRequired();       // Bool on 411 response
$response->isUnsupportedMediaType(); // Bool on 415 response
$response->isUnprocessableEntity();  // Bool on 422 response
$response->isTooManyRequests();      // Bool on 429 response
$response->isServerError();          // Bool on 500-level response
$response->isInternalServerError();  // Bool on 500 response
$response->isBadGateway();           // Bool on 502 response
$response->isServiceUnavailable();   // Bool on 503 response

use Pop\Http\Client;
use Pop\Http\Client\Handler\Stream;

$client = new Client('http://localhost/', new Stream());

use Pop\Http\Client;
use Pop\Http\Client\Handler\Stream;

$client = new Client('http://localhost/');
$client->setHandler(new Stream());

// Example with a CURL handler
$client->getHandler()->setOption(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

use Pop\Http\Client;
use Pop\Http\Client\Handler\Curl;

$curl = new Curl();
$curl->setOptions([
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0
]);

$client = new Client('http://localhost/');
$client->setHandler($curl);

use Pop\Http\Client;
use Pop\Http\Client\Handler\Stream;

$stream = new Stream();
$stream->setContextOptions([
    'http' => [
        'protocol_version' => '1.0'
    ]
]);

$client = new Client('http://localhost/');
$client->setHandler($stream);

use Pop\Http\Client;

// Three GET requests
$multiHandler = Client::createMulti([
    'http://localhost/test1.php',
    'http://localhost/test2.php',
    'http://localhost/test3.php'
]);

use Pop\Http\Client;
use Pop\Http\Client\Request;

// Three POST requests
$multiHandler = Client::createMulti([
    new Request('http://localhost/test1.php', 'POST'),
    new Request('http://localhost/test2.php', 'POST'),
    new Request('http://localhost/test3.php', 'POST')
]);

$running = null;

do {
    $multiHandler->send($running);
} while ($running);

$responses = $multiHandler->getAllResponses();

use Pop\Http\Client;
use Pop\Http\Client\Handler\CurlMulti;

$multiHandler = new CurlMulti();
$client1      = new Client('http://localhost/test1.php', $multiHandler);
$client2      = new Client('http://localhost/test2.php', $multiHandler);
$client3      = new Client('http://localhost/test3.php', $multiHandler);

use Pop\Http\Client;

$promise = Client::postAsync('http://localhost/');

use Pop\Http\Client;

$client  = new Client('http://localhost/');
$promise = $client->postAsync();

use Pop\Http\Client;

$client  = new Client('http://localhost/', ['method' => 'POST']);
$promise = $client->sendAsync();

use Pop\Http\Client;

$client  = new Client('http://localhost/', ['method' => 'POST', 'async' => true]);
$promise = $client->send();

use Pop\Http\Client;

$multiHandler = Client::createMulti([
    'http://localhost/test1.php',
    'http://localhost/test2.php',
    'http://localhost/test3.php'
]);

$promise = $multiHandler->sendAsync();

try {
    $response = $promise->wait();
    print_r($response->getParsedResponse());
} catch (\Exception $e) {
    echo $e->getMessage() . PHP_EOL;
}

$response = $promise->wait(false);
if ($response instanceof Response) {
    print_r($response->getParsedResponse());
}

use Pop\Http\Promise;
use Pop\Http\Client\Response;

$promise->setCancel(function(Promise $promise) {
    // Do something upon cancellation
});

$promise->then(function(Response $response) {
    // Do something on success
})->catch(function(Response $response)) {
    // Do something on failure
})->finally(function(Promise $promise) {
    // Do something at the end
});

$promise->resolve();

use Pop\Http\Client\Response;

// Force resolve
$promise->then(function(Response $response) {
    // Do something on success
}, true);

use Pop\Http\Client;
use Pop\Http\Client\Response;

$promise1 = Client::getAsync('http://localhost/test1.php');
$promise2 = Client::getAsync('http://localhost/test2.php');

$promise1->then(function(Response $response) use ($promise2) {
    // Do something with the first promise response
    return $promise2;
})->then(function(Response $response) {
    // Do something with the second promise response
});

$promise1->resolve();

use Pop\Http\Client;
use Pop\Http\Client\Response;

$promise = Client::getAsync('http://localhost/test1.php');

$promise->then(function(Response $response) {
    $data1   = $response->getParsedResponse();
    $promise = Client::getAsync('http://localhost/test2.php')
        ->then(function(Response $response) use ($data1) {
            $data2 = $response->getParsedResponse();
            // Do something with both the data results from promise 1 and 2.
        }, true);
}, true);

use Pop\Http\Client;

$promise  = Client::postAsync('http://localhost/', ['auto' => true]);
$response = $promise->wait(false); // The response will be the parsed content response

use Pop\Http\Client;

$promise  = Client::postAsync('http://localhost/', ['auto' => true]);
$promise->then(function($response) {
    // The response will be the parsed content response
}, true);

use Pop\Http\Client;

$client = Client::fromCurlCommand('curl -i -X POST -d"foo=bar&baz=123" http://localhost/post.php');
$client->send();

use Pop\Http\Client;

$client = new Client('http://localhost/post.php', [
    'method' => 'POST',
    'data'   => [
        'foo' => 'bar',
        'baz' => 123
    ]
]);

echo $client->toCurlCommand();

$headers = $reqeuest->getHeaders();
if ($request->hasHeader('Content-Type')) {
    $contentType = $request->getHeader('Content-Type');         // Header object
    var_dump($request->getHeaderValueAsString('Content-Type')); // Header value as string
}

$body = $request->getBody();           // Body object
var_dump($response->getBodyContent()); // Get actual content of the body object

$request->isGet();   
$request->isPost();
$request->isPut();
$request->isPatch();
$request->isDelete();
$request->hasFiles();

$queryData  = $request->getQuery(); // GET Request
$postData   = $request->getPost();
$putData    = $request->getPut();
$patchData  = $request->getPatch();
$deleteData = $request->getDelete();
$filesData  = $request->getFiles();
$serverData = $request->getServer();
$envData    = $request->getEnv();

$foo = $request->getQuery('foo'); // GET Request
$foo = $request->getPost('foo');
$foo = $request->getPut('foo');
$foo = $request->getPatch('foo');
$foo = $request->getDelete('foo');
$foo = $request->getFiles('foo');
$foo = $request->getServer('foo');
$foo = $request->getEnv('foo');

$parsedData = $request->getParsedData();
$rawData    = $request->getRawData();

use Pop\Http\Server;

$server = new Server();

echo $server->request->getHeader('Authorization')->getValue();
if ($server->request->isPost()) {
    print_r($server->request->getPost());
}

$server->response->setCode(200)
    ->setMessage('OK')
    ->setVersion('1.1')
    ->addHeader('Content-Type', 'text/plain')
    ->setBody('This is the response');

$server->send();

use Pop\Http\Server;
use Pop\Http\Server\Request;
use Pop\Http\Server\Response;

$myRequest  = new Request();
$myResponse = new Response();
$server     = new Server($myRequest, $myResponse);

use Pop\Http\Server;
use Pop\Http\Server\Reqeust;

$filters = ['strip_tags', 'addslashes'];
$server  = new Server(new Request(null, $filters));

if ($server->request->isPost()) {
    print_r($server->request->getPost());
}

use Pop\Http\Server\Response;

Response::redirect('http://www.newlocation.com/');

use Pop\Http\Server\Response;

Response::forward($clientResponse);

use Pop\Http\Server;

$server = new Server();
$server->response->setCode(200)
    ->setMessage('OK')
    ->setVersion('1.1')
    ->addHeader('Content-Type', 'text/plain')
    ->setBody('This is the response');

echo $server;

use Pop\Http\Server\Upload;

$upload = new Upload('/path/to/uploads');
$upload->setDefaults();

$upload->upload($_FILES['file_upload']);

// Do something with the newly uploaded file
if ($upload->isSuccess()) {
    $file = $upload->getUploadedFile();
} else {
    echo $upload->getErrorMessage();
}

$upload->overwrite(true);

$upload->upload($_FILES['file_upload'], 'my-custom-filename.docx');

$filename = $upload->checkFilename('my-custom-filename.docx');

// $filename is set to 'my-custom-filename_1.docx'
$upload->upload($_FILES['file_upload'], $filename);
bash
curl -i -X POST --header "Authorization: Bearer 1234567890" \
  --data "foo=bar&baz=123" "http://localhost/post.php"