Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP CURL POST example
<?php
$url = 'http://google.com';
if ($argc > 1){
$url = $argv[1];
}
$ch=curl_init();
// user credencial
curl_setopt($ch, CURLOPT_USERPWD, "username:passwd");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
<?php
class Log {
public static function debug($str) {
print "DEBUG: " . $str . "\n";
}
public static function info($str) {
print "INFO: " . $str . "\n";
}
public static function error($str) {
print "ERROR: " . $str . "\n";
}
}
function Curl($url, $post_data, &$http_status, &$header = null) {
Log::debug("Curl $url JsonData=" . $post_data);
$ch=curl_init();
// user credencial
curl_setopt($ch, CURLOPT_USERPWD, "username:passwd");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
// post_data
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
if (!is_null($header)) {
curl_setopt($ch, CURLOPT_HEADER, true);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
Log::debug('Curl exec=' . $url);
$body = null;
// error
if (!$response) {
$body = curl_error($ch);
// HostNotFound, No route to Host, etc Network related error
$http_status = -1;
Log::error("CURL Error: = " . $body);
} else {
//parsing http status code
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (!is_null($header)) {
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
} else {
$body = $response;
}
}
curl_close($ch);
return $body;
}
$url = "http://requestb.in/1h1tct81";
$json = "{\"name\" : \"UserName\", \"age\" : 12 }";
$ret = Curl($url, $json, $http_status);
var_dump($ret);
@ukiKwon

This comment has been minimized.

Copy link

@ukiKwon ukiKwon commented Sep 11, 2017

thank you !

@bellib

This comment has been minimized.

Copy link

@bellib bellib commented Jan 31, 2018

Log::error() where !!
thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.