Uploading File with CURL and Retrieving in Laravel Method - php

I'm trying to get data posted using cURL in my endpoint, which is built on Laravel. In my API controller, where I receive data, I am able to receive all the data except my media file. I check for presence of the file using $request->hasFile('file') but it returns false. I also try to get the file using $request->file('file') but it returns null.
When I use $request->get('file'), I get the following response.
file":{"name":"/Users/name/File/path/public/media/aaaah.wav","mime":null,"postname":null}
Below, I am using $headers[] = "Content-Type: application/json"; to convert the recipient from array to string. Can anyone help me understand why the file posted by cURL is not being received in my Laravel method when I use $request->hasFile('file') and $request->file('file')?
AppController
public function postCurlData()
{
$endPoint = 'http://127.0.0.1:9000/api';
$apiKey = '****';
$url = $endPoint . '?key=' . $apiKey;
$dir = '/Users/name/File/path/app/public/media/test.wav'; // full directory of the file
$curlFile = curl_file_create($dir);
$data = [
'recipient' => ['44909090', '44909090'],
'content' => 'i love to code',
'file' => $curlFile,
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
}
My endpoint where I'm receiving data:
APIController
public function receiveCurlData()
{
$apiKey = $request->get('key');
if (($apiKey)) {
return response()->json([
'status' => 'success',
'content' => $request->get('content'),
'recipient' => $request->get('recipient'),
'file' => $request->hasFile('file')
]);
}
}
Response
{"status":"success","content":"I love to code","recipient":
["44909090","44909090"],"file":false}

This answer is related to your question:
how to upload file using curl with php.
You should delete
$headers = array();
$headers[] = "Content-Type: application/json";
And
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
And also delete the json_encode() replacing it by the plain array
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);

Related

Uniquely identify iOS device with DeviceCheck API and server side php code not working

I'm getting error : Missing or incorrectly formatted payload
I'm generating device token from Apple DeviceCheck API in swift language with real device and also passing Transaction ID to this php api.
jwt token generating successfully with this code but further code not working with apple query bit api.
This is my server side code in php :
<?php
require_once "vendor/autoload.php";
use Zenstruck\JWT\Token;
use Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256;
use \Ramsey\Uuid\Uuid;
$deviceToken = (isset($_POST["deviceToken"]) ? $_POST["deviceToken"] : null);
$transId = (isset($_POST["transId"]) ? $_POST["transId"] : null);
function generateJWT($teamId, $keyId, $privateKeyFilePath) {
$payload = [
"iss" => $teamId,
"iat" => time()
];
$header = [
"kid" => $keyId
];
$token = new Token($payload, $header);
return (string)$token->sign(new ES256(), $privateKeyFilePath);
}
$teamId = "#####";// I'm passing My team id
$keyId = "#####"; // I'm passing my key id
$privateKeyFilePath = "AuthKey_4AU5LJV3.p8";
$jwt = generateJWT($teamId, $keyId, $privateKeyFilePath);
function postReq($url, $jwt, $bodyArray) {
$header = [
"Authorization: Bearer ". $jwt
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyArray); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$server_output = curl_exec($ch);
//$info = curl_getinfo($ch);
// print_r($info);
//echo 'http code: ' . $info['http_code'] . '<br />';
//echo curl_error($ch);
curl_close($ch);
return $server_output;
}
$body = [
"device_token" => $deviceToken,
"transaction_id" => $transId,
"timestamp" => ceil(microtime(true)*1000)
];
$myjsonis = postReq("https://api.development.devicecheck.apple.com/v1/query_two_bits", $jwt, $body);
echo $myjsonis;
?>
Where is problem in this code? Or any other solution in php code.
Is there anything that I'm missing.
I just checked the Docs. They don't want POST fields like a form, they want a JSON body instead. Here's a snippet of code that you should be able to tweak to do what you require:
$data = array("name" => "delboy1978uk", "age" => "41");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Actually, looking again at your code, it could be as simple as running json_encode() on your array.

