π™π™£π™§π™šπ™–π™‘ π˜Ύπ™€π™™π™šπ™§
1.64K subscribers
6 photos
7 files
34 links
A place for coders ;)
Download Telegram
#php #curl

Handle requests using Curl

class Request {
private $config = [];

public function __construct($config = []) {
$this->config = $config;
}

public function get($url) {
return $this->sendRequest($url, 'GET');
}

public function post($url, $headers = [], $payload = [], $store_cookies = true) {
return $this->sendRequest($url, 'POST', $headers, $payload, $store_cookies);
}

public function custom($url, $method, $headers = [], $payload = []) {
return $this->sendRequest($url, $method, $headers, $payload);
}

private function sendRequest($url, $method, $headers = [], $payload = [], $store_cookies = false) {
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

// Add additional configuration options
foreach ($this->config as $option => $value) {
curl_setopt($curl, $option, $value);
}

if ($store_cookies) {
$cookieFile = tempnam(sys_get_temp_dir(), 'cookies');
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookieFile);
}

if ($method === 'POST') {
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
}

$response = curl_exec($curl);
$error = curl_error($curl);

curl_close($curl);

if ($error) {
throw new Exception("Request failed: " . $error);
}

return $response;
}
}

// Usage example:
$request = new Request(["timeout" => 300]);

$response = $request->get($url);
echo $response;

$response = $request->post($url, $headers, $payload, true);
echo $response;

$response = $request->custom($url, $method, $headers, $payload);
echo $response;


Remember notes: private is a keyword.

private $config;
private function uneeq(){
}

Whenever you use private keyword the the variables, functions will become private and you can't use these outside of the class.
πŸ‘1