Skip to content

Instantly share code, notes, and snippets.

@rattrap
Last active August 2, 2021 14:27
Show Gist options
  • Select an option

  • Save rattrap/9604407 to your computer and use it in GitHub Desktop.

Select an option

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;
}
}
@gh-o-st

gh-o-st commented Oct 20, 2014

Copy link
Copy Markdown

You're currently using fopen() regardless of whether or not cURL is activated on the server... (see my fork)

@rattrap

rattrap commented Dec 4, 2014

Copy link
Copy Markdown
Author

Fixed. Thank you!

@gh-o-st

gh-o-st commented Jul 30, 2021

Copy link
Copy Markdown

7 years later and I still use this class for connecting remotely to an API... lol

@rattrap

rattrap commented Aug 2, 2021

Copy link
Copy Markdown
Author

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