How to send images and track user count in PHP Telegram bot?

I’m building a Telegram bot using PHP and need help with two features. Here’s my current bot code:

<?php
$input = json_decode(file_get_contents('php://input'));

function processMessage($message) {
    if($message == 'Hello')
        $response = 'Hello there!';
    if($message == 'What is your name?')
        $response = 'I am ChatBot';
    if($message == 'How are you?')
        $response = 'I am doing well, thank you!';
    return $response;
}

$bot_token = 'YOUR_BOT_TOKEN';
$api_url = 'https://api.telegram.org/bot' . $bot_token . '/sendMessage?chat_id=' . $chat_id;
$api_url .= '&text=' . $response;
$result = file_get_contents($api_url);
?>

I need to add two more features:

  1. Sending photos: How can I make my bot send an image from a URL when users request it?

  2. User tracking: How do I store user IDs in a database and count total users? I want to show member count when someone sends /stats command and increment the counter when new users send /start.

Any help with implementing these features would be great!

yo mike, for images use sendPhoto instead of sendMessage: https://api.telegram.org/bot{token}/sendPhoto?chat_id={chat_id}&photo={url}. for user tracking just create a mysql table with chat_ids and check if they exist before inserting. make sure you parse the input and grab the chat_id from the json first

Your code has several issues to fix before adding features. The $chat_id and $response variables aren’t defined from the input. Extract them from the JSON first: $chat_id = $input->message->chat->id and $text = $input->message->text. For photos, use the sendPhoto endpoint with proper URL encoding. For user tracking, set up a simple SQLite database with a users table - just chat_id and join_date columns. When someone sends /start, check if they exist with a SELECT query. If they’re new, insert them and bump your counter. For /stats, count the total rows. Don’t forget to handle different message types in your main processing function.

The other answers miss some key details. When sending images, handle the API response differently - sendPhoto doesn’t work like sendMessage. Use cURL instead of file_get_contents. You’ll get better error handling and proper POST requests.

For the database stuff, set up PDO with prepared statements. Don’t skip this - it prevents SQL injection attacks.

When you build the stats feature, store a first_seen timestamp too. Trust me, you’ll want that data for analytics later.

Your message processing code needs work. Switch to a switch statement or array mapping - it’s way cleaner than what you’ve got now.

One more thing: validate that input JSON exists before processing it. Otherwise you’ll get PHP warnings every time the webhook receives bad data.