php telegram sendPhoto not working (url & file location) - php

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

Related

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

VIMEO (Pro) get JSON response help (PHP/CURL)

I have a Vimeo PRO account.
I have protected videos uploaded.
Videos are also set to ONLY be embeddable on my domains (set in the video settings)
I am -not- grasping how to use their examples (sorry, for me the examples do not include real working samples for me,..or at least how to implement them to understand.. so I'm hoping to get some help)
Not clear on all the OAuth2, Oembed... authentication stuff either.. which I believe is where my problem lies.
I was following this gitHub example:
https://github.com/vimeo/vimeo-api-examples/blob/master/oembed/php-example.php
(looks to be pretty old?)
I'm looking to get JSON data returned for a video when an ID is passed along.
I was/am under the impression that I need to 'authenticate' before I can get my response/return data?
Is this best done in the CURL header or something?
Can someone guide me a bit more? (shouldnt be this hard!) haha..
Here is my code:
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
//JSON url
//$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
//this fixes the cURL approach
$json_url = $video_endpoint . rawurlencode($video_url);
// Curl helper function
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization : bearer xxxxxx'));
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
$vimeoJSON = json_decode((curl_get($json_url)));
var_dump($vimeoJSON);
And I get this response:
object(stdClass)#1 (1) { ["error"]=> string(52) "You must provide a valid authenticated access token." }
questions are:
1.) Is this even a valid approach? (assuming I just need to append some lines of code to the CURL header to send my auth over before getting a response?)
2.) How do I update my CURL snippet to work with VIEMO authentication?
I'm trying to keep this as CLEAN/SIMPLE as I can (for the JSON call/return portion)..
Any guidance is appreciated.
Thanks
update:
this code does NOT work:
$access_token = 'xxx';
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $json_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The video I want to use is located here:
https://vimeo.com/171811266/5822169b48
IT IS A PRIVATE VIDEO. (not sure you'll be able to see it)..
When I use the latest version of the code posted above.. I get this response:
{"error":"The requested video could not be found"}
Is this because its a PRIVATE video?
(actually I just set the video to be able to be viewed by anyone.. and I still got the same error/response) (not found)
If so.. what is the fix to use MY videos.. that are set to private... but use them on my site/domain still?
===========================================================================
FINAL UPDATE:
Trying to use the code in the readme example:
https://github.com/vimeo/vimeo.php
Trying to use (un-successfully) the LIB #Dashron pointed me too.. I cant even seem to get the basics to work from the GIT Page:
Code:
//project vars
$client_id = 'xxxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$redirect_uri = 'http://domain.com/file.php'; //where do I redirect them back to? the page where I have the embeded video at?
// scope is an array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#scopes
$scopes = Array('public', 'private');
$state = 'Ldhg0478y';
require("Vimeo/autoload.php");
$lib = new Vimeo\Vimeo($client_id, $client_secret);
// build a link to Vimeo so your users can authorize your app. //whatever that means and is for?
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state);
// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
I get this error message:
Parse error: syntax error, unexpected Fatal error: Class 'Vimeo\Vimeo' not found in /usr/www/users/aaemorg/aaem.org/video/vimeo_lib.php
Seems like its not creating instantiating my $lib object/class??
(I know I'm not great at high level PHP class/code... but this absurdly hard just to get a JSON response for video I own to embed (again) on a site I own as well)
Any direction would be appreciated?
======================================================================
Update: "what worked for me"..
I am appreciate the link to the 'official' library.. but the readme examples just didnt work for me...
To keep things nice and easy for others who may be new to the Vimeo API stuff as well.. here is a quick and dirty, simple code sample to get you up and running:
<?
//include offifial library
require("Vimeo/autoload.php");
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_id = 'xxx';
$lib = new Vimeo\Vimeo($client_id, $client_secret, $access_token);
$video_response = $lib->request('/videos/'.$video_id);
//dont really need this, but included in case there is some data you need to display
$token_response = $lib->clientCredentials();
//example of parsing out specific data from the array returned
//name/title
echo $video_response['body']['name'] . '<br><br>';
?>
The link you provided is very, very old. It is actually part of a different API, and no longer relevant.
The Library you should be using is located here: https://github.com/vimeo/vimeo.php with many examples in the readme, and the examples directory!
Below code works for me
Please follow this step before
Under video settings : General->privacy, Change Who can watch select box to Anyone.
$url = 'https://api.vimeo.com/videos/388591356';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer 969329f9b5b3882d74d1b39297528242";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$final_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result), true );
echo "<pre>";
print_r($final_result);

Getting a gmail contact Photo using Curl

I have created a class managing the connection to Google Contacts API, authenticate and return the contacts.
I've successfully got the contacts list, But I didn't yet manage to get the contact photo. This is my html code :
<img src="<?= $service->getPhoto($contact['image']) ?>" />
and this is my php:
public function getPhoto($url = false){
if(!$url)
return false;
$url = urlencode($url.'&access_token='.$this->_access_token);
//echo $url.'&access_token='.$this->_access_token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
$image = curl_exec($curl);
curl_close($curl);
return $image;
}
Note that the $url argument is the url provided by the contacts data returned by the Google API, it's like as the following:
https://www.google.com/m8/feeds/photos/media/{userEmail}/{contactID}
This is an exemple of an URL (according to my project) :
https://www.google.com/m8/feeds/photos/media/example%40gmail.com/ABCDEFGHIJK2345
Sometimes the contactId contains a '/'
The error message from Google is :
401. That's an error.
There was an error in your request. That's all we know.
Did I miss something?
NOTE: I tried with urlencode, urldecode and tried without using them...But I got the same problem. Also, the contacts I'm testing with have gmail photos.
You are encoding your whole url and probably which is causing the mess!?
$url = $url . '&access_token=' . urlencode($this->_access_token);
I've finally solved the problem, and this is what I did:
I changed the '&' to '?' in the $url
$url.'&access_token='.$this->_access_token
changed to :
$url.'?access_token='.$this->_access_token
Since access_token is the first parameter ... and I removed the curl, I just returned the $url as it is and put it in the image src.
Although it's somehow solved, I don't know if it's okey to put the access_token in the src of the image (which can be viewed by any client side user).

PHP Upload Image from URL to Facebook [duplicate]

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

PHP - Upload a web hosted photo to facebook album via Graph API

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

Categories