How to send file via pecl_http? - php

I'm writing API Client, but I can't send files via pecl_http. I wrote everything on http\Client. Most things by copy Postman things, but when I send I get null files. How should I send it? how I should put into this script my $_FILES variable with data?
<?php
$client = new http\Client;
$request = new http\Client\Request;
$body = new http\Message\Body;
$body->addForm(NULL, array(
array(
'name' => 'photo',
'type' => null,
'file' => 'user_path/2018-11-09 o 15.00.48.png',
'data' => null
)
));
$request->setRequestUrl('url');
$request->setRequestMethod('POST');
$request->setBody($body);
$request->setHeaders(array(
'Postman-Token' => 'f6154fff-46f4-47d0-a7c3-98d7de8d0f24',
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();

Here is part of the code I found in: Pecl_http Tutorial
<?php
$r = new HttpRequest('http://dev.iworks.at/.print_request.php', HTTP_METH_POST);
// if redirects is set to true, a single redirect is allowed;
// one can set any reasonable count of allowed redirects
$r->setOptions(
array( 'cookies' => array('MyCookie' => 'has a value'),
'redirect' => true,
)
);
// common form data
$r->setPostFields(
array( 'name' => 'Mike',
'mail' => 'mike#php.net',
)
);
// add the file to post (form name, file name, file type)
touch('profile.jpg');
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
print $r->send()->getBody();
} catch (HttpException $e) {
print $e;
}
?>

Related

PHP Azure OCR - use local file

I'm using the Azure OCR Service to get the text of an image back (
https://learn.microsoft.com/de-de/azure/cognitive-services/Computer-vision/QuickStarts/PHP).
So far everything is up and running, but now I would like to use a local file instead of an already uploaded one.
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
// Request body
$request->setBody("{body}"); // Replace with the body, for example, "{"url": "http://www.example.com/images/image.jpg"}
Unfortunately I don't know how to pass the raw binary as the body of my POST request in PHP.
At first, when we refer local file, we should use 'Content-Type': 'application/octet-stream' in a header, then we can send requests that use a stream resource as the body.
Here's my working code using Guzzle for your reference:
<?php
require 'vendor/autoload.php';
$resource = fopen('./Shaki_waterfall.jpg', 'r');
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze', [
'query' => [
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en'
],
'headers' => [
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>'
],
'body' => $resource
]);
echo $res->getBody();
Using HTTP_Request2:
<?php
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze');
$url = $request->getUrl();
$headers = array(
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>',
);
$request->setHeader($headers);
$parameters = array(
'visualFeatures' => 'Categories',
'details' => '',
'language' => 'en',
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setBody(fopen('./Shaki_waterfall.jpg', 'r'));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}

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?

AWS SES on PHP error: Unable to determine service/operation name to be authorized

I am trying to send email using AWS SES using the following PHP script:
<?php
require_once("phar://aws.phar");
use Aws\Ses\SesClient;
//Open client
$client = SesClient::factory(array(
"key" => "key",
"secret" => "secret",
"region" => "region"
));
$subject = "subject";
$messageText = "text message";
$messageHtml = "<h1>formatted message</h1>";
//Send email
try{
$response = $client->sendEmail(
array(
'Source' => 'verified_email#domain.com',
'Destination' => array(
'ToAddresses' => array('an_address#domain.com')
),
'Message' => array(
'Subject' => array('Data' => $subject),
'Body' => array('Text' => array('Data' => $messageText)),
'Html' => array('Data' => $messageHtml)
)
)
);
}catch(Exception $e){
//An error happened and the email did not get sent
echo($e->getMessage());
}
?>
Whenever I run this, it goes to the catch clause and prints to the screen the message:
Unable to determine service/operation name to be authorized
This doesn't really give me any information on what's wrong and there's no documentation on the API page about this. Any ideas?

convert cURL for Guzzle to send XML file

I am trying to convert this cURL script to use it with PHP and Guzzle. I have been able to set the cookie as shown below but I cannot send the xml file I need to afterwards.
cURL Script
# First, we need to get the cookie
curl [-k] –dump-header <header_file> -F “action=login” -F “username=<username>” -F “password=<password>” https://<website_URL>
# Then, we can use that cookie to upload our orders
# XML Order Upload
curl -b <header_file> -F “import=#<order_file>” http://<website_URL>/importXMLOrder.php
This is what I have that sets the cookie. I am not sure what the next part is to actually send the xml file I have.
$client = new \GuzzleHttp\Client();
$response = $client->post('http://website/login.php', array(
'body' => array(
'username' => 'xxxxx',
'password' => 'xxxxxx'
))
);
I have also tried this. However, I get an error message:
Call to undefined method GuzzleHttp\Message\Response::send()
$request = $client->post('http://website.com/import.php', array(
'body' => array(
'file_filed' => fopen('orders.xml', 'r')
)));
$response = $request->send();
$data = $response->xml();
print_r($data);
Update
$request = $client->createRequest('POST','http://website.com/import.php', array(
'body' => array(
'file_filed' => file_get_contents('orders.xml', 'r')
)
));
$response = $client->send($request);
//var_dump($response); die;
$data = $response->xml();
echo '<pre>';
print_r($data);
It looks like you are calling send() from the wrong class. send() is a method of \GuzzleHttp\Client. So you need to do $client->send() instead.
However, $client->post() sends the request as soon as it creates it. If you want to use send() then you'll need to replace post() with createRequest(), as seen here: http://guzzle.readthedocs.org/en/latest/clients.html#creating-requests
You'll also have problems with the call to fopen() which returns a file handle instead of the contents. Try file_get_contents() instead.
Edit:
In order to set the auth cookie, you'll need a cookie jar. Try the following:
$client = new \GuzzleHttp\Client();
$auth = $client->post('http://website/login.php', array(
'body' => array(
'username' => 'xxxxx',
'password' => 'xxxxxx'
),
'cookies' => true
));
Using the same Client:
$request = $client->createRequest('POST','http://website.com/import.php', array(
'body' => array(
'file_filed' => file_get_contents('orders.xml')
),
'cookies' => true
));
$response = $client->send($request);
//var_dump($response); die;
$data = $response->xml();
echo '<pre>';
print_r($data);

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