简体   繁体   English

从表单输入上传照片和文本并使用 php 发送到电报机器人

[英]upload photo and text from form input and sending to telegram bot with php

html code: html代码:

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

process.php:进程.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.我不知道如何使用“sendPoto”方法发送照片。

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 (eg, audio/mpeg for sendAudio, etc.).注意:当通过 URL 发送时,目标文件必须具有正确的 MIME 类型(例如,sendAudio 的音频/mpeg 等)。

Read sendPhoto document here在此处阅读 sendPhoto 文档

First of all you must store the file uploaded.首先,您必须存储上传的文件。

in your html code you have error.在您的html代码中,您有错误。 you must add enctype='multipart/form-data' to support file input .您必须添加enctype='multipart/form-data'以支持file input

So your html code must be like this:所以你的html代码一定是这样的:

<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.在您的php文件中,您必须首先保存上传的文件。

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.之后,您可以将此文件发送到电报 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM