OK so after struggling for a while trying to get cURL to fetch a password protected XML file, and getting absolutely nothing from it, I tried dumbing down my code to see what would work. It turns out nothing. Here's my code:
$ch = curl_init("www.google.com");
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($ch);
curl_close($ch);
And cURL is SILENT. I mean nothing prints to the page. I definitely have it enabled, my phpinfo looks like this:
cURL support enabled
cURL Information libcurl/7.16.0 OpenSSL/0.9.8a zlib/1.2.3
Running php 5.2 on a Windows NT server. Any suggestions?
The key is in this line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
You're telling cURL to return the result of the transfer instead of echoing it (the default). So either remove that line, or do something like this:
$result = curl_exec($ch);
if ($result === false) {
echo "Error: " . curl_error($ch);
} else {
echo $result;
}
If you're getting an SSL error as you point out in your comments, you can set another option on the cURL handle to disable checking the certificate:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
Related
I'm trying to do the bare minimum, just to get it working.
Here is my Google Script:
function doPost(e) {
return ContentService.createTextOutput(JSON.stringify(e.parameter));
}
Here is my PHP code:
$url = 'https://script.google.com/a/somedomain.com/macros/s/### script id ###/exec';
$data['name'] = "Joe";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
$error = curl_error($ch);
Executing this, $result is true.
If I uncomment the CURLOPT_RETURNTRANSFER line, $result =
<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Bad Request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>
$error is always empty.
I would use doGet() but I need to send some rather large POSTs that will exceed what GET can handle.
How can I post to a Google script and return data?
------ UPDATE ------
I've just learned my lead developer tried this some time ago and concluded doPost() errors when returning so apparently it's not just me. My take is that Google is simply not reliable enough to use. I would love for someone to prove me wrong.
------ UPDATE 2 - THE FIX ---------
Apparently this was the problem:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
needs to be:
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
No idea why http_build_query() caused it to error.
Try reading the documentation for CURLOPT_POSTFIELDS and you'll see that is says To post a file, prepend a filename with # and use the full path. That looks what you are trying to do. Note that in php 5.5, the CURLFile class was introduced to let you post files.
If you are using php 5.5 or later, you might try this:
$url = 'https://script.google.com/a/somedomain.com/macros/s/### script id ###/exec';
// create a CURLFile object:
$cfile = new CURLFile('file.pdf','application/pdf'); // you can also optionally use a third parameter
// your POST data...you may need to add other data here like api keys and stuff
$data = array("fileName" => $cfile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
// FROM THE DOCS:
// If value is an array, the Content-Type header will be set to multipart/form-data (so you might skip the line above)
// As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix
// As of PHP 5.5.0, the # prefix is deprecated and files can be sent using CURLFile
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set this to TRUE if you want curl_exec to retrieve the result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
if ($result === FALSE) {
echo "The result is FALSE. There was a problem\n";
$error = curl_error($ch);
var_dump($error);
die();
} else {
echo "success!\n";
var_dump($result);
}
// this can give you more information about your request
$info = curl_getinfo($ch);
if ($info === FALSE) {
echo "curlinfo is FALSE! Something weird happened";
}
var_dump($info); // examine this output for clues
EDIT: If you are not getting any error, and $result comes back with something like "Bad Request" then you will need to inspect the result more closely to find out what the problem is. A well-behaved API should have informative information to help you fix the problem. If the API doesn't tell you what you did wrong, you can examine the curlinfo you get from these commands:
$info = curl_getinfo($ch);
var_dump($info); // examine this output for clues
if $result and $info don't tell you what you've done wrong, try reading the API documentation more closely. You might find a clue in there somewhere.
If you can't figure out what the problem is using these tactics, there's not much else you can do with your code. You'll need more information from the maintainers of the API.
You need to look at your HTTP Request header to see what is actually being posted.
When trouble shooting I add these options:
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_ENCODING,"");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
CURLINFO_HEADER_OUT will add "request_header" to curl_getinfo()
You also want to look at these curl_getinfo() elements.
request_size
size_upload
upload_content_length
request_header
I recently uploaded my project from localhost to a live hosting server. In my project I have used a CURL request, which worked absolutely fine on localhost up til now.
As soon as I moved it on live server (Arizonawebservices.com), that CURL request stopped working. When my page sends the CURL request, it keeps on processing and never returns any output.
I checked server for CURL support (using "which curl" command in PHP's exec() function), and yes it has CURL support enabled.
Also created a test page for manually shooting CURL requests and check if it works ok. Tried www.google.com, www.yahoo.com, and many other URLs, all are working fine, but when I put my original API URL "https://dataviz.sandbox.rcoanalytics.com:10105/oauth/token" in it. It starts behaving like before. I am completely unable to get any response from that CURL request. Any help would be appreciated.
Used following code for testing purpose:
function httpPost($url,$params)
{
$postData = '';
if (!empty($params)) {
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
$postData = rtrim($postData, '&');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
if ($postData != "") {
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$output=curl_exec($ch);
if($output === false)
{
echo "Error Number:".curl_errno($ch)."<br>";
echo "Error String:".curl_error($ch);
}
curl_close($ch);
return $output;
}
$params = array(
);
echo httpPost("https://dataviz.sandbox.rcoanalytics.com:10105/oauth/token", $params);
The url has an SSL error, so in the cURL request when cURL tries to verify the host it blocks you from accessing the address.
use the following:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
This is obviously insecure method to access the URL but for a host like this one it will do the trick.
I am trying to connect to an echosign api which used to work and now has suddenly stop working, I have tried debugging but can't seem to resolve it, this is my code
public function get_access_token_get()
{
$echoSign = new EchoSign();
$ch = curl_init('https://secure.echosign.com:443/api/rest/v2/auth/tokens');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($echoSign->echosign_creds));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = json_decode(curl_exec($ch));
curl_close($ch);
echo "<pre>"; print_r($result); echo "</pre>"; exit();
return $result->accessToken;
}
I have tested your curl code with other urls, and its working fine for them, then i tried to call your url with other curl methods and it gives empty response, so I believe you should check with the echosign support to see whats wrong.
I am trying to fire a HTTP GET request on a secured URL which asks for username and password. This is fine when I am using that from browser but I am not sure how to do that using PHP.
I have tried using the two methods:
1) Using Curl as suggested in here: Make a HTTPS request through PHP and get response
2) Using the file_get_contents as suggested in here: How to send a GET request from PHP?
But the first one didn't give me any response back. And the second one gave me the following error:
failed to open stream: HTTP request failed
And this is my code for the curl:
$url="https://xxxxx.com";
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
and for the file_get_contents:
$url="https://xxxx.com";
$response=file_get_contents($url);
echo $response;
The URL will return a XML response for a API I am testing. Can someone point me to the right direction?
Thanks!
If we focus on the requirement to send a username and password because I suspect that's your main problem, try this
$ch = curl_init();
$url="https://xxxxx.com";
// OR - check with your server's operator
$url="http://xxxxx.com";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// or maybe
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// - see http://stackoverflow.com/questions/4753648/problems-with-username-or-pass-with-colon-when-setting-curlopt-userpwd
// check the cURL documentation
$output = curl_exec($ch);
$info = curl_getinfo($ch);
// don't forget to check the content of $info, even a print_r($info) is better
// than nothing during debug
curl_close($ch);
I'm having dificulties to query a webform using CURL with a PHP script. I suspect, that I'm sending something that the webserver does not like. In order to see what CURL realy sends I'd like to see the whole message that goes to the webserver.
How can I set-up CURL to give me the full output?
I did
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
but that onyl gives me a part of the header. The message content is not shown.
Thanks for all the answers! After all, they tell that It's not possible. I went down the road and got familiar with Wireshark. Not an easy task but definitely worth the effort.
Have you tried CURLINFO_HEADER_OUT?
Quoting the PHP manual for curl_getinfo:
CURLINFO_HEADER_OUT - The request string sent. For this to work, add
the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
If you are wanting the content can't you just log it? I am doing something similar for my API calls
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::$apiURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, count($dataArray));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$logger->info("Sending " . $dataString);
self::$results = curl_exec($ch);
curl_close($ch);
$decoded = json_decode(self::$results);
$logger->debug("Received " . serialize($decoded));
Or try
curl_setopt($ch, CURLOPT_STDERR, $fp);
I would recommend using curl_getinfo.
<?php
curl_exec($ch);
$info = curl_getinfo($ch);
if ( !empty($info) && is_array($info) {
print_r( $info );
} else {
throw new Exception('Curl Info is empty or not an array');
};
?>