PHP code example of ngawidev / nethttp
1. Go to this page and download the library: Download ngawidev/nethttp 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/ */
ngawidev / nethttp example snippets
use Ngawidev\NetHttp\Client;
$client = Client::new()->base('https://api.example.com');
$response = $client->request()
->acceptJson()
->bearer('your-token')
->get('/users')
->send();
echo $response->status; // 200
echo $response->ok(); // true
echo $response->data; // array
use Ngawidev\NetHttp\Client;
$client = Client::new()
->base('https://api.example.com')
->userAgent('MyApp/1.0')
->sslVerify(true)
->defaultTimeout(30)
->maxRedirects(5);
$response = $client->request()
->get('/users')
->send();
$response = $client->request()->get('/data')->send();
$response->status; // int: HTTP status code
$response->success; // bool: true if 2xx
$response->ok(); // bool: true if success
$response->failed(); // bool: true if failed
$response->data; // mixed: decoded JSON or string
$response->error; // ?string: error message
$response->elapsed; // float: time in seconds
$response->url; // string: full URL
$response->requestHeaders; // array: request headers
$response->responseHeaders; // array: response headers
$response = $client->request()
->header('X-Custom', 'value')
->headers([
'X-Api-Key' => 'abc123',
'Accept' => 'text/html',
])
->get('/data')
->send();
// Basic Auth
$client->request()
->basicAuth('username', 'password')
->get('/protected')
->send();
// Bearer Token
$client->request()
->bearer('your-token-here')
->get('/protected')
->send();
$client->request()
->query(['page' => 1, 'limit' => 10])
->get('/users')
->send();
// URL: /users?page=1&limit=10
// JSON
$client->request()
->json(['name' => 'John', 'email' => '[email protected] '])
->post('/users')
->send();
// Form URL Encoded
$client->request()
->form(['username' => 'admin', 'password' => 'secret'])
->post('/login')
->send();
// Multipart Form Data
$client->request()
->multipart(['name' => 'John Doe', 'email' => '[email protected] '])
->post('/upload')
->send();
$response = $client->request()
->multipart(['description' => 'My photo'])
->attach('photo', '/path/to/photo.jpg', 'image/jpeg')
->post('/upload')
->send();
$response = $client->request()
->asFile('/path/to/save/file.zip')
->get('/download/archive.zip')
->send();
// File saved to /path/to/save/file.zip
// HTTP Proxy
$client = Client::new()
->base('https://api.com')
->proxyHttp('127.0.0.1', 8080);
// SOCKS5 Proxy
$client = Client::new()
->base('https://api.com')
->proxySocks5('127.0.0.1', 1080);
// With Auth
$client = Client::new()
->base('https://api.com')
->proxyHttp('127.0.0.1', 8080)
->proxyAuth('user', 'pass');
// Send cookies
$client = Client::new()
->base('https://api.com')
->cookie()
->sendCookie('session', 'abc123')
->sendCookies(['theme' => 'dark', 'lang' => 'id']);
// Cookie jar (read/write)
$client = Client::new()
->base('https://api.com')
->cookieJar('/tmp/cookies.txt');
// Cookie file (read only)
$client = Client::new()
->base('https://api.com')
->cookieFile('/tmp/cookies.txt');
// Enable SSL verification
$client = Client::new()
->base('https://api.com')
->sslVerify(true);
// Disable SSL verification (default)
$client = Client::new()
->base('https://api.com')
->sslVerify(false);
// Default timeout for all requests
$client = Client::new()
->base('https://api.com')
->defaultTimeout(60);
// Per-request timeout
$client->request()
->timeout(10) // total timeout
->connectTimeout(5) // connection timeout
->get('/slow-endpoint')
->send();
$client = Client::new()
->base('https://api.com')
->retry(3, 2000); // 3 retries, 2s delay
$response = $client->request()
->get('/flaky-endpoint')
->send();
$response = $client->request()
->gzip()
->get('/large-data')
->send();
// Response automatically decoded
// Install ext-zstd terlebih dahulu
// pecl install zstd
// Auto decode - user gak perlu ngapa-ngapain
$response = $client->request()
->get('/compressed-data')
->send();
// $response->data sudah decoded otomatis
if (Client::isZstdAvailable()) {
echo "ext-zstd installed\n";
}
// Specific browser (random version)
$client = Client::new('chrome')->base('https://example.com');
// Specific browser + version
$client = Client::new('chrome:150')->base('https://example.com');
// Random version within range
$client = Client::new('chrome:130-150')->base('https://example.com');
// Random browser + random version
$client = Client::new('random')->base('https://example.com');
$client = Client::new('chrome:150');
$profile = $client->getBrowserProfile();
echo $profile->getBrowser(); // "chrome"
echo $profile->getVersion(); // 150
print_r($profile->getHeaders()); // All headers
$client = Client::new('chrome:150')
->base('https://example.com');
// Override User-Agent per-request
$client->request()
->getUserAgent('MyBot/1.0')
->get('/path')
->send();
// Set max redirects
$client = Client::new()
->base('https://api.com')
->maxRedirects(3);
// Or per-request
$client->request()
->maxRedirects(10)
->get('/redirect-chain')
->send();
// Default options for all requests
$client = Client::new()
->base('https://api.com')
->curlOpt([
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_TIMEOUT => 30,
]);
// Per-request options (override defaults)
$client->request()
->curlOpt([
CURLOPT_TIMEOUT => 60,
CURLOPT_POSTFIELDS => null,
])
->get('/endpoint')
->send();
$client = Client::new()->base('https://api.com');
// Before request
$client->before(function ($request, $ch) {
echo "Sending: {$request->getMethod()} {$request->getUrl()}\n";
});
// After request
$client->after(function ($response, $request) {
echo "Got: {$response->status} in {$response->elapsed}s\n";
});
$client->request()->get('/data')->send();
// Enable on client
$client = Client::new()
->base('https://api.com')
->debug();
// Or per-request
$client->request()
->debug()
->get('/data')
->send();
$client = Client::new()->base('https://api.com');
$client->request()->get('/users')->send();
$client->request()->post('/users')->send();
$logs = $client->getLogs();
// [
// ['method' => 'GET', 'url' => 'https://api.com/users', 'status' => 200, 'time' => 0.15],
// ['method' => 'POST', 'url' => 'https://api.com/users', 'status' => 201, 'time' => 0.23],
// ]
$client->clearLogs();
$client = Client::new()->base('https://api.com');
$requests = [
$client->request()->acceptJson()->get('/users'),
$client->request()->acceptJson()->get('/posts'),
$client->request()->acceptJson()->get('/comments'),
];
$results = Client::pool($requests);
foreach ($results as $i => $response) {
echo "Request {$i}: {$response->status}\n";
}
$client = Client::new()->base('https://api.com');
// Block sampai response ready
$response = $client->request()
->acceptJson()
->get('/users')
->async()
->await();
echo $response->status;
$client->request()
->acceptJson()
->get('/users')
->async()
->then(function ($response) {
echo "Success: {$response->status}\n";
})
->catch(function ($error) {
echo "Error: {$error}\n";
})
->await();
$client = Client::new()->base('https://api.com');
$results = Client::asyncPool([
$client->request()->acceptJson()->get('/users'),
$client->request()->acceptJson()->get('/posts'),
$client->request()->acceptJson()->get('/comments'),
])->await();
// Semua request dieksekusi secara parallel
foreach ($results as $i => $response) {
echo "Request {$i}: {$response->status}\n";
}
Client::asyncPool([
$client->request()->acceptJson()->get('/users'),
$client->request()->acceptJson()->get('/posts'),
])
->then(function ($responses) {
// Semua berhasil
echo "All " . count($responses) . " requests succeeded!\n";
})
->catch(function ($error) {
// Ada error
echo "Error: {$error}\n";
})
->await();
use Ngawidev\NetHttp\Exception\RequestException;
try {
$response = $client->request()
->get('/data')
->send();
if ($response->failed()) {
echo "Request failed: {$response->error}\n";
}
} catch (RequestException $e) {
echo "cURL error: {$e->getMessage()}\n";
echo "cURL error detail: {$e->getCurlError()}\n";
}