I’m trying to create a basic Telegram bot using PHP that responds to user messages through webhooks. The bot should reply when someone sends the /hello command, but I’m running into issues with the message sending part.
Here’s my current PHP code:
<?php
header('Content-Type: application/json; charset=utf-8');
$input = file_get_contents("php://input");
$update = json_decode($input, true);
$bot_token = "YOUR_BOT_TOKEN_HERE";
$user_id = $update['message']['from']['id'];
$user_text = $update['message']['text'];
if($user_text == '/hello'){
$reply_text = "Hi there!";
$api_url = "https://api.telegram.org/bot".$bot_token."/sendMessage?chat_id=".$user_id."&text=".$reply_text;
// Trying with cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $api_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
}
?>
I’m experiencing several problems:
- Using file_get_contents() gives me an HTTP 400 bad request error
- cURL method doesn’t seem to work either - no messages are sent
- When I copy the generated URL and paste it directly into my browser, it works perfectly and sends the message
I’m using Cloudflare for SSL and have set up the webhook correctly. Any ideas what might be causing this issue with the server-side execution?
Check your server’s error logs first - they’ll show exactly what’s failing. Since the URL works in your browser but not server-side, your hosting environment is probably blocking outbound requests. Most shared hosts disable external HTTP requests by default. I hit this same issue last year and had to get my host to whitelist Telegram’s API endpoints. Also make sure your webhook URL is actually receiving requests. Drop some basic logging at the start of your script to confirm the webhook triggers. Just add file_put_contents('debug.log', $input, FILE_APPEND); right after getting the input to see what data Telegram’s actually sending.
You’re missing the POST method in your curl setup. Telegram’s API requires POST requests for sendMessage, not GET. Add curl_setopt($curl, CURLOPT_POST, true); and send your data as POST fields instead of URL parameters. That’s why it works in the browser but not with curl - they handle requests differently.
I had the same issue with my first Telegram bot. Your code’s missing URL encoding for the message text - special characters and spaces will break it. Wrap urlencode() around your $reply_text variable. Also, you’re not checking if array keys exist before using them. Add isset($update['message']['text']) checks to avoid PHP warnings that kill your webhook. I’d also send a response back to Telegram - something like {"ok":true} at the end. It’s not required but it’s good practice. If the URL works in your browser but fails with cURL, it’s probably SSL issues or your server’s user agent getting blocked. Try adding curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); for testing, but fix the SSL properly before going live.