Search code examples
phpphp-telegram-bot

How to "refresh" the status of file_get_contents('php://input')?


I'm triying to do a BOT for telegram using PHP code.

Basically the user have to choose between insert: 1) name 2) surname 3) address

choosing surname he have to write his surname and i want to store it into a variabile but, if i use $update = file_get_contents('php://input') i always read "surname" (which is the frist input of the user)

So i think that my problem is: how to change the content of file_get_contents('php://input') in a partical "moment" of my program?

Please read my code for more details, many thanks!!!

    <?php
$botToken = "MYTOKEN"; //token 
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents('php://input'); //updates from telegram (JSON format)
$update = json_decode($update, TRUE); 

$chatId = $update['message']['from']['id']; 
$text = $update['message']['text']; 

switch($text)
    {
    case "name";
    sendMessage ($chatId,"You write name");
    break;

    case "surname";
    sendMessage ($chatId,"You write surname"); 
    sendMessage ($chatId,"Insert your surname"); 
                /* here is my problem: what i have to do to "read" what the 
                user write now? i want to store his surname into a new 
                variable*/
    break;

    case "address";
    sendMessage ($chatId,"You write address");
    break; 

    default;
    sendMessage ($chatId,"You don't write a valid command");
    break;     
    }


function sendMessage($chatId,$text)
    {
        $url = $GLOBALS[website]."/sendMessage? 
chat_id=$chatId&text=".urlencode($text);
        file_get_contents($url);
    }
?>

Solution

  • I'm one of those who would "hack" this with Javascript to send just the data entered and the HTML element it was entered in but you are asking specifically for php://input.

    Basically, php://input returns all the raw data after the HTTP-headers of the request, regardless of the content type.

    So you could use XPath or domdocument (https://www.php.net/manual/en/class.domdocument.php) to find an element by its ID from the content you got from the "php://input" stream.