Post a blob using Guzzle - php

Is it possible to post a blob using Guzzle? The only methods I've been able to find are using #filename to upload a local file. The file is stored as a blob in a MySQL database and I would like to upload it to an api as a post field without the redundancy of saving the blob to disk (and the permissions/path issues that come with it), uploading #filename, and then unlinking the file. Here is the code I have that is working for everything but the blob. I need the 'file' field to save the data as a blob.
$data = array(
'first_name' => $fname,
'last_name' => $lname,
'email' => $email,
'partner_key' => 'qwerty',
'secret_key' => 'qwerty',
'file' => $fileblob
);
$curl = new \GuzzleHttp\Client();
return $curl->post('https://www.api.com',['verify'=>false,'body'=>$data])
The goal being to replace the existing cURL code using Guzzle:
'file' => "#".$localfile.";type=".mime_content_type($localfile)

I found the solution. Hopefully this helps others in the future:
$data = array(
'first_name' => $fname,
'last_name' => $lname,
'email' => $email,
'partner_key' => 'qwerty',
'secret_key' => 'qwerty',
'file' => new \GuzzleHttp\Post\PostFile('filename', $fileblob)
);
$curl = new \GuzzleHttp\Client();
return $curl->post('https://www.api.com',['verify'=>false,'body'=>$data])

Related

How to send Image or file to the external API using HTTP Client?

