Tutorial: Script usuários simultâneos / conectados sem banco de dados

  • Autor Autor Mask7OfDragon
  • Data de início Data de início
Tradução em andamento: em alguns minutos este tópico estará em português. Por enquanto, o conteúdo está no original em espanhol. Ver original
Mask7OfDragon

Mask7OfDragon

Zeta
Verificación en dos pasos activada
Temas anteriores
1. Criar sua própria lista de música com PHP
2. Script adsense incompleto forzado de publicidad en PHP

Hola <3, Bueno estoy haciendo unos sistemas de videos y por cierto motivo necesito contar los usuarios simultaneos, pero no requiero base de datos ni nada. Como no encontre nada lo he realizado de la siguiente forma, no es recomendable hacerlo directamente en disco, recomiendo usar un sistema de cache como mencached, pero ahi les dejo la idea.

Archivo index.php
PHP:
<?php

/** Metodo para la IP del usuario */
function helper_user_ip()
{

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        //check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        //to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    } else {
        $ip = null;
    }
    return $ip;
}

/** Metodo para obtener el agent del usuario */
function helper_user_agent()
{

    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
        //check ip from share internet
        $agent = $_SERVER['HTTP_USER_AGENT'];
    } else {
        $agent = null;
    }
    return $agent;
}


$next = base64_encode(helper_user_ip() . helper_user_agent());

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Usuarios simultaneos</title>
</head>

<body>
    <div>Usuarios conectados: <a href="#" id="users">0</a></div>
    <script>
        /** Inicio */
        window.onload = start;
        async function start() {
            await fetch('/engine.php?period=<?php echo $next; ?>&event=start')
                .then(response => {
                    return response.json()
                })
                .then(data => {
                    // Work with JSON data here
                    // console.log(data)
                })
                .catch(err => {})
        }

        /** Salida */
        window.onbeforeunload = limit;
        async function limit() {
            await fetch('/engine.php?period=<?php echo $next; ?>&event=limit')
                .then(response => {
                    return response.json()
                })
                .then(data => {
                    // Work with JSON data here
                    // console.log(data)
                })
                .catch(err => {})
        }

        function events() {

            setTimeout(function() {
                fetch('/engine.php?period=<?php echo $next; ?>&event=views')
                    .then(response => {
                        return response.json()
                    })
                    .then(data => {
                        document.getElementById('users').innerHTML = data.protocol;
                    })
                    .catch(err => {
                    })
                   
                /** Consulta */
                events();

            }, 5000);
        }

        /** Consulta */
        events();
    </script>

</body>

</html>

Archivo engine.php

PHP:
<?php

/** Parametros */
$event = isset($_GET['event']) ? $_GET['event'] : false;
$period = isset($_GET['period']) ? $_GET['period'] : false;

if ($event !== false and $period !== false) {

    header('Accept: application/vnd.api+json');
    header('Content-Type: application/vnd.api+json');

    switch ($event) {
        case 'start':

            @file_put_contents('support/' . $period, time());

            /** Inicio */
            $count = 0;

            if ($handle = opendir('support/')) {
                while (false !== ($file = readdir($handle))) {
                    if ('.' === $file) {
                        continue;
                    };
                    if ('..' === $file) {
                        continue;
                    };

                    $count++;
                }
            }

            /** Respuesta */
            $response = array(
                'status' => 200,
                'protocol' => $count
            );

            echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

            break;

        case 'limit':

            @unlink('support/' . $period);

            /** Inicio */
            $count = 0;

            if ($handle = opendir('support/')) {
                while (false !== ($file = readdir($handle))) {
                    if ('.' === $file) {
                        continue;
                    };
                    if ('..' === $file) {
                        continue;
                    };

                    $count++;
                }
            }

            /** Respuesta */
            $response = array(
                'status' => 200,
                'protocol' => $count
            );

            echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);


            break;

        case 'views':

            /** Inicio */
            $count = 0;

            if ($handle = opendir('support/')) {
                while (false !== ($file = readdir($handle))) {
                    if ('.' === $file) {
                        continue;
                    };
                    if ('..' === $file) {
                        continue;
                    };

                    $count++;
                }
            }

            /** Respuesta */
            $response = array(
                'status' => 200,
                'protocol' => $count
            );

            echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);


            break;

        default:

            /** Respuesta */
            $response = array(
                'status' => 400,
                'protocol' => 'not supported'
            );

            echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

            break;
    }
} else {
    header('Accept: application/vnd.api+json');
    header('Content-Type: application/vnd.api+json');

    /** Respuesta */
    $response = array(
        'status' => 400,
        'protocol' => 'not supported'
    );

    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

crear una carpeta llamada support que sera la encargada de manejar los archivos. No es perfecto pero no requiere bases de datos y usando mencached funcionara mucho mejor que usando mysql.

<3
 
Foi útil? Participe da conversa

Com sua conta grátis você pode responder, mandar mensagem privada ao autor e comprar com Saldo retido: o pagamento é liberado quando você recebe o combinado.

Leva 30 segundos · você volta a este tópico ao terminar
Codeas todo lo que imaginas. Genial aporte estimado! 😀
 

Tópicos similares

Voltar
Topo