Skip to content

Instantly share code, notes, and snippets.

@gh-o-st
Forked from rattrap/Request.php
Created October 20, 2014 15:53
Show Gist options
  • Select an option

  • Save gh-o-st/ab8c8b8123ac112318eb to your computer and use it in GitHub Desktop.

Select an option

Save gh-o-st/ab8c8b8123ac112318eb to your computer and use it in GitHub Desktop.
POST with cURL but fallback to fopen
<?php
class Request {
/**
* do_post
* POST request
*
* @access public
* @param string $url - url
* @param array $data - post data
* @return string
*/
public function do_post($url, $data = array()) {
if($this->has_curl()) {
return $this->do_post_curl($url, $data);
} else {
return $this->do_post_fopen($url, $data);
}
}
/**
* has_curl
* Does the server have the curl extension ?
*
* @access protected
* @return boolean
*/
protected function has_curl() {
return function_exists('curl_init');
}
/**
* do_post_curl
* POST request with curl
*
* @access protected
* @param string $url - url
* @param array $data - post data
* @return string
*/
protected function do_post_curl($url, $data = array()) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
return $contents;
}
/**
* do_post_fopen
* POST request with fopen
*
* @access protected
* @param string $url - url
* @param array $data - post data
* @return string
*/
protected function do_post_fopen($url, $data = array()) {
$stream = fopen($url, 'r', false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query(
$data
)
)
)));
$contents = stream_get_contents($stream);
fclose($stream);
return $contents;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment