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



html code:

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

工艺.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");

我收到短信,但没有照片。我不知道如何使用"发送Poto"方法发送照片。

首先,您必须存储上传的文件。

html代码中出现错误。必须添加enctype='multipart/form-data'以支持file input

所以你的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>

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);

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

您应该将图像保存在服务器中,然后将直接的下行链接传递给电报。 像这样:

//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");

注意:通过URL发送时,目标文件必须具有正确的MIME类型(例如,用于发送音频的音频/mpeg等(。

在此处阅读发送照片文档

最新更新