Skip to content
This repository was archived by the owner on Sep 2, 2025. It is now read-only.

Commit 0b866d3

Browse files
authored
Merge pull request #139 from DJTommek/pr/attachments-fclose
Pr/attachments fclose
2 parents d816bfd + 20bbc47 commit 0b866d3

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
include __DIR__.'/basics.php';
6+
7+
use React\EventLoop\Factory;
8+
use unreal4u\TelegramAPI\HttpClientRequestHandler;
9+
use unreal4u\TelegramAPI\Telegram\Methods\SendDocument;
10+
use unreal4u\TelegramAPI\Telegram\Types\Custom\InputFile;
11+
use unreal4u\TelegramAPI\TgLog;
12+
13+
$loop = Factory::create();
14+
$tgLog = new TgLog(BOT_TOKEN, new HttpClientRequestHandler($loop));
15+
16+
// File name shown in Telegram clients has exactly same name as file is saved on system. So if we want to upload
17+
// file but with different name, we have to rename it or in this example, copy it as new name.
18+
// Later, after Telegram request is completed, temporary file can be easily deleted
19+
$tempFilePath = sprintf('%s/binary-test-data/%s/custom-file-name.txt', __DIR__, uniqid());
20+
mkdir(dirname($tempFilePath));
21+
copy(__FILE__, $tempFilePath);
22+
23+
$sendDocument = new SendDocument();
24+
$sendDocument->chat_id = A_USER_CHAT_ID;
25+
$sendDocument->document = new InputFile($tempFilePath);
26+
$sendDocument->parse_mode = 'HTML';
27+
$sendDocument->caption = sprintf('Uploaded file was originaly named as <b>%s</b> but display name in Telegram client is <b>%s</b>', basename(__FILE__), basename($tempFilePath));
28+
29+
$promise = $tgLog->performApiRequest($sendDocument);
30+
31+
$promise->then(
32+
function ($response) use ($tempFilePath) {
33+
echo '<pre>';
34+
var_dump($response);
35+
echo '</pre>';
36+
37+
// Delete temporary file and directory after upload to Telegram server is completed
38+
if (@unlink($tempFilePath) && @rmdir(dirname($tempFilePath))) {
39+
var_dump('Temporary file and folder were deleted.');
40+
} else {
41+
var_dump('Error while deleting temporary file or directory:', error_get_last());
42+
}
43+
},
44+
function (\Exception $exception) {
45+
// Onoes, an exception occurred...
46+
echo 'Exception ' . get_class($exception) . ' caught, message: ' . $exception->getMessage();
47+
}
48+
);
49+
50+
$loop->run();

src/InternalFunctionality/PostOptionsConstructor.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ private function appendMediaStream(Builder $builder, array $multipartData): Buil
170170
stream_get_contents($mediaStream['stream']),
171171
pathinfo($mediaStream['filename'], PATHINFO_BASENAME)
172172
);
173+
fclose($mediaStream['stream']);
173174

174175
$builder->append($appendingData);
175176
}

0 commit comments

Comments
 (0)