What's wrong with this PHP CURL script (integrating Foursquare API)? - php

I am trying to integrate Foursquare API to my website, here is the code:
$curl = curl_init('https://api.foursquare.com/v2/photos/add?v=20181008&oauth_token='.$token.'&photo='.$args['img'].'&venueId='.$title);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
// Decode the response
$data = json_decode($data);
// Verify if the post was published
if ( #$data->meta->code == 200) {
return true;
} else {
return false;
}
But when I run this script on my website and try to post image, it is showing
An error occurred while processing your request

Remove the lines
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
and try a simple
curl_setopt($curl, CURLOPT_POST, false);
You are sending the Request with GET Arguments

This could have multiple reasons.
I can't tell from the error message where exactly it triggers but when the curl fails, you should first investigate if there were any issues with the curl request itself.
Use curl_error for this: http://php.net/manual/de/function.curl-error.php
And are you using the API-Call the correct way?
In the docs POST https://api.foursquare.com/v2/photos/add
theres no $photo param at all.
Also when using POST you should add the parameters via
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
and not as GET-Parameters via URL.

Related

how to call an api via php and get a json file from it

I want to check all of the requested urls and if the url contains "video" folder in it, redirect it to an API file. then the API gives me a json files which only contains "respond:true" or "respond:false". In case of having respond:true in the json file the url must be showed and if the json file contains respond:false a predefined simple 403 page must be showed to the user.
I know that the fist part is possible with a simple code in .htaccess file like this:
RewriteRule ^your/special/folder/ /specified/url [R,L]
But I don't know how to do the second part. I mean how to get the result of API, which is in form of a json file and check it.
You can use CURL..
GET REQUEST
$url = 'http://example.com/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
POST REQUEST
$postdata = array(
'name' => 'Arfan'
);
$url = "https://example.com/api/user/create";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
You can also use file_get_content to get API data.
$json = file_get_contents("$url")
You can execute second part (Calling API and response): Call API using curl and process based on its response:
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, "api_url_here");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$api_response_json = curl_exec($ch);
curl_close($ch);
//convert json to PHP array for further process
$api_response_arr = json_decode($api_response_json);
if($api_response_arr['respond'] == true ){
//code for success here
}else{
// code for false here
}
Please note: Json response from API is depend on API Response, If API is giving response in json format ( can be based on params also ).

Request cUrl in Curl

I have action something like this
public function coordinatAction()
{
$curl = curl_init('https://maps.googleapis.com/maps/api/geocode/json?latlng=30.0000000000,40.0000000000');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $aParams);
//Sending request
$result = curl_exec($curl);
if (false === $result) {
$sResult = curl_error($curl);
};
curl_close($curl);
return $result;
}
And have unit test for this action:
public function coordinatActionTest()
{
$curl = curl_init();
$params = [/** Some Params */]
curl_setopt($curl, CURLOPT_URL, 'http://mysite.local/coordinate'); //path to my action
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$this->assertEquals(200, $httpCode, "Wrong HTTP Response Code");
}
When I execute test I get request "curl in curl" (curl in test call curl in action), but second curl is failed by time out after 5 minutes. If I call just one curl in action it everything ok, but duble curl is timed out. Could any explain why it happens
First make sure that the url is accessible using browser. http://mysite.local/coordinate. You can do it using curl command too to verfiy the link. For example:
curl -XPOST YOUR_URL -d _YOUR_PARAMS
Secondly, it can happen that your server doesn't accept any request without a proper user-agent string. I'ld recommend you to use CURLOPT_USERAGENT option with your curl test (with any browser like Opera or Mozila).
Finally, check your server's httpd.conf file and see what are the other parameters mandatory for an incoming request.

Displaying curl data, blank page

