Send custom HTTP headers AND get response header - curl - php

I'm trying to curl (in PHP) a URL and send a custom header in the request. But then I also need to be able to view the response header that is returned. I'm querying an external API that I don't control.
I've tried using both the CURLOPT_HTTPHEADER and CURLOPT_HEADER options but they don't seem to work well together. CURLOPT_HEADER seems to overwrite the request headers so I can't authenticate my request BUT I then can view the headers in the response. If I take CURLOPT_HEADER out, I can successfully authenticate, but can't view headers.
PHP Code:
$url = "http://url-goes-here";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$headers = array("X-Auth-Token: $token");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 1);
$out = curl_exec($ch);
curl_close($ch);

As per the documentation, it has to be
curl_setopt($ch, CURLOPT_HEADER, 1); // or TRUE
instead of
curl_setopt($ch, CURLOPT_HEADER, $headers);
EDIT: I must say I can't replicate the issue. I've created two scripts: a.php (using your content, with $url changed to 'http://localhost/b.php') and b.php (queried by a.php) which contains this:
<?php
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
So when I run php a.php, I get this:
HTTP/1.1 200 OK
Date: Tue, 16 Feb 2016 02:42:45 GMT
Server: Apache/2.4.10 (Fedora) PHP/5.6.15
X-Powered-By: PHP/5.6.15
Content-Length: 50
Content-Type: text/html; charset=UTF-8
Host: localhost
Accept: */*
X-Auth-Token: xxx
Which means I'm 1) getting the response headers successfully, and 2) receiving them successfully as well from a.php. I'd suggest you trying something similar and see if your web server (or your application) is playing tricks with you.

Related

PHP cURL not sending headers (?)

I attempted to modify the code I found on this webpage: https://tutorialsclass.com/php-rest-api-get-data-using-curl/
The API I'm using needs two custom headers: Accept-Encodig and x-api-key.
My modified code looks like this:
$curl_handle = curl_init();
$url = "http://thelinktomyAPI";
$headers = array(
'Accept-Encoding: application/json',
'Content-Type: application/json',
'x-api-key: MyLongAPIKey'
);
// Set the curl URL option
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_HEADER, true);
curl_setopt($curl_handle, CURLOPT_ENCODING, 'application/json');
// This option will return data as a string instead of direct output
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
$curl_data = curl_exec($curl_handle);
if ($curl_data === false)
{
print_r('Curl error: ' . curl_error($curl_handle));
}
curl_close($curl_handle);
print_r($curl_data);
So as you can see I'm making my headers visible to make sure I'm actually sending them. What I get shown is a webpage with the following:
HTTP/1.1 302 Moved Temporarily Date: Thu, 02 Dec 2021 08:09:59 GMT
Content-Type: text/html Content-Length: 110
Connection: keep-alive
Location: http://thelinktomyAPI
X-Trace-ID:f306fe34-079b-493c-b5db-073e792ec2a1
X-Kong-Response-Latency: 0
Server: kong/2.3.3 302 Found
Since the Content-Type is shown as "text/html" it leads me to believe that my headers aren't sent at all, hence I'm not getting any data. I'd appreciate any help.
Edit Adding curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true); as Professor Abronsius suggested helped!

Get jsonRPC data with PHP curl,

Setting up a JSON-RPC on my vps which I want to connect via PHP CURL on my website doing a basic request and looking for getmasternodecount.
Tried many scripts and libraries before however none seems to work in my case. Now I try to write some basic php code, but this skill isnt my best.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
function coinFunction () {
$feed = 'http://user:pass#ip/';
$post_string = '{"method": "getmasternodecount", "params": []}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feed);
curl_setopt($ch, CURLOPT_PORT, port);
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/stratum', 'Content-length: '.strlen($post_string)));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json', 'Content-length: '.strlen($post_string)));
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$data = coinFunction();
var_dump($data);
echo $data;
?>
And gives me this data dump:
string(127) "HTTP/1.1 403 Forbidden Date: Sun, 24 May 2020 00:06:21 GMT Content-Length: 0 Content-Type: text/html; charset=ISO-8859-1 " HTTP/1.1 403 Forbidden Date: Sun, 24 May 2020 00:06:21 GMT Content-Length: 0 Content-Type: text/html; charset=ISO-8859-1
When i delete all the var dump information etc, it send me a whitepage and sometimes NULL.
Kindly Regards,
Let's work with the first snippet. Since it's a POST request, file_get_contents is rather out of place here. Add the following setopt lines:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
Without those, the result of curl_exec won't contain the returned content.
It would also be advisable to specify the Content-Type of the request (which is application/json). The server might handle it even without, but just in case:
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json'));
Authentication is another thing. Credentials in the URL suggest Basic, but the server might expect otherwise... See CURLOPT_HTTPAUTH.

Handling HTTP headers sent with curl

I'm currently trying to implement oAuth on a server side in order to provide an API for developers. I'm experiencing a very easy issue. I want to be able to handle HTTP headers sent to a script called request.php.
I have no idea how I can do that. I'm a coding a wrapper for clients, and try to make http call on request.php with curl.
$data = array('name' => 'Foo');
$header = array('Content-type: text/plain', 'Content-length: 100');
$ch = curl_init("test");
curl_setopt($ch, CURLOPT_URL, 'http://localhost/api/request.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$res = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
So, in $headers I received the http responses headers but what I want to do is handling headers received by request.php.
You should use
curl_setopt($s, CURLOPT_HEADER, true);
this will cause $res in you code to have both the headers and the data seperated by 2 CRLF (4 chars in total as defined in HTTP standards).
HTTP Response example,
HTTP/1.0 302 Found
Content-Type: text/html; charset=UTF-8
Content-Length: 11782
Date: Tue, 13 Dec 2011 15:07:19 GMT
Server: GFE/2.0
<!DOCTYPE html>
<html>
(...)
</html>
Use curl_getinfo to read headers.
It is not necessary to set (CURLOPT_HEADER, true) to do this.
For example:
...
curl_setopt($this->ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($this->ch);
$httpCode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);

Problem when posting a file with curl in php

I'm trying to post a file with curl in php, but the file is never uploaded/accepted by the server. I have searched and tried for several hours, but I can't find whats wrong, everyone elses examples and codes seems to work, but not this one.
Here is the code:
<?php
$url = "http://jpptst.ams.se/0.52/default.aspx";
$headers = array(
"Content-Type: text/xml; charset=iso-8859-1",
"Accept: text/xml"
);
$data = array("file" => "#documents/xmls/1298634571.xml");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>
The result I get:
string(904) "HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Mon, 25 Jul 2011 19:13:41 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 659"
Thats all I get.. the file is never accepted by the server.
If anyone can help me with this problem it would be much appreciated :)
Thanks!
You're trying to upload a file via HTTP post, so sending a Content-type: text/xml header is inappropriate. An HTTP file upload is actually done as multipart/form-data, and is actually pretty much identical to a MIME-encoded email attachment. PHP's curl will fill in the header details for you automatically. As well, the Accept header is not necessary either.
Check that the path to the .xml file you're trying to upload is correct. You've not specified a leading / to it, so the path is relative to where your PHP script is executing from.
Replace:
$data = array("file" => "#documents/xmls/1298634571.xml");
With this:
$data = array("file" => "#".realpath('documents/xmls/1298634571.xml'));
Try it, might work, i'm not sure tho.
EDIT:
Try this out:
<?php
$xmldatafile="documents/xmls/1298634571.xml"; // Make sure the file path is correct
function postData($postFields,$url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST ,1);
curl_setopt($ch, CURLOPT_POSTFIELDS ,$postFileds);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$xmlData = file_get_contents($xmldatafile);
$postFileds = 'data='.$xmlData;
$result = postData($postFields,"http://jpptst.ams.se/0.52/default.aspx");
?>

PHP Curl, error: Browser must support session cookies?

I am getting an error on the browser saying:
HTTP/1.1 500 Internal Server Error Date: Fri, 06 May 2011 20:25:28 GMT Server: IBM_HTTP_Server/6.0.2.43 Apache/2.0.47 (Unix) $WSEP: Set-Cookie: JSESSIONID=0000HpGRXpuwrdY_u0k-ecHKAFK:14ekdcv70; Path=/ Connection: close Transfer-Encoding: chunked Content-Type: text/html;charset=ISO-8859-1 Content-Language: en Error 500: Browser must support session cookies.
How to solve this problem?
here what I did:
session_start();
$postData = http_build_query($_GET);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "\BuiltinObjectToken-VerisignClass3PublicPrimaryCertificationAuthority.crt");
curl_setopt($ch, CURLOPT_URL, "https://zzzzzz.zzzzz.co.uk/zzz/zzzz/" . $form_link );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataCapcha);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$PagaeCapcha = curl_exec($ch);
exit($PagaeCapcha);
Set-Cookie: JSESSIONID=0000HpGRXpuwrdY_u0k-ecHKAFK:14ekdcv70; Path=/
This is the response header which initially sets a session cookie. This one will not get stored in your cookiefile jar. It's a temporary cookie, and you are throwing it away.
You will have to first issue a requesting request that points to the e.g. homepage. And only afterwards send the actual data request to the desired endpoint /zzz/zzzz/.
Problem is that you're sending the name of the session that YOUR copy of PHP has created. This is almost certainly not the name of the session that the .co.uk server has created. So it's seeing that as your "browser" not supporting cookies - it tries to set a session cookie named 'JSESSIONSID', but you send back a cookie named 'PHP_SESSID' (or whatever).

Categories