Search code examples
phphtmldiscorddiscord.js

How to get discord username from user id with a PHP site?


I'm working on a PHP site where I can search for discord users by their id (like the discord.id site already does), but I don't really have the slightest idea where to start, can someone give me a hand?

Please, I don't know what to do anymore...

I have tried searching for documentation and tutorials on the Internet but unfortunately have found nothing.


Solution

  • To get a Discord username from a user ID with PHP, you need to use the Discord API. Here's a basic example of how you can do this using the curl library in PHP:

    <?php
    $userId = 'your-user-id';
    $botToken = 'your-bot-token';
    
    $ch = curl_init();
    
    curl_setopt_array($ch, array(
        CURLOPT_HTTPHEADER => array(
            'Authorization: Bot ' . $botToken,
            'Content-Type: application/json',
        ),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => 'https://discord.com/api/users/' . $userId,
    ));
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $user = json_decode($response);
    
    echo $user->username;
    ?>
    

    In this example, replace 'your-user-id' with the user ID you're interested in, and 'your-bot-token' with your bot's token. This script sends a GET request to the Discord API's /users/{user.id} endpoint, which returns information about the user. The response is a JSON object that includes the user's username, which is printed out at the end.

    Please note that to use this endpoint, your bot needs the Identify scope, and you need to replace 'your-bot-token' with your actual bot token.

    Also, remember that making too many requests in a short period of time can lead to your bot being rate limited.