CSV file upload in Php using curl - php

I am using Php as a frontend and Java as a backend. I have created an Post API for uploading file and using curl for api request.
I have hit my Api using Postman at that time it works fine but i am facing prodblem when i request api using Curl i don't eble to get what i am doing wrong.
Here is the curl requested data :-
$data2 = array(
'file' =>
'#' . $data1->file->tmp_name
. ';filename=' . $data1->file->name
. ';type=' . $data1->file->type
);
This is how i am sending curl request:-
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch,CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HEADER, 1); //parveen
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //parveen
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data2);
$headers = array(
'Content-Type:'.$this->service->contentType,
'Launcher:'.$this->serverName,
'domain:'.$this->service->domain,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$this->responseBody=curl_exec($ch);
Links where i find this solution:-
enter link description here
I search a lot to find the solution but nothing is worked for me so please help me .
Thanks

the way you're trying to upload the file hasn't been supported since the PHP5 days, and even in 5.5+ you'd need CURLOPT_SAFE_UPLOAD to upload with #. use CURLFile when uploading files, like
$data2 = array(
'file' => new CURLFile($data1->file->name,$data1->file->type,$data1->file->tmp_name)
);
also, don't use CURLOPT_CUSTOMREQUEST for POST requests, just use CURLOPT_POST. (this is also true for GET requests and CURLOPT_HTTPGET )
also, check the return value of curl_setopt, if there was a problem setting your option, it returns bool(false), in which case you should use curl_error() to extract the error message. use something like
function ecurl_setopt($ch,int $option,$value){
if(!curl_setopt($ch,$option,$value)){
throw new \RuntimeException('curl_setopt failed! '.curl_error($ch));
}
}
and protip, whenever you're debugging curl code, use CURLOPT_VERBOSE, it prints lots of useful debugging info

Related

How to use an array in an API using curl

I am trying to access the cdnify API to purge cache for an individual file ( https://cdnify.com/learn/api#purgecache )
This is my current code
$cdn_api_user = env('CDNIFY_API');
$cdn_api_password = env('CDNIFY_API_PASS');
$cdn_api_resource = env('CDNIFY_API_RESOURCE');
$cdnifyapicacheurl = 'https://' . $cdn_api_user . ':' . $cdn_api_password . '#' . 'cdnify.com/api/v1/resources/' . $cdn_api_resource . '/cache';
return print $cdnifyapicacheurl;
$fields = array(
'files' => $storageFilename
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cdnifyapicacheurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//unless you have installed root CAs you can't verify the remote server's certificate. Disable checking if this is suitable for your application
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//perform the HTTP DELETE
$result = curl_exec($ch);
//close connection
curl_close($ch);
the env variables at the top call in my api key, password, and resource for the url. I have verified I am logging in via that url.
When I debug through my code i get an error on
$fields = array(
'files' => $storageFilename
);
which is Array to string conversion.
The $storageFilename variable returns
$storageFilename = "/" . $directoryname . "/" . $asset->name;
which is the filename required for the API call of DELETE.
I can't get passed that $fields array. The other stuff below it may or may not run properly. I am just stuck on how to write this part out.
CURLOPT_POST is just there to indicate if some post data should be included in the HTTP request, so its value should a boolean (true or false).
If your array $fields represents the data to be posted, you need to use http_build_query() to assign them to CURLOPT_POSTFIELDS:
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
There is a return in your code that stops the code the curl code is not getting executed remove it or comment it using // and try again and CURLOPT_POST value is boolean true or false that indicates if you want to use post method or not, your CURL code is really messed up you want to use http delete method or post method ?? You can only use one method, please learn how to use php cURL first http://php.net/manual/en/book.curl.php

JIRA API attachment names contain the whole paths of the posted files

I have been working with Jira API and have seen inconsistent results for my requests. Sometimes it works and sometimes it doesn't. Last week I was able to post attachments to issues just fine, but now an old problem occurred: the names of the attachments contain the whole path of the posted file, hence the attachments can't be opened. I use json representation to post files:
$array = array("file"=>"#filename");
json_encode($array);
...
This gets the file posted but the problem is when it's posted the file names in JIRA are like this:
/var/www/user/text.text
Needless to say it can't be opened in JIRA. I had this problem before, then it suddenly disappeared, now it occurred again. I don't really get it. By the way I am not using curl for this request even though it might be recommended in the documentation.
I realize this question is somewhat old but I had a similar problem. It seems Jira doesn't necessarily trim the filename as expected. I was able to fix it with the following. If you're using PHP >= 5.5.0:
$url = "http://example.com/jira/rest/api/2/issue/123456/attachments";
$headers = array("X-Atlassian-Token: nocheck");
$attachmentPath = "/full/path/to/file";
$filename = array_pop(explode('/', $attachmentPath));
$cfile = new CURLFile($attachmentPath);
$cfile->setPostFilename($filename);
$data = array('file'=>$cfile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error){
echo "cURL Error: $ch_error"; exit();
} else {
print_r($result);
}
For PHP <5.5.0 but > 5.2.10 (see this bug):
$data = array('file'=>"#{$attachmentPath};filename={$filename}");
Yes, I filed an issue on this at https://jira.atlassian.com/browse/JRA-30765
Adding attachments to JIRA by REST is sadly not as useful as it could be.
Interesting that the problem went away - perhaps you were running your script from a different location?

Use GCM with PHP

I've seen several posts about how to send GCM messages from my PHP server, but I can't get it working. This is my code:
public function test_gcm($id_user){
// Search user's RegIds and stores them in $regids
if(count($regids) == 0){
echo "This user has no registered device.";
return;
}
$ch = curl_init();
$data = array(
'data' => array('message'=>'my message', 'title'=>'message title'),
'registration_ids' => $regids
);
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
I'm using the browser key. I tried the server key too, but none of them work, the curl_exec always return false. Does anybody know why is it?
EDIT: I just used 'netstat -tuanc | grep 173' on my server and performed the server call. I'm using grep 173 because if I ping android.googleapis.com I ping this ip address. The netstat didn't show any connection to that ip address when I use the curl_exec. Does that mean I'm not connecting to android.googleapis.com? Or what I'm doing is wrong?
Thanks!
Check the "message" content are same or not in android code. 'message'=>'my message' should match with the message from IntentService class in android.
I've managed to fix it. It was a firewall issue, my firewall was blocking the connection. I've added the rules to accept these messages and now it works.
Thanks to all the people that tried to help :)
Try to change it from https to http
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
to
curl_setopt($ch, CURLOPT_URL, 'http://android.googleapis.com/gcm/send');
try this http://2mecode.blogspot.hk/2013/01/google-cloud-messaging-php.html
hope it can help you

cURL POST to REST Service

I am trying to post to a REST service using PHP cURL but I'm after running into a bit of difficulty (this being that I've never used cURL before!!).
I've put together this code:
<?php
error_reporting(E_ALL);
if ($result == "00")
{
$url = 'http://127.0.0.1/xxxxxx/AccountCreator.ashx'; /*I've tried it a combination of ways just to see which might work */
$curl_post_data = array(
'companyName' =>urlencode($companyName),
'mainContact' =>urlencode($mainContact),
'telephone1' =>urlencode($telephone1),
'email' => urlencode($email),
'contact2' => urlencode($contact2),
'telephone2' => urlencode($telephone2)
'email2' => urlencode($email2);
'package' => urlencode($package)
);
foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .$value.'&';
}
rtrim($fields_string, '&');
die("Test: ".$fields_string);
$ch = curl_init();
curl_setopt ($ch, CURLOPT, $url);
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
Following this, my code sends an email and performs an IF statement. I know this works okay, I only started running into trouble when I tried to insert this cURL request.
I've tried this however it doesn't run. As I am integrating with payment partners, it just says:
Your transaction has been successful but there was a problem connecting back to the merchant's web site. Please contact the merchant and advise them that you received this error message. Thank you.
The exact error that was received was a HTTP 500 error.
Thanks.
foreach($curl_post_data as $key=>value) {$fields_string .=$key. '=' .value.'&';
value here is missing a dollar i guess
foreach($curl_post_data as $key => $value) {$fields_string .=$key. '=' .$value.'&';
have you tried die($fields_string); to see what are you actually sending to the merchant?
First of all: are you testing locally? Because that IP you're using is not a valid server address.
The constant to set the URL is called CURLOPT_URL:
curl_setopt ($ch, CURLOPT_URL, $url);
Also CURLOPT_POST must be true or false ( http://php.net/curl_setopt ), not a number (except for 1 maybe):
curl_setopt ($ch, CURLOPT_POST, true);
Here's some POST sample code: PHP + curl, HTTP POST sample code?
It would be best if you can provide your PHP version.
As of PHP 5, some handy functions are bundled in the core instead of separate PECL libraries.
// If you are working with normal HTTP requests, simply do this.
$curl_post_data = http_build_query($curl_post_data);
curl_setopt($ch, CURLOPT, $url);
// This is a boolean option, although passing non-zero integer
// will be type-casted to TRUE, count() is not the proper way.
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_post_data);
// If you really want the next statement be meaningful, do this.
// Otherwise your HTTP response will be passed directly into
// the output buffer.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
Keep in mind that CURLOPT_POSTFIELDS in PHP supports file uploads, by adding a '#' character followed by a full file path as the value.
You don't want to call http_build_query() on such situations.
Sample code for file upload
$curl_post_data = array('file1' => '#/home/user/files_to_be_uploaded');
While you can optionally specify MIME type, see the documentation for more information.
As said, check your PHP version first. This feature only works in PHP 5, AFAIK there are companies still hosting PHP 4.x in their servers.
Have a look at http_build_query

Updating Twitter background via API

I'm having a little trouble updating backgrounds via Twitter's API.
$target_url = "http://www.google.com/logos/11th_birthday.gif";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $html), 'POST');
When I try to pull the raw data via cURL or file_get_contents, I get this...
Expectation Failed The expectation given in the Expect request-header
field could not be met by this server.
The client sent
Expect: 100-continue but we only allow the 100-continue expectation.
OK, you can't direct Twitter to a URL, it won't accept that. Looking around a bit I've found that the best way is to download the image to the local server and then pass that over to Twitter almost like a form upload.
Try the following code, and let me know what you get.
// The URL from an external (or internal) server we want to grab
$url = 'http://www.google.com/logos/11th_birthday.gif';
// We need to grab the file name of this, unless you want to create your own
$filename = basename($url);
// This is where we'll be saving our new file to. Replace LOCALPATH with the path you would like to save the file to, i.e. www/home/content/my_directory/
$newfilename = 'LOCALPATH' . $filename;
// Copy it over, PHP will handle the overheads.
copy($url, $newfilename);
// Now it's OAuth time... fingers crossed!
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $newfilename), 'POST');
// Echo something so you know it went through
print "done";
Well, given the error message, it sounds like you should load the URL's contents yourself, and post the data directly. Have you tried that?

Categories