I am currently using the below mentioned code to make http post request and it only returns body. I want the body and headers both. How I can I get body and headers both with file_get_content method or CURL?
$sURL = "url";
$sPD = "data";
$aHTTP = array(
'http' =>
array(
'method' => 'POST',
'header' => "Content-Type: application/atom+xml"
'content' => $sPD
)
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
Try:
$context = stream_context_create($aHTTP);
$stream = fopen($sURL, 'r', false, $context);
$contents = stream_get_contents($stream);
$metadata = stream_get_meta_data($stream);
You can also use the HTTP Functions if available.
Related
Calling GitHub API route like this
$url='https://api.github.com/search/repositories?q=2021-3-1&sort=stars&order=desc';
$content = file_get_contents($url);
but when I try var_dump($content);die(); th result in browser
bool(false)
That's because GitHub expects you to set a User-Agent header, so you need to create a proper context for file_get_contents:
$url = 'https://api.github.com/search/repositories?q=2021-3-1&sort=stars&order=desc';
$opts = [
'http' => [
'method' => 'GET',
'header' => 'User-Agent: MyAgent/1.0',
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
I'm trying to do A GET request to an API but it gives me a 500 Http error.
I tried the same thing on https://reqbin.com/ and it worked without any error
What's the problem in my code?
My code:
$addr = $_GET['addr'];
$api_key = 'secure';
$url = 'https://www.blockonomics.co/api/merchant_order/'.$addr;
$options = array(
'http' => array(
'header' => "Authorization: Bearer $api_key",
)
);
$context = stream_context_create($options);
$contents = file_get_contents($url, false, $context);
$object = json_decode($contents);
You can use this code to catch any error messages:
<?php
$addr = $_GET['addr'];;
$api_key = 'your_api_key';
$url = 'https://www.blockonomics.co/api/merchant_order/'.$addr;
$options = array (
'http' => array (
'header' => "Authorization: Bearer $api_key",
'ignore_errors' => true
)
);
$context = stream_context_create($options);
$contents = file_get_contents($url, false, $context);
$object = json_decode($contents);
if($object->status != 200) {
echo $http_response_header[0]."\n".$contents;
}
This way you will see the error message which tells you what is wrong:
HTTP/1.1 500 Internal Server Error
{"status": 500, "message": "Order not found."}
For 2 days I'm having trouble with my PHP script on my server. I've changed nothing and suddenly it didn't work anymore.
Here is the code:
$query = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n",
'method' => "POST",
'content' => $query,
),
);
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n",'method' => 'POST',
'content' => http_build_query($data),));
$contexts = stream_context_create($opts);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $contexts, -1, 40000);
I'm getting these error messages:
Notice: file_get_contents(): Content-type not specified assuming
application/x-www-form-urlencoded in
Warning: file_get_contents(https://mobile.dsbcontrol.de): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server
Error in
But when I try the script locally it works perfectly.
You are passing $contexts to file_get_contents() and that only contains the User-Agent header in the $opts array. All other headers and options are in the $options array which you add in to $context but aren't using. Try:
$query = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n".
"User-Agent:MyAgent/1.0\r\n",
'method' => "POST",
'content' => $query,
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context, -1, 40000);
While the existing answers did not work for me, I managed to solve the problem like this:
The PHP Manual says params must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.
$header = array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($postdata)
);
$packet['method'] = "POST";
$packet['header'] = implode("\r\n", $header);
$packet['content'] = $postdata;
$transmit_data = array('http' => $packet);
$context = stream_context_create($transmit_data);
i'm using this
$url = '';
$result = json_decode(file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => http_build_query($dataQuery)
)
))), true);
I have this function here:
public static function call($action, array $args)
{
$post_args = array(
'action' => $action,
'args' => $args
);
$stream = json_encode($post_args);
$headers = array(
'Content-type: application/json',
'Accept: application/json',
'Expect:'
);
$userpwd = self::$_user.':'.sha1(sha1(self::$_pass));
$ch = curl_init();
$args = array(
CURLOPT_URL => self::$_url,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $stream,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userpwd
);
curl_setopt_array($ch, $args);
$res = curl_exec($ch);
$data = json_decode($res, true);
if (isset($data) === TRUE
&& empty($data) === FALSE
) {
$res = $data;
}
return $res;
}//end call()
and at the URL where I'm posting, I'm just doing:
echo file_get_contents('php://input');
but getting nothing, even though I do post data. What could be the problem? I'm at a dead end.
Also, why do I need CURLOPT_FOLLOWLOCATION set to TRUE when I'm just posting to a simple virtual host URL on my local machine, not doing any redirects.
EDIT:
tried redoing it with fopen like so:
public static function call($action, array $args)
{
$post_args = array(
'action' => $action,
'args' => $args
);
$stream = json_encode($post_args);
$userpwd = self::$_user.':'.sha1(sha1(self::$_pass));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => array(
"Authorization: Basic ".base64_encode($userpwd),
"Content-type: application/json"
),
'content' => $stream
)
);
$context = stream_context_create($opts);
$res = '';
$fp = fopen(self::$_url, 'r', false, $context);
if($fp){
while (!feof($fp)){
$res .= fread($fp, 128);
}
}
return $res;
}//end call()
no success. The connection works with curl and with fopen, since I pass the status along with result (which is just the php://input stream). Any ideas?
Can you be sure about that curl_exec function ends successfully. Also, why don't you use fopen for this purpose. I have written a JSON RPC client and server. I'm sending requests with fopen, and it works perfect.
$httpRequestOptions =
array(
'http'=>array(
'method'=>'POST',
'header'=>'Content-type: application/json',
'content'=>$requestJSON
)
);
$context = stream_context_create($httpRequestOptions);
// send request
if($fileHandler = #fopen($serverURL, 'r', false, $context)){
I'm not writing the rest. You can use this code I have written.
Found out the problem.
I was calling http://localhost/api, since I thought that it would load the index.php automatically, and then I was going to change the default file name for the folder.
The problem was that I didn't add index.php at the end - I should've called http://localhost/api/index.php.
This way it worked with cURL and with fopen.
Any ideas how to call the API without revealing the filename?
If cURL is unavailable I want to send HTTP requests using fopen. I got the code for a class from a PACKT RESTful PHP book but it does nto work. Any ideas why?
if ($this->with_curl) {
//blah
} else {
$opts = array (
'http' => array (
'method' => "GET",
'header' => array($auth,
"User-Agent: " . RESTClient :: USER_AGENT . "\r\n"),
)
);
$context = stream_context_create($opts);
$fp = fopen($url, 'r', false, $context);
$result = fpassthru($fp);
fclose($fp);
}
return $result;
}
The HTTP context options are laid out here: http://www.php.net/manual/en/context.http.php
The header option is a string, so as #Mob says you should be using \r\n and string concatenation rather than an array. However, user_agent is a valid key, so you could just use that instead.
I'm guessing that the contents of the $auth variable is something along the lines of Authorization: blah - i.e. standard header format?
The below code is a working example. Note that I've changed your fpassthru() (which outputs the content to the browser, and does not store it to $result) to a fread() loop. Alternatively you could have wrapped the fpassthru() call with ob_start(); and $result = ob_get_clean();
<?php
class RESTClient {
const USER_AGENT = 'bob';
}
$url = 'http://www.example.com/';
$username = "fish";
$password = "paste";
$b64 = base64_encode("$username:$password");
$auth = "Authorization: Basic $b64";
$opts = array (
'http' => array (
'method' => "GET",
'header' => $auth,
'user_agent' => RESTClient :: USER_AGENT,
)
);
$context = stream_context_create($opts);
$fp = fopen($url, 'r', false, $context);
$result = "";
while ($str = fread($fp,1024)) {
$result .= $str;
}
fclose($fp);
echo $result;
You're mixing this. Shouldn't it be ::
$opts = array (
'http' => array (
'method' => "GET",
'header' => $auth . "\r\n" . //removed array()
"User-Agent: " . RESTClient :: USER_AGENT . "\r\n" )
)
Here's an example of setting headers from the PHP manual
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);