how to send / get files via web-services in php - php

is this possible ?
what is the correct way to send files ?
thanks

I don't if you want your webservice to upload/download files. Anyway you can use curl(http://fr.php.net/curl ) to upload/download file from other webserver.
To get some file uploaded to the webservice from the user it's pretty much the same as gettings it from a form, please use the superglobal variable:$_FILES (doc) to get upload files.
for uploading from php to a webservice
$fullflepath = 'C:\temp\test.jpg';
$upload_url = 'http://www.example.com/uploadtarget.php';
$params = array(
'photo'=>"#$fullfilepath",
'title'=>$title
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);
the webservice to get a file
$uploads_dir = '/uploads';
foreach ($_FILES["photo"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["photo"]["tmp_name"][$key];
$name = $_FILES["photo"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
PS: sorry for some reason stackoverflow doesn't like to make a link of $_FILES ... so I have linked the superglobals page instead

You use this php program based on nusoap : http://biclim.com/WSClients.action

You can debug the response of your php service and check the file upload from iphone using this app - http://itunes.apple.com/us/app/rest-client/id503860664?ls=1&mt=8
It was really helpful to debug serverside code.

Hello Here Example Image upload
<?php
$path="aa/";// Set your path to image upload
if(!is_dir($path)){
mkdir($path);
}
$roomPhotoList = $_POST['image'];
$random_digit=date('Y_m_d_h_i_s');
$filename=$random_digit.'.jpg';
$decoded=base64_decode($roomPhotoList);
file_put_contents($path.$filename,$decoded);
?>
it can be quick image upload code in php for ios and android

Related

php telegram sendPhoto not working (url & file location)

I need some help if possible with php sendPhoto api, I've been using the sendPhoto method in php on my apache server to auto send images into telegram, I've been using this same method for almost 6-7 months and from few days ago suddenly the api method stopped working. I tried passing photo= using the absolute path of file in url and in php using the files directory+filename but sends me an error msg from the api as shown below, first part is my php method which doesnt return any errors, just shows blank
# my php telegram code
$dir = "Attachments/2022/04/09/imagename.jpeg";
$chat_id = '(groupchatid)';
$bot_url = "https://api.telegram.org/bot(mybotapi)/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id ;
$post_fields = array('chat_id' => $chat_id,
'photo' => new CURLFile(realpath($dir)),
'caption' =>'Test Image', );
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type:multipart/form-data" ));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
When i execute this script as it used to work before recently this is the response i get from the API
{
"ok": false,
"error_code": 400,
"description": "Bad Request: invalid file HTTP URL specified: Unsupported URL protocol"
}
If I replace the image URL to another server it send the image successfully, but im unable to send anything only from my server, If I try access the file directly using the URL of my servers image file I can access it from any pc no issue, only problem is telegram fetching the image, please help, appreciate it
Excuse, I don't usually use curl, so I can give you another option:
function sendPhoto($id, $photo, $text = null){
GLOBAL $token;
$url = 'https://api.telegram.org/bot'.$token."/sendPhoto?
chat_id=$id&photo=$photo&parse_mode=HTML&caption=".urlencode($text);
file_get_contents($url);
}
Just declare the sendPhoto function in this way, put the variabile in which you stored the token instead of "$token" and use the parameters in this way:
$id = the id of the user (the one you declared like this: $id = $update['message']['from']['id'];)
$photo = absolute path of the image you want to send
$text = OPTIONAL caption for the image

I need to send an image using "input type="file"" without any restriction on the image size

I'm programming a telegram bot.
I want to send an image to a series of IDs that are stored in my DB (I'M NOT UPLOADING A PHOTO I'M JUST SENDING IT).
The function to send the image works just fine.
The only problem I have is that images that are above 1MB size won't be sended.
I don't upload these images anywhere, I just send them specifying the image url (so it isn't a problem about a max size upload).
/*this is the function that I use to send the image*/
<?php
include "./db.php";
include "../Gestionale-Bar/webhook.php";
$queryID="SELECT DISTINCT acquirente FROM BackupChat ORDER BY acquirente";
$resultID=$conn->query($queryID);
$file =new CURLFile(realpath($_FILES["photo"]["tmp_name"]));
while($rowID = $resultID->fetch_assoc())
{
$url = $website . "/sendPhoto?chat_id=" . $rowID['acquirente'] ;
$post_fields = array('chat_id' => $rowID['acquirente'], 'photo' => $file);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
}
echo "<script language=\"Javascript\">
window.location.href='mywebpageblablabla';
</script>
";
?>
/*this is the input button where I select the photo*/
function img()
{
var gridWrapper = document.querySelector('.content');
gridWrapper.innerHTML =
"<form action=\"inviaimg.php\" enctype=\"multipart/form-data\" method=\"post\" class=\"inputfile\">" +
"<input type=\"file\" name=\"photo\"/>" +
"<input type=\"submit\" value=\"send\" style=\"background-color:#2a2b30; color:#5c5edc; font-family:AvenirNext; width:10%; height:30px\"></form>"
}
Whenever I try to send an image that is under 1MB everything works fine.
So basically I expect to send photos with bigger size. :)
in your $post_fields you have key photo which value is CURLFile object. In documentation of telegram bots it is written that it belongs pass a value which is file_id as String to send a photo that exists on the Telegram servers, HTTP URL as a String for Telegram to get a photo from the Internet or upload a local photo by passing a file path.
You wrote you didn't upload a file but just sending. Despite this you use a $_FILES[] to get a realpath() of file which is uploaded. Maybe this is a fault of upload_max_filesize. Checkout this.
Check also this this piece of code:
$file = realpath($_FILES["photo"]["tmp_name"]);
while($rowID = $resultID->fetch_assoc())
{
$url = $website . "/sendPhoto?chat_id=" . $rowID['acquirente'] ;
$post_fields = array('chat_id' => $rowID['acquirente'], 'photo' => $file
);
Replace old one with this and give feedback. Greetings, plum!
Sources:
$_FILES[] - https://www.php.net/manual/en/reserved.variables.files.php
The CURLFile class - https://www.php.net/curlfile
Telegram documentation - https://core.telegram.org/bots/api#sendphoto

Download file from google drive api to my server using php

1 - I have configure google picker and it is working fine and I select the file from picker and get the file id.
2 - After refresh token etc all process I get the file metadata and get the file export link
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
3 - After that I use this
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200)
{
$content = $httpRequest->getResponseBody();
print_r($content);
} else {
// An error occurred.
return null;
}
and get this response
[responseBody:protected] => PK��DdocProps/app.xml���
�0D���k�I[ѫ��m
��!����A={���}�
2G�Z�g�V��Bľ֧�n�Ҋ�ap!����fb�d����k}Ikc�_`t<+�(�NJ̽�����#��EU-
�0#���P����........
4 - I use some cURL functions to get file from google drive and save it to server. IN server directory a file created but cropped. I use this code
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
//$downloadUrl value is
/*https://docs.google.com/feeds/download/documents/export/Export?id=1CEt1ya5kKLtgK************IJjDEY5BdfaGI&exportFormat=docx*/
When I put this url into browser it will download file successfully but when I use this url to fetch file with cURL or any php code and try to save it on server it saves corrupted file.
$ch = curl_init();
$source = $downloadUrl;
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "test/afile5.docx";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
It result a corrupted file stored on server but whe I use this code to get any file other then google drive I download it successfully on server.
Can any one please help that how to download file from $downloadUrl to my server using php ?

File Upload to Slim Framework using curl in php [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Failing to upload file with curl in heroku php app
After handling a file upload in php, I am trying to send that file using curl to my rest api which uses Slim Framework. However, $_FILES is always empty once it reaches the function in Slim.
sender.php
if(move_uploaded_file($_FILES['myFile']["tmp_name"], $UploadDirectory . $_FILES['myFile']["name"] ))
{
$ch = curl_init();
$data = array('name' => 'test', 'file' => $UploadDirectory . $_FILES['myFile']["name"]);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/slimlocation/upload/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
}
And the function to receive the request in Slim:
$app->post('/upload/', function() use ($app) {
if(isset($_FILES)){
// count is always zero
echo count($_FILES);
}
});
Am I sending the file incorrectly and / or is it possible to do what I am attempting? Any help is appreciated.
As far as i know, you need to use more options for a file upload with curl. See here.
Look at the CURLOPT_UPLOAD option and the description of CURLOPT_POSTFIELDS, it says that you need to use an # before the file name to upload (and use a full path).
These were the changes I needed and it worked:
$filepath = str_replace('\\', '/', realpath(dirname(__FILE__))) . "/";
$target_path = $filepath . $UploadDirectory . $FileName;
$data = array('name' => 'test', 'file' => '#'.$target_path);

Convert image to pdf php

I am using csxi to make scanning for documnets as image, but I have to upload pdf files to server. How can I convert image to PDF in php ? or is there any way to make csxi scan documents as PDF not image
If you have ImageMagick installed on your machine you could use the ImageMagick bindings for PHP to execute some simple PHP code to do this task:
$im=new Imagick('my.png');
$im->setImageFormat('pdf');
$im->writeImage('my.pdf');
Alternatively if you don't have ImageMagick available you could use a commercial API such as Zamzar which supports image to PDF conversion via PHP (more info in the docs).
Code to use this would be:
<?php
// Build request
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "YOUR_API_KEY";
$sourceFilePath = "my.png";
$targetFormat = "pdf";
$sourceFile = curl_file_create($sourceFilePath);
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
// Send request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
// Process response (with link to converted files)
$response = json_decode($body, true);
print_r($response);
?>
Wrap your image inside HTML and use some HTML to PDF converter like fpdf or mpdf
You can use convertapi service, easy to install:
composer require convertapi/convertapi-php
require_once('vendor/autoload.php');
use \ConvertApi\ConvertApi;
//get api key: https://www.convertapi.com/a/si
ConvertApi::setApiSecret('xxx');
$result = ConvertApi::convert('pdf', ['File' => '/dir/test.png']);
# save to file
$result->getFile()->save('/dir/file.pdf');
to convert multiple files and other options check https://github.com/ConvertAPI/convertapi-php
Here, Php 7.4, Laravel 7+, ImageMagick-7.1.0-Q16, and Ghostscript gs10.00.0 is used.
If any files are contained in the folder JpgToPdf then delete them. And so on.
/**
* jpg To pdf WEB
*
* #method convertJpgToPdf
*/
public function convertJpgToPdf(Request $request)
{
try {
//get list of files
$files = Storage::files('JpgToPdf');
/*get count of files and ,
* check if any files contain
* if any files contains
* then
* get the files name
* delete one by one
*/
if(count($files) >1 )
{
foreach($files as $key => $value)
{
//get the file name
$file_name = basename($value);
//delete file from the folder
File::delete(storage_path('app/JpgToPdf/'. $file_name));
}
}
if ($request->has('jpeg_file'))
{
$getPdfFile = $request->file('jpeg_file');
$originalname = $getPdfFile->getClientOriginalName();
$path = $getPdfFile->storeAs('JpgToPdf', $originalname);
}
// file name without extension
$filename_without_ext = pathinfo($originalname, PATHINFO_FILENAME);
//get the upload file
$storagePath = storage_path('app/JpgToPdf/' . $originalname);
$imagick = new Imagick();
$imagick->setResolution(300, 300);
$imagick->readImage($storagePath);
$imagick->setImageCompressionQuality( 100 );
$imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$imagick->writeImage( storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
return response()->download(storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
} catch (CustomModelNotFoundException $exception) {
// Throws error exception
return $exception->render();
}
}
For just a few images, do it manually and easily with the Chrome web browser. You wont need an internet connection.
Save the following with .html extension in the same folder of your image:
<html>
<body>
<img src="image.jpg" width="100%">
</body>
</html>
Open the html file with Google Chrome,
Crtl + P, to open the print dialog
Choose Save as PDF, to save it locally
Alternatively, you could send a copy to your smatphone via Google Cloud Print

Categories