I am trying to post a file and some data using curl to a local go server hosted on the same machine:
// initialise the curl request
$request = curl_init('http://localhost:9049/api');
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'company' => 'compname',
'user' => 'compuser',
'srv'=> 0,
'colTxt' => 'col1|col2|col3',
'upfile' => '#' . $_FILES['upfile']['tmp_name']
. ';filename=' . $_FILES['upfile']['name']
. ';type=' . $_FILES['upfile']['type']
));
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($request);
// close the session
curl_close($request);
Unfortunately the above code is giving an empty response, have tried many various methods, but still an empty response.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
Even the curl_getinfo($ch) is empty, so it is getting hard to diagnose. Although there doesn't seem to be a network problem as i can post a file using curl from the command line and it worked perfectly fine. Any idea on what i might be missing?
Thanks.
Have a look here for details on using curl to upload files with the curlfile class
Related
Hi everyone i have crul request when i use it in single php page without laravel it work fine but if i put it inside laraevl controller to use it not working and return code status 0
My Request
$data = '{"PaymentInquiryV4RequestMessage":{"RefNum":"123456"}}';
$ch = curl_init('https://b2btest.stcpay.com.sa/B2B.DirectPayment.WebApi/DirectPayment/V4/PaymentInquiry');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
curl_setopt($ch, CURLOPT_SSLCERT, 'crt.crt');
curl_setopt($ch, CURLOPT_SSLKEY, 'key.key');
curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'X-ClientCode: XXXXXXXXXXX'
)
);
$result = curl_exec($ch);
$result = json_decode($result, true);
print_r ($result);
when dealing with curl always start by debugging errors, which you can enable like
$result = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo $error_msg;
}
and as you mentioned in comment, you received below error after adding above code:
could not load PEM client certificate, OpenSSL error error:02001002:system library:fopen:No such file or directory, (no key found, wrong pass phrase, or wrong file format?)
It clearly indicate it can't find your certificate files, update path to those files in your call , like if your certificates are in directory /var/www/certificate/, your code would be
curl_setopt($ch, CURLOPT_SSLCERT, '/var/www/certificate/crt.crt');
curl_setopt($ch, CURLOPT_SSLKEY, '/var/www/certificate/key.key');
and make sure cert files are readable by setting proper permissions.
p.s you can also use Laravel helpers to get the path
base_path(); // '/var/www/mysite'
app_path(); // '/var/www/mysite/app'
storage_path(); // '/var/www/mysite/storage'
so you call will contain like
curl_setopt($ch, CURLOPT_SSLCERT, base_path().'/certificate/crt.crt');
curl_setopt($ch, CURLOPT_SSLKEY, base_path().'/certificate/key.key');
I'm taking multiple documents of candidate from database, put it into one array and sending this array and some other additional information to the REST API. Then it's throwing an exception FILE Type NOT Support. When sending single image it works properly.
foreach($a_files as $a_file)
{
$file_name_with_full_path=$a_file->uploaded_path.$a_file->document_name;
$mime_type=mime_content_type($file_name_with_full_path);
$cFile[] = '#'.realpath($file_name_with_full_path).';type='.$mime_type.';';
}
Sending this information through REST API. My post data is like:
$post= array('level' => "level",
'nameOfInstitute' => "nameOfInstitute",
'nameAsPerDocument' => "nameAsPerDocument",
'issueDate' => "issueDate",
'registrationNumber' => "registrationNumber",
'yearOfPassing' =>"yearofpassing",
'degree' =>"degree",
'fieldOfStudy' =>"fieldofstudy",
'grade' =>"grade",
'nameOfBoardUniversity'=>"university",
'file' =>$cFile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_USERPWD, $val);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec ($ch);
$err = curl_error($ch);
curl_close($ch);
It's throwing an exception file type not supported. But when sending single file, it's working fine (without loop). What is the problem in above code when sending multiple files in the API. Please help me out from this problem.
I made a script that uses the Mobile.de API.
It worked fine on their test environment, only difference with the live environment is the proxy. So in my cURL I removed the proxy.
For any POST call this works just fine, but for my PUT call it doesn't work at all.
So let's say I sent the following with for example Postman:
PUT /seller-api/sellers/123/ads/456
Host: services.mobile.de
Content-Type: application/vnd.de.mobile.api+json
Authorization: Basic abcdef12345=
And I put in the right JSON, it works just fine.
And this is the script I use in PHP:
function updateVehicle($seller, $voertuig_id, $json) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://services.mobile.de/seller-api/sellers/' . $seller . '/ads/' . $voertuig_id);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_USERPWD, USERNAME . ':' . PASSWORD);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Host: services.mobile.de',
'Content-type: application/vnd.de.mobile.api+json'
));
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
In return I get the 403 forbidden. 'You don't have permission to access /seller-api/sellers/123/ads/456 on this server.'
I already printed out al curl info and saw that all the headers are there and everything seems just fine, but why don't I have permission.
Contacted Mobile.de already but they say it's something in my code.
So after much debugging I found out it was a space after the $voertuig_id that got me an 403 forbidden error. :S
I'm trying to setup the application server part of C2DM push messaging using this code - https://github.com/lytsing/c2dm-php.
I have completed the app side of things and have registered an email address with Google - every time I run the code (on a server with php/cURL installed) i get the error 'get auth token error'. It driving me nuts as I've no idea where to begin to solve the problem.
The only lines I have changed in the code are - in the s2dm.php file -
'source' => 'com.phonegap.chillimusicapp',
and I added my email/password into the post.php file -
$result = $c2dm->getAuthToken("email#googlemail.com", "password");
Any advice would be great!
Cheers
Paul
Try using below sample code, It is working fine.
<?php
define("C2DM_ACCOUNT_EMAIL","[C2DM_EMAIL]");
define("C2DM_ACCOUNT_PASSWORD","[C2DM_PASSWORD]");
define("C2DM_CLIENT_LOGIN_URL","https://www.google.com/accounts/ClientLogin");
define("C2DM_MSG_SEND_URL","https://android.apis.google.com/c2dm/send");
function sendPushNotification($device_reg_id,$msg){
$auth_id=get_auth_id(); // To get Auth ID
$post_fields=array(
'collapse_key=ck_1',
'registration_id='. trim($device_reg_id),
'data.payload='. trim($msg),
);
$data_str=implode('&', $post_fields);
$headers = array(
'Authorization: GoogleLogin auth='.trim($auth_id),
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.trim(strlen($data_str)),
'Connection: close'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,C2DM_MSG_SEND_URL);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// print_r($server_output);
}
function get_auth_id(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,C2DM_CLIENT_LOGIN_URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Email=".C2DM_ACCOUNT_EMAIL."&Passwd=".C2DM_ACCOUNT_PASSWORD."&accountType=GOOGLE&source=Google-cURL-Example&service=ac2dm");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// print_r($server_output);
$parts=explode("Auth=",$server_output);
$auth_id=$parts[1];
// echo $auth_id;
return $auth_id;
}
$reg_id = "[DEVICE_REG_ID]";
sendPushNotification($reg_id,"Hello World...!! Jay is testing C2DM...");
FYI! No need to call get_auth_id() every time you send notification, You can call once and store auth_id somewhere in config file also.
I am attempting to send a file to an Https URL with this code:
$file_to_upload = array('file_contents'=>'#'.$target_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSER, FALSE);
curl_setopt($ch, CURLOPT_UPLOAD, TRUE);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'file='.$file_to_upload);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close ($ch);
echo " Server response: ".$result;
echo " Curl Error: ".$error;
But for some reason I'm getting this response:
Curl Error: Failed to open/read local data from file/application
Any advice would help thanks!
UPDATE: When I take out CURLOPT_UPLOAD, I get a response from the target server but it says that there was no file in the payload
You're passing a rather strange argument to CURLOPT_POSTFIELDS. Try something more like:
<?
$postfields = array('file' => '#' . $target_path);
// ...
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
?>
Also, you probably want CURLOPT_RETURNTRANSFER to be true, otherwise $result won't get the output, it'll instead be sent directly to the buffer/browser.
This example from php.net might be of use as well:
<?php
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
On top of coreward's answer:
According to how to upload file using curl with php, starting from php 5.5 you need to use curl_file_create($path) instead of "#$path".
Tested: it does work.
With the # way no file gets uploaded.