Search code examples
phpservermultiplayer

How to handle global variables to be tha same for all users in PHP?


I want to create simple multiplayer game with php using global variables that will be shared among all users, without using sockets.

I tried write php server that have on global variable called "connections" and code to handle GET request with url parameter that called "myName". when the user send the GET request to the php server, "connections" is incremented and sent back to the user as the GET response.

<?php
    $connections = 0;
    if(isset($_GET['myName'])) {
        $connections = $connections+ 1;
        echo json_encode($connections);
        exit();
    }
?>
<html>
    <head>
    </head>
        <body>
        <form action="Test/testServer.php">
            <input type="text" name="myName">
            <input type="submit" value="submit">
        </form>
    </body>
</html>

I am new to php and perhaps i missing something about how php server is actually work. I expected the "connections" to be the number of connected users that send GET request along all the "server life".


Solution

  • PHP is a Server side language, once the program is executed, the state of everything is forgot. Therefore, in the next request, unless stored in cache, it will not exist.

    However, you can use the likes of a Database to store data. You can connect to your Database like so:

    new PDO('mysql:host=localhost;dbname=yourDb;charset=utf8mb4', 'username', 'password', array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ));
    

    To execute, you can use Prepared statements.

    // (new PDO) is your pre-instanced PDO
    $stmt = (new PDO)->Prepare('SELECT id FROM test WHERE email = ? LIMIT 1');
    $stmt->execute(array('[email protected]'));
    $stmt->fetch(); // Array ( 'id' => (int) 1 )
    

    In your case, you would need to set up a Database to register connections. When a new player joins, for a utter basic (no security) example, you could store his ID.

    session_start();
    // new PDO is your pre-instanced PDO
    $con = new PDO;
    $con->Prepare('INSERT INTO players (username) VALUES (?)')->execute(array('foo'));
    $_SESSION['player.id.insecure'] = $con->lastInsertId();
    

    Then, what you are trying to achieve all comes down to your infrastructure. You can read more on PDO here.