PHP code example of tg111 / php-request

1. Go to this page and download the library: Download tg111/php-request 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/ */

    

tg111 / php-request example snippets


use PhpRequest\PhpRequest;

// Simple GET request
$response = PhpRequest::get('https://httpbin.org/get');
echo $response->text();

// GET with parameters
$response = PhpRequest::get('https://httpbin.org/get', [
    'key1' => 'value1',
    'key2' => 'value2'
]);

// POST with data
$response = PhpRequest::post('https://httpbin.org/post', [
    'username' => 'user',
    'password' => 'pass'
]);

// JSON POST
$response = PhpRequest::post('https://httpbin.org/post', [
    'name' => 'John Doe',
    'email' => '[email protected]'
], [
    'headers' => ['Content-Type' => 'application/json']
]);

// Alternative syntax using global functions
$response = requests_get('https://httpbin.org/get');
$response = requests_post('https://httpbin.org/post', ['key' => 'value']);

$response = PhpRequest::get('https://api.example.com/data', [], [
    'headers' => [
        'Authorization' => 'Bearer your-token-here',
        'Accept' => 'application/json',
        'User-Agent' => 'MyApp/1.0'
    ],
    'timeout' => 30
]);

$response = PhpRequest::get('https://httpbin.org/cookies', [], [
    'cookies' => [
        'session_id' => 'abc123456789',
        'user_preference' => 'dark_mode'
    ]
]);

use PhpRequest\PhpRequest;

// Create a session
$session = PhpRequest::session()
    ->setHeaders([
        'Authorization' => 'Bearer token123',
        'Accept' => 'application/json'
    ])
    ->setCookies([
        'session_id' => 'session123'
    ])
    ->setTimeout(60);

// Use the session for multiple requests
$profile = $session->get('/user/profile');
$settings = $session->get('/user/settings');
$updated = $session->post('/user/update', ['name' => 'New Name']);

// Basic authentication
$session = PhpRequest::session()->auth('username', 'password');

// Bearer token
$session = PhpRequest::session()->bearerAuth('your-token');

// Custom header authentication
$session = PhpRequest::session()->setHeader('API-Key', 'your-api-key');

use PhpRequest\PhpRequest;
use RequestsLike\RequestException;

try {
    $response = PhpRequest::get('https://api.example.com/data');
    
    if ($response->ok()) {
        $data = $response->json();
        // Process successful response
    } else {
        // Handle HTTP error status codes
        echo "HTTP Error: " . $response->getStatusCode();
    }
    
} catch (RequestException $e) {
    // Handle network errors, timeouts, etc.
    echo "Request failed: " . $e->getMessage();
}

$response = PhpRequest::get('https://httpbin.org/json');

// Get response content
$text = $response->text();           // Raw text content
$data = $response->json();           // Parse JSON response
$code = $response->getStatusCode();  // HTTP status code

// Check response status
$success = $response->ok();          // True for 2xx status codes
$isClientError = $response->isClientError(); // True for 4xx codes
$isServerError = $response->isServerError(); // True for 5xx codes

// Get headers and metadata
$headers = $response->getHeaders();
$contentType = $response->getContentType();
$totalTime = $response->getTotalTime();
$url = $response->getUrl();

// Save response to file
$response->save('/path/to/file.json');

$response = PhpRequest::post('https://httpbin.org/post', [
    'file' => new CURLFile('/path/to/file.txt'),
    'description' => 'File upload test'
], [
    'headers' => ['Content-Type' => 'multipart/form-data']
]);

class ApiClient
{
    private $session;
    
    public function __construct($apiKey, $baseUrl = 'https://api.example.com')
    {
        $this->session = RequestsLike::session()
            ->setBaseUrl($baseUrl)
            ->setHeaders([
                'Authorization' => "Bearer $apiKey",
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ])
            ->setTimeout(30);
    }
    
    public function getUser($id)
    {
        $response = $this->session->get("/users/$id");
        return $response->ok() ? $response->json() : null;
    }
    
    public function createUser($userData)
    {
        $response = $this->session->post('/users', $userData);
        return $response->ok() ? $response->json() : null;
    }
}

// Usage
$client = new ApiClient('your-api-key');
$user = $client->getUser(123);
$newUser = $client->createUser(['name' => 'John', 'email' => '[email protected]']);
bash
composer