I have an API to save images and files
this is the code to save the image request from the API
$file = $request->file('gambar');
$fileName = $file->getClientOriginalName();
$file->storeAs('images/berita', $fileName);
$berita = new Berita;
$berita->judul = $request->judul;
$berita->kategori_id = $request->kategori_id;
$berita->isi = $request->isi;
$berita->gambar = $fileName;
$berita->tgl = $request->tgl;
$berita->user_id = $request->user_id;
$berita->save();
return response()->json([
'message' => 'Data berita Added Successfully!',
'Added berita' => $berita
], Response::HTTP_OK);
I already try the API in postman, and everything went well, image sucessfully uploaded.
Then on the client side, I'm using HTTP Client from Laravel to POST the data to the API. And here's the code.
$Berita = Http::withToken('xxx')
->attach('attachment', file_get_contents($request->file('gambar')))
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'gambar' => file_get_contents($request->file('gambar')),
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
return $Berita;
All the data send successfully, except the gambar which contains the image that i sent. It says that in my API validation.
The gambar must be a file of type: jpeg, jpg, png.
It thought that means the image that i send is sent as a string, so it didn't receive it as a file.
By the way, here's the Laravel documentation about HTTP Client: https://laravel.com/docs/9.x/http-client#multi-part-requests
Does anyone knows how to correctly using it? I think i've misused it.
I think there is problem with attachment.
return Http::withToken('xxx')
->attach('gambar', file_get_contents($request->file('gambar')), , 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
or
return Http::withToken('xxx')
->attach('gambar', $request->file('gambar'), 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
This is because the server cannot read your data.
You should send the data using the application/x-www-form-urlencoded content type, you can achieve this as Laravel documentation says:
$response = Http::asForm()->post('http://example.com/users', [
'name' => 'Sara',
'role' => 'Privacy Consultant',
]);

URL has problems in laravel app wihile using S3 on local machine

Imagine you've uploaded a file on a S3 bucket or any type of external storage, right? the address might be :
storage.mystie.com/file
and the browser sees this like:
https://storage.mysite.com/file
but the app I'm working on, sends it like this:
//https://storage.mysite.com
and it results in this error:
Error executing "ListObjects" on "//https://IP"; AWS HTTP error: cURL error 6: Could not resolve host:
What's my problem? is it related to my .env file?!
I've implemented "AWS S3" in one of my Laravel's project when I'm going to save user data and upload his profile picture on s3 storage, while updating that image unlink the previous one and then upload the newest picture.
While storing User's Information code was like-this:
$user = User::create([
'first_name' => preg_replace('!\s+!', ' ', ucfirst($user['first_name'])),
'last_name' => preg_replace('!\s+!', ' ', ucfirst($user['last_name'])),
'email' => strtolower($user['email']),
'phone' => $user['phone'],
'address' => $user['address'],
'avatar' => $this->avatar?env('s3').Storage::disk('s3')->put('/profile',$this->avatar,'public'):'',
'type' => 'business',
'password' => bcrypt('business123456789'),
'meta' => $user['meta']
]);
While updating User's Data:
$filne_name = $this->old_avatar;
if($_FILES['avatar']['size'] > 0 && env('image-upload') == 'true')
{
if(!empty($this->old_avatar))
{
$image = pathinfo($this->old_avatar);
$response = Storage::disk('s3')->exists('/profile/'.$image['basename']);
if($response)
{
Storage::disk('s3')->delete('/profile/'.$image['basename']);
}
}
$filne_name = env('s3').Storage::disk('s3')->put('/profile',$this->avatar,'public');
}
return User::where('id',$this->segment(3))->update([
'first_name' => preg_replace('!\s+!', ' ', ucfirst($user['first_name'])),
'last_name' => preg_replace('!\s+!', ' ', ucfirst($user['last_name'])),
'email' => $user['email'],
'phone' => $user['phone'],
'address' => $user['address'],
'avatar' => $filne_name,
'meta' => json_encode($user['meta'])
]);
And in my .env
s3='https://bucket_link.com/' (That was s3 bucket link)

POST request in PHP is returning PHP code when file extension is used

I am sending post requests in PHP to get a boolean value from my API (so it should return wither true or false)
This is the code I am using in the file for my API. The file is called users.php
if ($_POST['type'] == "authenticateMinecraft"){
$p = new dibdibs\post(
array(
'url' => 'https://authserver.mojang.com/authenticate',
'data' => array(
'agent' => array(
'name' => 'Minecraft',
'version' => 1
),
'username' => $_POST['username'],
'password' => $_POST['password'],
'clientToken' => "33225A179D9A4E1BDA73C012C1C3CBAB8BD00326883BDBEB6FA682482E40F68D"
)
)
);
$res = $p->json();
if (isset($res["selectedProfile"])){
echo("true");
}
else{
echo("false");
}
}
This is the code I am using to reference it (I am using a class which I have put on Pastebin to actually send the request).
$params = array(
'data' => array(
'type' => 'authenticateMinecraft',
'username' => $mcuname,
'password' => $mcpasswd
),
'url' => "api/users.php"
);
$c = new dibdibs\post($params);
$r = $c->http();
var_dump($r);
Whenever I use the .php fule extension when defining url, the whole PHP code of the API page is returned, but when I remove the extension, only true or false is returned. Why is this and is it a problem that I should be aware of and I should fox?

NuSoap, XML was empty, couldn't parse

First, I have to say that I am totally new to WSDL-based Web Services using NuSOAP. I am trying to return an array of friends list from my soap server. Please find below my code listings as is:
Server:
//File includes omitted
function getFriendList($test = ''){
$results = array();
$results[] = array('name' => 'XXXXA1', 'surname' => 'XXXXA2');
$results[] = array('name' => 'XXXXXB1', 'surname' => 'XXXXB2');
$results[] = array('name' => 'XXXXXC1', 'surname' => 'XXXXC2');
return $results;
}
//Create server instance
$server = new soap_server();
//Configure our WSDL
$server->configureWSDL('server', 'urn:server');
//Add our Complex Type data type since we want to return an array
$server->wsdl->addComplexType(
'Friend',
'complexType',
'struct',
'all',
'',
array(
'name' => array('name' => 'name', 'type' => 'xsd:string'),
'surname' => array('name' => 'surname', 'type' => 'xsd:string')
)
);
//Register our array as a response
$server->wsdl->addComplexType(
'FriendArray',
'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(
array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:Friend[]')
),
'tns:Friend'
);
//Register the actual function that retuns the array but in the
//return n field specify the complex type of array we added onto the wsdl
$server->register('getFriendList',
array('test' => 'xsd:string'),
array('return' => 'tns:FriendArray'),
'urn:server',
'urn:server#getFriendList',
'document',
'encoded',
'Fetch a list of friends as an array. If you\'re not here sorry.'
);
//Serve the service
$server->service($HTTP_RAW_POST_DATA = (!isset($HTTP_RAW_POST_DATA)) ? $HTTP_RAW_POST_DATA : '');
With this, I hoped that I did everything correctly. I followed the standard procedure to make it work but in vein.
On the client side, I used the soap address url in wsdl and appended it with "?wsdl", so that it give me wsdl file dynamically.
example:
//Client call
$client = new nusoap_client("http://soapserver.dev/webroot/part_three/server.php?wsdl", true);
I have also taken labour of adding some whistles and bells on my client object as shown below:
$client->soap_defencoding = 'UTF-8';
$client->decode_utf8 = false;
This doesn't seem to help at all. I had experienced an issue earlier since my function accepts no parameter, where my service died because I didnt pass any parameter that speaks of inputs in my $client->call($name, $in, $out). I ended up providing an empty array and I got this error.
Could this be related to the rpc/document parameter types of the register function?
Even using the wsdl file which I saved from my server url, I got the same error.
Can somebody please help me out here? Please!

post big data via Zend_Http_Client_Adapter_Curl

I use $site->setParameterPost and $site->request('POST')->getBody() for posting data to an action, one parameter of setParameterPost is very big data, and it doesn't send data via post method. What can I do?
$config = array('adapter' => 'Zend_Http_Client_Adapter_Curl' );
$site = new Zend_Http_Client('http://somewhere.tld/api/news', $config);
$site->setParameterPost(array(
'news' => $news, //very big data, without it data send properly
'modelName' => 'somemodel',
'method' => 'somemethod',
'key' => 'something',
'siteName' => $sitename,
));
$sitedata = $site->request('POST')->getBody();
I should use streaming requests, which are allowed only with PUT method.
$http_client = new Zend_Http_Client ('http://something.some/thing');
$http_client->setConfig (array (
'adapter' => 'Zend_Http_Client_Adapter_Curl',
'timeout' => 180
));
$file = fopen ('news.dat', 'r'); // put all your news to the file beforehand
$http_client->setRawData ($file);
$http_client->setParameterPost (array (
'modelName' => 'somemodel',
'method' => 'somemethod',
'key' => 'something',
'siteName' => $sitename
));
$response = $http_client->request ('PUT');
On the server-side you can access your big data through
fopen ("php://input", "r");

Categories