Sending an voice file to API (laravel) - 5.4

I am trying to send a voice file to my api built in laravel. Everything seems right in my code but when i send the file to my api, i check at my api side if the data posted has file contained in it but i keep getting false. Am i posting my voice file wrongly.
Path: Absolute path
PHP version : 7.0
$endPoint = 'https://api.domain.com/api';
$apiKey = '**********';
$url = $endPoint . '?key=' . $apiKey;
$curlFile = new \CurlFile('/Users/public/Voice/aaaah.wav');
$data = [
'message' => 'First Voice',
'file' => $curlFile,
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: multipart/form-data";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
return $result;

Post Json and audio file with php (curl) to a laravel API

I am posting json and audio file to my api built on laravel with the code below
$endPoint = 'http://localhost:9000/api/audio/send';
$apiKey = 'anvx7P7ackndaD8MvXlufSaG4uJ901raoWIwMPGZ93dkH';
$url = $endPoint . '?key=' . $apiKey;
$curlFile = new \CURLFile('/Users/desktop/myapp/public/Voice/aaaah.wav');
$data = array("request" =>
json_encode(array("test" => "First audio ",'recipient' =>['442342342', '35345242'])) . ";
type=application/json","file" => "#d8696c304d09eb1.wav;type=audio/wav");
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
return $result;
When i submit my json to the api, it returns null from the api. Meaning no data is being posted to my api. Is there any error with how i am posting my json and audio file to the laravel api please?
PS: Beginner in PHP
You cannot post files in a JSON!.
A normal POST request is needed (the one that gets generated from the <form> element) for posting a file.
If you are bound to send the file using JSON, base64_encode it and send. On the other end though, the server will need to base64_decode it first.

FCM is not receiving by IOS device even if I am getting Successful response on server side

In PHP side I have created code to send FCM to IOS devices, I am passing accurate parameters here,When I try to send notification I am getting successful response like this
{
multicast_id: 6784314520531373000,
success: 2,
failure: 0,
canonical_ids: 0,
results: [
{
message_id: "0:1493995134709022%045ee4bf045ee4bf"
},
{
message_id: "0:1493995134709678%b71f17fbb71f17fb"
}
]
}
[image removed]
Bellow I posted my PHP code
function sendFcmIOS($urls, $registrationId) {
// $ch = curl_init('https://fcm.googleapis.com/fcm/send');
$message = array('title' => 'FabPro1', 'URL' => $urls);
//This array contains, the token and the notification. The 'to'
attribute stores the token.
//registration_ids
$arrayToSend = >array('registration_ids' => $registrationId, 'notification' => $message,
'priority' => 'high');
//Generating JSON encoded string form the above array.
$json = json_encode($arrayToSend);
//Setup headers:
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=*****';
//Setup curl, add headers and post parameters.
$url = 'https://fcm.googleapis.com/fcm/send';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Send the request
$response = curl_exec($ch);
if ($response) {
echo $response;
} else {
trigger_error(curl_error($ch));
;
}
//Close request
curl_close($ch);
}

laravel5 and GuzzleHttp

I am using GuzzleHttp to send request to external api and get response, but the response returned is empty from data. and when i test a uri and parameters in advanced rest client i get a data,So why Guzzle response is empty?!
please help me if you can.
here is my code:
public function index($id)
{
$client = new Client(['base_uri' => 'http://qpeople.me/']);
$response=$client->post('profileinfo', [
'json'=>[
'tshirtID'=>$id
]
]);
$body=$response->getBody();
dd($body);
return view('profile');
}
this is the response
Ok,I found the solution by using cURL to send the request and get a response,
here is the code:
$url = 'http://qpeople.me/profileinfo';
$data['tshirtID'] =$id;
$_data = json_encode($data);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($_data),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
try:
<?php
$body = (string) $response->getBody();
dd($body);

Categories