Skip to content

Instantly share code, notes, and snippets.

@rattrap
Last active August 2, 2021 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rattrap/9604407 to your computer and use it in GitHub Desktop.
Save rattrap/9604407 to your computer and use it in GitHub Desktop.
POST with cURL but failback 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;
}
}
@rattrap
Copy link
Author

rattrap commented Aug 2, 2021

Ha! I'm glad it's still useful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment