skip to Main Content

html code:

<form action="process.php">
     <input type="text" name="name">
 <input type="file" name="photo">
 <input type="submit" value="Submit">
</form>  

process.php:

define ('url',"https://api.telegram.org/bot****/");

$name = $_GET['name'];
$img=$_FILES['photo']['name'];
$chat_id = '****';
$message = urlencode("Name:".$name);
file_get_contents(url."sendmessage?text=".$message."&chat_id=".$chat_id."&parse_mode=HTML");

I recieve text message but photo not. I don’t know how to send photo with “sendPoto” method.

2

Answers


  1. You should save the image in your Server and then pass a direct downlaod link to telegram. like this:

    //TODO save uploded photo on myfiles/avatar1.png
    
    // send to telegram
    file_get_contents("https://api.telegram.org/bot****/sendPhoto?chat_id=1245763214&photo=http://example.com/myfiles/avatar1.png");
    

    Note: When sending by URL the target file must have the correct MIME type (e.g., audio/mpeg for sendAudio, etc.).

    Read sendPhoto document here

    Login or Signup to reply.
  2. First of all you must store the file uploaded.

    in your html code you have error. you must add enctype='multipart/form-data' to support file input.

    So your html code must be like this:

    <form action="process.php" method="post" enctype="multipart/form-data">
        <input type="text" name="name">
        <input type="file" name="photo">
        <input type="submit" value="Submit">
    </form>
    

    In your php file you must first save file uploaded.

    define ('url',"https://api.telegram.org/bot****/");
    
    $info = pathinfo($_FILES['photo']['name']);
    $ext = $info['extension']; // get the extension of the file
    $newname = "newname.".$ext;
    
    $target = 'images/'.$newname; // the path you want to upload your file
    move_uploaded_file( $_FILES['photo']['tmp_name'], $target);
    

    After that you can send this file to telegram api.

    $chat_id = '123456'; // telegram user id
    $url = url."sendPhoto?chat_id=$chat_id";
    
    $params = [
        'chat_id'=>$chat_id,
        'photo'=>'Your site address/'.$target,
        'caption'=>$_POST['name'],
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $server_output = curl_exec($ch);
    curl_close($ch);
    
    echo $server_output;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search