I'm trying to download json data using curl in PHP from companies house API.
Here is the example they provide that I'm trying to use:
https://developer.companieshouse.gov.uk/api/docs/company/company_number/readCompanyProfile.html#here
The example:
curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON: https://api.companieshouse.gov.uk/company/{company_number}
My code
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.companieshouse.gov.uk/company/01000000");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'curl -u8yUXrestOfmyApiKey:'
));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($curl);
if(false == $result){
echo curl_error($curl);
}
curl_close($curl);
print($result);
?>
Using header:
'-u my_api_key:8yUXGgcHznjaNWnKpuKIJ7yv7HDvU_slH273GuF1'
I get 400 - bad request and with header in my code above I get nothing no errors blank page no data.
PS. There is a company with number 01000000 I've checked
You shuld add CURLOPT_USERPWD
curl_setopt($curl, CURLOPT_USERPWD, "YOUR API KEY"); #Add your api key

How to make a call to .aspx https from php script from my localhost with xamp?

I am trying to send SMS from my localhost with xamp installed.
Requested page is on https and an .aspx page.
I am getting error: "HTTP Error 400. The request is badly formed." or blank page only in some cases.
Detaisl is as follows :
$url = 'https://www.ismartsms.net/iBulkSMS/HttpWS/SMSDynamicAPI.aspx';
$postArgs = 'UserId='.$username.
'&Password='.$password.
'&MobileNo='.$destination.
'&Message='.$text.
'&PushDateTime='.$PushDateTime.
'&Lang='.$Lang;
function getSslPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$response = getSslPage($all);
echo "<pre>";
print_r($response); exit;
I tried every possible solution/combination found on internet but could not resolve that. The API developers do not have a example for php script.
I tried httpful php library and file_get_contents function but getting empty page. Also tried every combination with curl_setup.
I need to call this url without any post data and see the response from it.
Instead getting a blank page.
Please note that when I execute the url with all details in browser it works fine.
Can anybody help me in this regard.
Thank you,
Usman
First do urlencode over your data as follows:
$postArgs = 'UserId='. urlencode($username.
'&Password='.urlencode($password).
'&MobileNo='.urlencode($destination).
'&Message='.urlencode($text).
'&PushDateTime='.urlencode($PushDateTime).
'&Lang='.urlencode($Lang);
After that two possible solutions. One is using GET.
curl_setopt($ch, CURLOPT_URL, $url . "?" . $postArgs);
Second option is using POST method.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);

JIRA Update custom fields using REST, PHP and cURL

I am trying to update some custom fields using the REST API and PHP/cURL.
I'm wondering if I might have edited something without realizing it, while what I have below "worked" yesterday (I think), it does not work now.
I get varying responses using the different "methods", from:
I get this one using the POST method, as it is uncommented below.
HTTP 405 - The specified HTTP method is not allowed for the requested
resource ().
I get this one if I use the commented-out PUT method, with POST commented out.
{"status-code":500,"message":"Read timed out"}
And this one mixing and matching PUT and POST.
{"errorMessages":["No content to map to Object due to end of input"]}
What am I missing/doing wrong? I am using the following code:
<?php
$username = 'username';
$password = 'password';
$url = "https://example.com/rest/api/2/issue/PROJ-827";
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json'
);
$test = "This is the content of the custom field.";
$data = <<<JSON
{
"fields": {
"customfield_11334" : ["$test"]
}
}
JSON;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Also tried, with the above two lines commented out...
// curl_setopt($ch, CURLOPT_PUT, 1);
// curl_setopt($ch, CURLOPT_INFILE, $data);
// curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
echo $result;
}
curl_close($ch);
?>
The problem here is that PHP's cURL API is not particularly intuitive.
You might think that because a POST request body is sent using the following option
that a PUT request would be done the same way:
// works for sending a POST request
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// DOES NOT work to send a PUT request
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_PUTFIELDS, $data);
Instead, to send a PUT request (with associated body data), you need the following:
// The correct way to send a PUT request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Note that even though you're sending a PUT request, you still have to use the CURLOPT_POSTFIELDS
option to send your PUT request body. It's a confusing and inconsistent process, but it's what you've
got if you want to use the PHP cURL bindings.
According to the relevant manual entrydocs, the CURLOPT_PUT option seems to only work for PUTting a file directly:
TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
A better option IMHO is to use a custom stream wrapper for HTTP client operations. This carries the
added benefit of not making your application reliant on the underlying libcurl library. Such an
implementation is beyond the scope of this question, though. Google is your friend if you're interested
in developing a stream wrapper solution.

Categories