Last active
August 2, 2021 14:27
-
-
Save rattrap/9604407 to your computer and use it in GitHub Desktop.
POST with cURL but failback to fopen
This file contains hidden or 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 | |
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; | |
} | |
} |
Fixed. Thank you!
7 years later and I still use this class for connecting remotely to an API... lol
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
You're currently using fopen() regardless of whether or not cURL is activated on the server... (see my fork)