Last active
March 8, 2022 18:33
-
-
Save guimadaleno/9359569 to your computer and use it in GitHub Desktop.
PHP function to send GET/POST requests without 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 | |
# Function | |
function post_without_curl ($url, $data, $optional_headers = null) | |
{ | |
$params = array('http' => array | |
( | |
'method' => 'POST', | |
'content' => http_build_query($data, "", "&") | |
)); | |
if ($optional_headers !== null): | |
$params['http']['header'] = $optional_headers; | |
endif; | |
$ctx = stream_context_create($params); | |
$fp = @fopen($url, 'rb', false, $ctx); | |
if (!$fp): | |
throw new Exception("Problem with $url, $php_errormsg"); | |
endif; | |
$response = @stream_get_contents($fp); | |
if ($response === false): | |
throw new Exception("Problem reading data from $url, $php_errormsg"); | |
endif; | |
return $response; | |
} | |
# Usage | |
$response = post_without_curl ("http://www.domain.com/page.php", array | |
( | |
'field1' => "bla bla bla", | |
'field2' => 123 | |
)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment