Sending an image to aws via php - php

The main problem that i've to do is sending an image from another server to AWS after some process. For that i've done the database processes in the first server. It works very well, i tested it. After that i've to send this image directly to AWS to start another .php file. I try it via cURL function:
server1.php the php file that's found in the first server:
$url = 'http://myawsurl.com/server/test.php';
$imageData = file_get_contents($_FILES['fileToUpload']['tmp_name']);
$post_data = array(
'tmp' => $_FILES["fileToUpload"]["tmp_name"],
'type' => $_FILES["fileToUpload"]["type"],
'name' => $_FILES["fileToUpload"]["name"],
'data' => $imageData
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
test.php the php file that's found in aws:
if ($_POST["tmp"] && $_POST["name"] && $_POST["type"] && $_POST["data"]) {
$target_dir_requests = "/requests/";
create_folder_if_not_exist(ABSPATH . $target_dir_requests);
$dir_for_req_server = ABSPATH . $target_dir_requests . basename($_FILES["fileToUpload"]["name"]);
$dir_for_req_server = base64_to_jpeg($_POST["data"],$dir_for_req_server);
// After some requests that i've to do and i've done
} else {
echo "data sending error";
}
i tried something for todo but they did not work. Could you please help me for find a solution ? Thanks.

You are checking if the variable is true or not with the if($_POST[])
What you actually want is to check if the variable isset
Try this and see if you get any result:
if(isset($_POST['tmp'])){
echo 'test';
}
Or
$tmp = isset($_POST['tmp']) ? trim($_POST['tmp']) : null;
if(!empty($tmp)){
echo 'test';
}
The curl itself should be working

Related

PHP Curl Post and Get Response

I have a shell code as below."curl -X POST -F 'file=#textomate-api.pdf;type=text/plain' https://textomate.com/a/uploadMultiple"
This code send a file to the URL and get the response below.
{
"countedFiles": [
{
"wordsNumber": 340,
"charsNumber": 2908,
"charsNoSpacesNumber": 2506,
"wordsNumberNN": 312,
"charsNumberNN": 2755,
"charsNoSpacesNumberNN": 2353,
"md5": null,
"fileName": "textomate-api.pdf",
"error": null
}
],
"total": {
"wordsNumber": 340,
"charsNumber": 2908,
"charsNoSpacesNumber": 2506,
"wordsNumberNN": 312,
"charsNumberNN": 2755,
"charsNoSpacesNumberNN": 2353,
"md5": null
}
}
And I want to post a file via PHP and get this response or only value of "charsNoSpacesNumber".
Could you please help me with this?
Thanks a lot
You can do it as follows:
YET be sure to first check their T&C as I am not sure if they provide such a service for free.
Also be sure to include some error / exceptions handling.
<?php
//Initialise the cURL var
$ch = curl_init();
//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the Url
curl_setopt($ch, CURLOPT_URL, 'https://textomate.com/a/uploadMultiple');
$path = '/path/to/your/file.pdf';
$file = curl_file_create($path, 'application/pdf', 'file');
//Create a POST array with the file in it
$postData = array(
'file' => $file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// Execute the request, decode the json into array
$response = json_decode(curl_exec($ch), true);
var_dump($response['total']['charsNoSpacesNumber']);
Thanks for your support Bartosz.
This is my code and I also shared an image of the code and results.
I hope there are enough information.
<?php
if(is_callable('curl_init')){
echo "curl is active";
} else {
echo "curl is passive";
}
//Initialise the cURL var
$ch = curl_init();
//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the Url
curl_setopt($ch, CURLOPT_URL, 'https://textomate.com/a/uploadMultiple');
$path = 'textomate-api.pdf';
$file = curl_file_create($path, 'application/pdf', 'file');
//Create a POST array with the file in it
$postData = array(
'file' => $file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// Execute the request, decode the json into array
$response = json_decode(curl_exec($ch), true);
var_dump($response['total']['charsNoSpacesNumber']);
var_dump($response);
var_dump(file_exists($path));
?>
Updated code is below and you can see the results in the image.
I want to use this API on my website to be able to calculate character count of documents. I am using Wordpress and API provider gives us 3 options, Java, PHP (Wordpress) and Shell. They have something for Wordpress but I don't know how to use it.
You can reach all the files from here.
https://github.com/zentaly/textomate-api
If you take a look there, you can get more information and maybe you can find me a better solution.
And again thank you so much for your support, I appreciate it.
<?php
if(is_callable('curl_init')){
echo "curl is active";
} else {
echo "curl is passive";
}
//Initialise the cURL var
$ch = curl_init();
//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the Url
curl_setopt($ch, CURLOPT_URL, 'https://textomate.com/a/uploadMultiple');
curl_setopt($ch, CURLOPT_VERBOSE, 2);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec: var_dump(curl_errno($ch));
var_dump(curl_error($ch));
$path = 'textomate-api.pdf';
$file = curl_file_create($path, 'application/pdf', 'file');
//Create a POST array with the file in it
$postData = array(
'file' => $file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// Execute the request, decode the json into array
$response = curl_exec($ch);
var_dump($response);
$response = json_decode($ch);
var_dump($response['total']['charsNoSpacesNumber']);
var_dump($response);
var_dump(file_exists($path));
var_dump($file);
?>

Telegram Send image from external server

I'm using PHP to config a webhook for a BOT.
I'd like to send picture from another server.
I've tried this way
function bot1($chatID,$sentText) {
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$this->sendPhoto($botUrl,$chatID,$img);
}
function sendPhoto($botUrl,$chatID, $img){
$this->sendMessage($botUrl,$chatID,'This is the pic'.$chatID);
$this->sendPost($botUrl,"sendPhoto",$chatID,"photo",$img);
}
function sendMessage($botUrl,$chatID, $text){
$inserimento = file_get_contents($botUrl."/sendMessage?chat_id=".$chatID."&text=".$text."&reply_markup=".json_encode(array("hide_keyboard"=>true)));
}
function sendPost($botUrl,$function,$chatID,$type,$doc){
$response = $botUrl. "/".$function;
$post_fields = array('chat_id' => $chatID,
$type => new CURLFile(realpath($doc))
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
}
But I receive only the message.
What is the problem?
I've tried to change in http but the problem persists
Well, I've done a workaround because my cUrl version seems to have a bug in uploading file.
Now I use Zend FW
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$realpath = realpath($doc);
$url = $botUrl . "/sendPhoto?chat_id=" . $chatID;
$client = new Zend_Http_Client();
$client->setUri($url);
$client->setFileUpload($realpath, "photo");
$client->setMethod('POST');
$response = $client->request();
You have to send a file, not a URL.
So:
function bot1( $chatID,$sentText )
{
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$data = file_get_contents( $img ); # <---
$filePath = "/Your/Local/FilePath/Here"; # <---
file_put_contents( $data, $filePath ); # <---
$this->sendPhoto( $botUrl, $chatID, $filePath ); # <---
}
This is as raw example, without checking success of file_get_contents().
In my bot I use this schema, and it works fine.

Uploading files using PHP

I have set up an HTML form to select a file and submit it to a PHP script which will upload it. I cannot use move_uploaded_files() because Box's API requires that I add a HTTP Header for Authorization: access_token. What I've done is set up my own POST method using the cURL library.
The problem I'm running into is setting the filename correctly, as it requires the full path of the file. I cannot get the full path of the file from the HTML form and using $_FILES['filename']['tmp_name'] uploads a .tmp file which I do not want. Does anyone know the solution to this problem? Thanks a lot!
My code:
public function upload_file($file) {
$url = 'https://api.box.com/2.0/files/content';
$params = [
'filename' => '#'.$file['tmp_name'],
'folder_id' => '0'
];
$header = "Authorization: Bearer ".$this->access_token;
$data = $this->post($url, $params, $header);
}
public function post($url, $params, $header='') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
if(!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Suggest you do one of the following:
Use move_uploaded_files to upload file into some directory and use that location to send the file to box using curl. After successful upload you can delete the file from this directory.
Instead of uploading the file through PHP, you can upload them client side using the cors http://developers.blog.box.com/2013/05/13/uploading-files-with-cors/
Another question which I have in my mind is how are you keeping your access_token refreshed?
Vishal
I agree with what Vishal has suggested in point number one.
I have written the PHP SDK for v2
Just include the api class and initiate the class:
<?php
include('library/BoxAPI.class.php');
$client_id = 'CLIENT ID';
$client_secret = 'CLIENT SECRET';
$redirect_uri = 'REDIRECT URL';
$box = new Box_API($client_id, $client_secret, $redirect_uri);
if(!$box->load_token()){
if(isset($_GET['code'])){
$token = $box->get_token($_GET['code'], true);
if($box->write_token($token, 'file')){
$box->load_token();
}
} else {
$box->get_code();
}
}
// Upload file
$box->put_file('RELATIVE FILE URL', '0'));
?>
Have a look here
Download: BoxPHPAPI

curl error when upload to the webhost

I am going to have a php that upload json to the web.
Here is my file to upload (located in my local drive)
test.php
$string = file_get_contents("results.json");
$ch = curl_init();
$post_values = array('json_data' => $string);
curl_setopt($ch, CURLOPT_URL, '<dir path>/test1.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_values);
$data = curl_exec($ch);
if (!curl_errno($ch)) {
echo 'Received raw data' . $data;
}
curl_close($ch);
?>
This is the code to get the posted json
test1.php
<?php
$data = json_decode($_POST['json_data'], true);
header('Content-type: text/json');
foreach ($data['queue'] as $queue) {
echo "Wof = " . $queue['wof'];
echo "Input Date = " . $queue['input_date'] . "<br />";
}
?>
Both code works well.
But when I upload test1.php to the web server, it means I send my json located in my computer to the server. I doesn't work.
No Error msg I get, only it does not show the data. only show Received raw data
My question is : How to fix it?, is there something wrong with my code?
Thanks in advance.

PHP Printing with Google Cloud Print

I am currently adding the ability to a php back-end system to allow it to print directly and I am trying to get things working with Google's Cloud Print. Imagine the app as an online shopping cart and I want it to print picking notes (completed orders) without the need for someone to login. The server is remote and the destination has Cloud Ready Printers.
So far I have been successful in getting it to print using the interfaces, as long as I am simply passing HTML, plain text or a URL to a PDF. I am able to set the print to color, marginless and the print quality.
However where I have hit a problem is, the PDF which the system creates are not publicly accessible, hence I can't pass a URL to the file, I need to pass the contents of the file.
I have been trying with no success to modify one of the examples I have found on the web HERE. However I don't know the language so am struggling with it.
Another example in python HERE again I have been trying without success!
I'm using PHP and the Zend framework to work with the interface. Here is one sample I have tried, cut down to where I am trying to prepare the file to send, like I say I'm not really sure on translating from python to php, or if the python script even works, but this is what I came up with:
<?php
// Test print a job:
$b64_pathname = PDF_PATH.'ec22c3.pdf'.'.b64';
$fileType = "application/pdf";
// Open the original file and base64 encode it:
$dataHandle = fopen(PDF_PATH.'ec22c3.pdf', "rb");
$dataContent = fread($dataHandle, filesize(PDF_PATH.'ec22ed167763a15e8591a3776f3c65c3.pdf'));
fclose($dataHandle);
$b64data = $fileType.base64_encode($dataContent);
// Store the base64 encoded file:
$ourFileHandle = fopen($b64_pathname, 'w');
fwrite($ourFileHandle, $b64data);
fclose($ourFileHandle);
// Read the contents of the base64 encoded file and delete it:
$fileHandle = fopen($b64_pathname, "rb");
$fileContent = fread($fileHandle, filesize($b64_pathname));
fclose($fileHandle);
unlink($b64_pathname);
// URL encode the file contents:
$file = urlencode($fileContent);
// Add the file and send to the printer:
$client->setParameterPost('content', $file);
$client->setParameterPost('contentType', $fileType);
$client->request(Zend_Http_Client::POST);
?>
Here's a method in php using cUrl (note, I have object level variables called _auth, _username, _password & _printerId).
First, build a function to post with cUrl:
function processRequest($url, $postFields, $referer) {
$ret = "";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_USERAGENT, "");
if(!is_null($postFields)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
$postFields);
// http_build_query() will properly escape the fields and
// build a query string.
}
if(strlen($this->_auth) > 0) {
$headers = array(
"Authorization: GoogleLogin auth=". $this->_auth,
//"GData-Version: 3.0",
"X-CloudPrint-Proxy", "yourappname"
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$ret = curl_exec ($ch);
curl_close ($ch);
return $ret;
}
Then, a function to authorize against Google:
public function authorize() {
$url = "https://www.google.com/accounts/ClientLogin";
$post = array("accountType" => "HOSTED_OR_GOOGLE",
"Email" => $this->_username,
"Passwd" => $this->_password,
"service" => "cloudprint",
"source" => "yourappname");
$resp = $this->processRequest($url, $post, "");
preg_match("/Auth=([a-z0-9_\-]+)/i", $resp, $matches);
$this->_auth = $matches[1];
}
Finally, build a function to submit to the cloud printer:
function printDocument($title, $docBytes)
{
$url = "http://www.google.com/cloudprint/submit?printerid=". $this->_printerId."&output=json";
$post = array(
"printerid" => $this->_printerId,
"capabilities" => "",
"contentType" => "dataUrl",
"title" => $title,
"content" => 'data:application/pdf;base64,'. base64_encode($docBytes)
);
$ret = $this->processRequest($url, $post, "");
echo $ret;
}
In use, call authorize() to get the authentication token. Then just read your file (from wherever) into a variable and pass it to printDocument with the title.
In order to send base64 encoded content you need to send another parameter in submit request:
$client->setParameterPost('contentTransferEncoding', 'base64');

Categories