如何在PHP中查找含视频或图片的Telegram嵌入HTML代码及在浏览器等环境使用Telegram Core API
Let me break down both questions for you clearly, based on my experience working with Telegram's APIs and embedding systems:
Extracting or generating Telegram's embedded HTML for media depends on pulling content from public Telegram links or processing existing HTML. Here's a practical, step-by-step approach:
Step 1: Fetch the Telegram Share Page HTML
Public Telegram channel/post links (likehttps://t.me/c/CHANNEL_ID/MESSAGE_ID) serve a web page with embedded media. Use PHP'sfile_get_contentsor cURL to grab this page—make sure to set a valid User-Agent to avoid being blocked by Telegram's anti-scraping measures.Example code:
$telegramUrl = 'https://t.me/c/123456/789'; $context = stream_context_create([ 'http' => [ 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36\r\n" ] ]); try { $pageHtml = file_get_contents($telegramUrl, false, $context); if (!$pageHtml) throw new Exception("Failed to fetch Telegram page"); } catch (Exception $e) { echo "Error: " . $e->getMessage(); exit; }Step 2: Parse HTML to Extract Media Embeds
Use PHP'sDOMDocumentto parse the fetched HTML and filter out media elements. Telegram hosts media oncdn.telesco.pe, so we can use that to target valid images and videos.Example for extracting image embeds:
$dom = new DOMDocument(); libxml_use_internal_errors(true); // Suppress HTML parsing warnings $dom->loadHTML($pageHtml); libxml_clear_errors(); // Extract and generate image embed code $imageElements = $dom->getElementsByTagName('img'); foreach ($imageElements as $img) { $src = $img->getAttribute('src'); if (str_contains($src, 'cdn.telesco.pe')) { $embeddedImg = '<img src="' . htmlspecialchars($src) . '" alt="Telegram Media" style="max-width: 100%;">'; echo $embeddedImg; } }Example for extracting video embeds:
// Extract and generate video embed code $videoElements = $dom->getElementsByTagName('video'); foreach ($videoElements as $video) { $source = $video->getElementsByTagName('source')->item(0); if ($source && str_contains($source->getAttribute('src'), 'cdn.telesco.pe')) { $embeddedVideo = '<video controls style="max-width: 100%;"> <source src="' . htmlspecialchars($source->getAttribute('src')) . '" type="' . $source->getAttribute('type') . '"> </video>'; echo $embeddedVideo; } }Important Notes
- This only works for public Telegram content. Private channels/posts require authentication, which adds complexity and isn't recommended due to Telegram's terms of service.
- Avoid aggressive scraping—Telegram may block your IP if you make too many requests in a short time.
Telegram's Core API (MTProto) is a binary protocol built for native apps, but you can use it in non-native environments like browsers with a couple of workarounds. Here are the most reliable methods:
Method 1: Use a JavaScript MTProto Library
Libraries like telegram-mtproto-js wrap MTProto in WebSocket/HTTP tunnels, making it usable in browsers. Here's how to set it up:
Register a Telegram App
First, get yourapi_idandapi_hashby registering a Telegram application via their official developer portal (you’ll need a Telegram account to complete this).Implement the Client
You can install the library via npm, or include it via a CDN. Here's a basic login workflow example:// Install via npm first: npm install telegram-mtproto const { MTProto } = require('telegram-mtproto'); const apiConfig = { layer: 158, // Use the latest layer (check Telegram's docs for updates) initConnection: 0x69796de9, api_id: YOUR_API_ID, // Replace with your registered API ID api_hash: 'YOUR_API_HASH', // Replace with your registered API hash }; const serverConfig = { dev: false, // Set to true if using Telegram's test servers }; const client = new MTProto({ api: apiConfig, server: serverConfig }); // Request a verification code for the user's phone number async function requestVerificationCode(phoneNumber) { try { const response = await client('auth.sendCode', { phone_number: phoneNumber, settings: { _: 'codeSettings' }, }); return response.phone_code_hash; // Save this for the sign-in step } catch (error) { console.error('Error requesting verification code:', error); } } // Sign in using the verification code async function signInUser(phoneNumber, code, codeHash) { try { const user = await client('auth.signIn', { phone_number: phoneNumber, phone_code_hash: codeHash, phone_code: code, }); console.log('Successfully logged in:', user); } catch (error) { console.error('Sign-in failed:', error); } }
- Caveats
- Browsers don't support raw TCP connections, so the library uses WebSockets or HTTP polling. Ensure your hosting supports WebSockets if deploying this.
- Cross-origin issues may arise if your frontend is hosted on a different domain—most libraries handle this via their own proxy endpoints, but test thoroughly.
Method 2: Use a Backend Proxy (Recommended for Production)
For a more stable and secure setup, build a backend service (using PHP, Python, Node.js, etc.) that interacts with the MTProto API, then have your browser frontend communicate with this backend via HTTP/REST.
Example workflow:
- Frontend sends a request to your backend (e.g.,
POST /api/telegram/get-messages). - Backend uses a server-side MTProto library (like
mtproto-phpfor PHP) to call the Telegram Core API. - Backend returns formatted, easy-to-use data to the frontend.
- Why This is Better
- No CORS or WebSocket limitations to worry about.
- You can handle rate limiting, caching, and authentication logic on the backend.
- Your
api_idandapi_hashstay secure—never expose them directly in frontend code!
内容的提问来源于stack exchange,提问作者Ehsan Jeihani




