Last active
November 5, 2017 18:33
-
-
Save sourovroy/1fba93188470bbe3eefa15cd17533b23 to your computer and use it in GitHub Desktop.
This is a source file of a article about PHP cURL. http://sourov.im/send-http-request-using-php-curl/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
|--------------------------------------------------- | |
| PHP class to send HTTP request in better way | |
|--------------------------------------------------- | |
*/ | |
if(!class_exists('setHTTPRequest')){ | |
class setHTTPRequest | |
{ | |
/** | |
* Protected Properties | |
*/ | |
protected $response; | |
protected $http_code; | |
protected $errno; | |
protected $error; | |
/** | |
* Public Properties | |
*/ | |
public $url; | |
public $http_auth = false; | |
public $auth_method = CURLAUTH_ANY; | |
public $username; | |
public $password; | |
public $headers; | |
public $request_method = 'GET'; | |
public $post_data; | |
/** | |
* Send http request from here | |
*/ | |
public function send() | |
{ | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $this->url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
// Redirect | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_MAXREDIRS, 3); | |
// Authentication | |
if($this->http_auth == true){ | |
curl_setopt($ch, CURLOPT_HTTPAUTH, $this->auth_method); | |
curl_setopt($ch, CURLOPT_USERPWD, $this->username .":". $this->password); | |
} | |
// Headers | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); | |
// Different type of request method | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->request_method); | |
if($this->request_method != 'GET'){ | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->post_data); | |
} | |
$this->response = curl_exec($ch); | |
$this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
$this->errno = curl_errno($ch); | |
$this->error = curl_error($ch); | |
curl_close($ch); | |
}//End of send | |
/** | |
* Get the response | |
*/ | |
public function getResponse() | |
{ | |
return $this->response; | |
} | |
/** | |
* Get HTTP status Code | |
*/ | |
public function getHttpCode() | |
{ | |
return $this->http_code; | |
} | |
/** | |
* Get cURL errors | |
*/ | |
public function getErrors() | |
{ | |
return [ | |
'errno' => $this->errno, | |
'error' => $this->error, | |
]; | |
} | |
}//End of class | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment