Foros del Web » Programando para Internet » PHP »

Contador de visitas Online

Estas en el tema de Contador de visitas Online en el foro de PHP en Foros del Web. Hola un saludo a todos, particularmente ya he navegado por este foro pero de manera como Guess, y gracias al buscador he solucionado mis problemas ...
  #1 (permalink)  
Antiguo 14/04/2009, 21:56
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Pregunta Contador de visitas Online

Hola un saludo a todos, particularmente ya he navegado por este foro pero de manera como Guess, y gracias al buscador he solucionado mis problemas sin necesidad de postear, pero ahora... estoy en una circunstancia compleja verán he estado haciendo un contador de visitas online, a claro primero que no es el contador tipico que va sumando al total de las ultimas visitas, este contador son las visitas que estan en este momento viendo una pagina web, bien hasta ahora; tengo una pagina custom en un foro SMF donde se encuentra un Chat PJIRC, ahi quiero colocar el contador (en la página custom). Ahora ese contador quiero que se muestre en cualquier parte de la web, pero sin seguir aumentando.

He tomado el siguiente codigo:

Código PHP:
<?
//Script created by Razore.co.uk under the GNU GPL


//Database variables
$server             "localhost";          // Your MySQL Server address. This is usually localhost
$db_user            "nombre_username";         // Your MySQL Username
$db_pass            "pass_username";        // Your MySQL Password
$database           "nombre_BD";          // Database Name

//Customizations
$timeoutseconds     "300";            // How long it it boefore the user is no longer online
$showlink         "0";                  // Link to us? 1 = Yes  0 = No

//Only one person is online
$oneperson1       "En la actualidad hay";  //Change the text that will be displayed
$oneperson2       "usuario online.";     //Change the text that will be displayed

//Two or more people online
$twopeople1       ="En la actualidad hay"//Change the text that will be displayed
$twopeople2       ="usuarios online.";      //Change the text that will be displayed

//The following should only be modified if you know what you are doing
$timestamp=time();
$timeout=$timestamp-$timeoutseconds;  
mysql_connect($server$db_user$db_pass) or die ("online Database CONNECT Error");                                                                   
mysql_db_query($database"INSERT INTO online VALUES ('$timestamp','$REMOTE_ADDR','$PHP_SELF')") or die("online Database INSERT Error"); 
mysql_db_query($database"DELETE FROM online WHERE timestamp<$timeout") or die("online Database DELETE Error");
$result=mysql_db_query($database"SELECT DISTINCT ip FROM online WHERE file='$PHP_SELF'") or die("online Database SELECT Error");
$user  =mysql_num_rows($result);
mysql_close();


if (
$user==1) {$archivo 'archivo.txt';
$fp fopen($archivo"w");
$string "$oneperson1 $user $oneperson2";
$write fputs($fp$string);
fclose($fp);}

else {
$archivo 'archivo.txt';
$fp fopen($archivo"w");
$string "$twopeople1 $user $twopeople2";
$write fputs($fp$string);
fclose($fp);}

//If you have chosen to support us.
switch ($showlink) {
case 
0:
   echo 
"";
   break;
case 
1:
   echo 
"<br><br><font size=\"1\">Prueba Design Online by
<a target=\"_blank\" href=\"pagina aqui\">Prueba</a></font>"
;
   break;
}
?>
Código:
#Created by Razore



#
# Table structure for table 'online'
#

CREATE TABLE online (
   timestamp int(15) DEFAULT '0' NOT NULL,
   ip varchar(40) NOT NULL,
   file varchar(100) NOT NULL,
   PRIMARY KEY (timestamp),
   KEY ip (ip),
   KEY file (file)
);
Este es el codigo del contador y el de la BD.

Bien explico el código php, se conecta a la base de datos y va agregando usuarios ("visitantes") a la tabla, se borrára despues de que haya consumado su secion 300seg, y la cadena de los valores de las variables es guardada en el archivo.txt

Ahora en la pagina del chat he colocado

Código PHP:
<?php
//This file shows you how to include the file in your php document.
include("online.php"); 
?>
Para que el usuario que entre cuente como visitante y se agregue en la tabla y escriba en el archivo.txt

Ahora hize otro archivo php, donde genera una imagen leyendo el texto que se encuentra en el archivo.txt y coloque esa imagen en cualquier parte de mi sitio web y muestre los visitantes que estan en la pagina custom del foro (que viene siendo la del chat)

el codigo es el siguiente:

Código PHP:
<?php
$archivo 
'archivo.txt';
$fp fopen($archivo"r");
$contents fread($fpfilesize($archivo));

$font imageloadfont('8x13iso.gdf');

/* I use .gdf as its extension to represents "GD Fonts" */
/* But, if your server not allow .gdf, you can change it*/
/* to any extension .jpg, .bmp, .txt, .bmf, .etc        */

$fontWidth imagefontwidth($font);
$fontHeight imagefontheight($font);
$im imagecreate(strlen($contents) * $fontWidth$fontHeight);
$bgColor imagecolorallocate($im255255255);
$fgColor imagecolorallocate($im,   0,   0255);
imagestring($im$font00$contents$fgColor);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
fclose($fp);
?>
Generá la imagen de acuerdo el contenido del archivo.txt

Ahora las siguientes cuestiones que me complican es como puedo actualizar la base de datos de la tabla online cuando no haya visitantes dentro de la pagina del chat y asi escriba en el archivo.txt que "Hay 0 usuarios en linea"

Cabe aclarar que va agregando los datos a la tabla y al terminar su secion va borrando los datos en la BD pero no borra la ultima secion y se queda guardada.

La verdad no se si me complique la vida, pero no quiero usar un contador gratuito.

Solo quiero mostrar el # de visitantes que estan "en este tiempo en linea" en la pagina del chat y mostrarlo en otras paginas sin aumentar el contador.

Espero y me ayuden a resolver algo, agrego que no soy muy experto en PHP pero he estado leyendo las funciones y eso ahora si que me declaró un novato.
  #2 (permalink)  
Antiguo 15/04/2009, 17:47
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Respuesta: Contador de visitas Online

Bueno creo que es algo complicado.
  #3 (permalink)  
Antiguo 15/04/2009, 21:24
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Contador de visitas Online

pues si.... tal ves haces cosas muy complejas!

aquí dejo una funcion simple... que hace lo que indicas, incluso... puedes usarla donde quieras...

Código PHP:
/**
 * (nulo)
 *
 * Comprueba y devuelve el numero de usuarios activos.
 */
function actives()
{
    
$remote $_SERVER['REMOTE_ADDR'];

    
$tmp '/ruta/del/archivo.txt'// <-- indispensable

    
$arr file($tmp);

    
$cur false;
    
$new // marca !
            
sprintf("\n%s\t%d"$remotetime());


    
// iteramos las lineas
    
foreach ($arr as $i => $val)
    {
        if ( ! 
trim($val))
        {
            unset(
$arr[$i]);
            continue;
        }

        
// -- separamos !
        
list($addr$old) = explode("\t"$val);

        
// cada 15mins.
        
if ((time() - $old) > 260)
        { 
// eliminamos viejos..
            
unset($arr[$i]);
        }
        elseif (
$addr === $remote)
        { 
// actualizamos...
            
$arr[$i] = $new;
            
$cur true;
        }
    }

    if ( ! 
$cur)
    { 
// nuevo?
        
$arr []= $new;
    }

    
// al archivo !
    
$old fopen($tmp'w+');
    
fwrite($oldjoin(''$arr));
    
fclose($old);

    
$out sizeof($arr);
    return 
$out;


espero te sirva, suerte!
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #4 (permalink)  
Antiguo 16/04/2009, 16:29
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Respuesta: Contador de visitas Online

Podrias explicarme un poco mas de esta funcion por favor, la verdad no se como emplearla.
  #5 (permalink)  
Antiguo 16/04/2009, 16:45
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Contador de visitas Online

solo cambia la ruta del archivo dentro de la funcion...

Código PHP:
//ejemplo
$tmp 'usuarios.txt'// <-- indispensable 
esta funcion guardala en un script para incluirla después... puedes incluirla en algún script de funciones que mas uses...


cargas el include una ves, de preferencia al inicio del script...
Código PHP:
include 'el_script_que_guardaste.php'
después, donde quieras usarla...

Código HTML:
<p>Usuarios on-line: <?php echo actives(); ?></p> 
espero te sirva...
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #6 (permalink)  
Antiguo 30/04/2009, 18:15
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Respuesta: Contador de visitas Online

A ver estoy tratando de usar tu contador pero no se, esta completo tu codigo?

Ya que le he colocado las <? php y ?> por que no se la verdad como termine.

Estoy usando un foro SMF, y la verdad me sale lo siguiente error:

Parse error: syntax error, unexpected T_FUNCTION in /home/seedro/domains/seedro.com/public_html/contador/1contador.php on line 7
  #7 (permalink)  
Antiguo 30/04/2009, 20:56
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Contador de visitas Online

¿pues como esta el código de tu script???

este script si funciona, pues esta probado....
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #8 (permalink)  
Antiguo 01/05/2009, 11:23
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Respuesta: Contador de visitas Online

Código PHP:
<?php

function template_main()
{
global 
$context$scripturl$boardurl ;
//Text To Display If No Guests Allowed Is On
$guesttext '<a href="'$boardurl '/index.php?action=register ">Register Today</a></br> Chat is not enabled for guests.';




echo
' <br></br> ';

echo 
'
<BODY text=black marginheight="0"
marginwidth="0" topmargin="0" leftmargin="20" link="#666666" background="images/colorsin2.jpg">
<table width="690" border="0" cellspacing="0" cellpadding="0" vspace="0" align="center" height="60">
  <tr>
    <td width="596" valign="bottom">
      <div align="left">
        <img border="0" src="images/seedradio.gif" width="231" height="97"><br>
        <embed type="application/x-mplayer2" src="enlace ala radio" name="NSPlay" pluginspage="enlace al plugin&amp;sbp=mediaplayer&amp;ar=media&amp;sba=plugin" showdisplay="0" showstatusbar="1" autostart="True" height="50" width="300"></div>
    </td>
  </tr>
</table>
<TABLE cellSpacing=0 cellPadding=0 width=690 border=0 vspace="0" align="center">
  <TR>
    <TD vAlign=top align=left width=30 height="22"></TD>
    <TD vAlign=top colSpan=3 height="22" >
      <table border="0" cellspacing="0" cellpadding="0" align="right"  height="20">
        <tr>
          <td width="20" height="19"><img src="images/left1.gif" width="20" height="20"></td>
          <td height="19" background="images/barra1.png">
            <div align="center"><font color="#666666" face="Arial, Helvetica, sans-serif" size="2"><b>
                <a href="enlace a home /"TARGET=”_blank”>Home</a></b></font></div>
          </td>
          <td width="40" height="19"><img src="images/right1.gif" width="20" height="20"><img src="images/left1.gif" width="20" height="20"></td>
          <td height="19" background="images/barra1.png">
            <div align="center"><b>
                <font face="Arial, Helvetica, sans-serif" size="2">
                <a href="enlace a foros " TARGET=”_blank”>Foro</a></font></b></div>
          </td>
          <td width="40" height="19" ><img src="images/right1.gif" width="20" height="20"><img src="images/left1.gif" width="20" height="20"></td>
          <td height="19" background="images/barra1.png">
            <div align="center"><font color="#666666" face="Arial, Helvetica, sans-serif" size="2"><b>
                <a href="enlace a soporte" TARGET=”_blank”>Soporte</a></b></font></div>
          </td>
          <td width="20" height="19"><img src="images/right1.gif" width="20" height="20"></td>
          <td width="20" height="19" ><img src="images/left1.gif" width="20" height="20"></td>
          <td height="19" background="images/barra1.png">
            <div align="center"><b>
                <font face="Arial, Helvetica, sans-serif" size="2">
                <a href="enlace a registro" TARGET=”_blank”>Registra tu
                Nick</a></font></b></div>
          </td>
          <td width="20" height="19" ><img src="images/right1.gif" width="20" height="20"></td>
        </tr>
        <tr bgcolor="#9999FF">
          <td colspan="10" height="1".><img src="images/line1.gif" width="1" height="1"></td>
        </tr>
      </table>
    </TD>
    <TD vAlign=top align=right width="30" height="22"></TD>
  </TR>
  <TBODY>
  <TR>
    <TD vAlign=top align=left width=30 height=438 bgcolor="#FFFFFF"><img src="images/top_left.gif" width="30" height="30"><img border="0" src="images/barraizq.png" width="30" height="408"><BR>
    </TD>
    <TD vAlign=top colSpan=3 bgcolor="#FFFFFF"> <br>
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td height="18" width="9"><img src="images/gph2.gif" width="9" height="18"></td>
          <td height="18" bgcolor="#084079"><b>
            <font face="Verdana, Arial, Helvetica, sans-serif" size="2" color="#FFFFFF">
            SeeDRadio Web Chat</font></b></td>
          <td height="18" width="9"><img src="images/gph1.gif" width="9" height="18"></td>
        </tr>
      </table>
      <br>
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td valign="top" width="100%"><iframe src ="iframe del webchat" width="100%" height="407" name="chat" title="Chat" border="0" frameborder="0"> </iframe>
</td>
        </tr>
      </table>

    </TD>
    <TD vAlign=top align=right width="30" height="438" bgcolor="#FFFFFF"><img src="images/top_right.png" width="30" height="30">
      <BR>
      <img border="0" src="images/barraderecha.png" width="30" height="408"><BR>
    </TD>
  </TR>
  <TR>
    <TD vAlign=top align=left width=30 ><img src="images/bottom_left.gif" width="30" height="30"></TD>
    <TD colSpan=3>
    <img border="0" src="images/barraabajo.png" width="630" height="30"></TD>
    <TD vAlign=top align=right  width="30"><img src="images/bottom_right.gif" width="30" height="30"></TD>
  </TR>
  </TBODY>
</TABLE>
<table width="690" border="0" cellspacing="0" cellpadding="0" vspace="0" align="center">
  <tr>
    <td height="30">
      <div align="center"><font face="Arial, Helvetica, sans-serif" size="2" color="#FFFFFF">
        Copyright © 2008 SeeDRO. All Rights Reserved</font></div>
    </td>
  </tr>
</table>
</BODY>

'
;

}

?>
Este template necesito que se inserte el contador, y cuente las personas que estan viendo siempre la pagina y me lo muestre en cualquier parte del sitio.
  #9 (permalink)  
Antiguo 01/05/2009, 11:57
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Contador de visitas Online

pues es fácil... solo agrega la funcion actives() en el mismo script, si es que se va a cargar siempre!!

Código PHP:
function actives() { /* ... */ }

// ...

function template_main() {
  
// ...

  
echo '<p>Activos: ' actives() . '</p>';

  
// ...

NOTA: no olvides modificar la variable $tmp en la función actives()


suerte...
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #10 (permalink)  
Antiguo 01/05/2009, 13:40
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Respuesta: Contador de visitas Online

Código PHP:
/**
 * (nulo)
 *
 * Comprueba y devuelve el numero de usuarios activos.
 */
function actives()
{
    
$remote $_SERVER['REMOTE_ADDR'];

    
$tmp '/ruta/del/archivo.txt'// <-- indispensable

    
$arr file($tmp);

    
$cur false;
    
$new // marca !
            
sprintf("\n%s\t%d"$remotetime());


    
// iteramos las lineas
    
foreach ($arr as $i => $val)
    {
        if ( ! 
trim($val))
        {
            unset(
$arr[$i]);
            continue;
        }

        
// -- separamos !
        
list($addr$old) = explode("\t"$val);

        
// cada 15mins.
        
if ((time() - $old) > 260)
        { 
// eliminamos viejos..
            
unset($arr[$i]);
        }
        elseif (
$addr === $remote)
        { 
// actualizamos...
            
$arr[$i] = $new;
            
$cur true;
        }
    }

    if ( ! 
$cur)
    { 
// nuevo?
        
$arr []= $new;
    }

    
// al archivo !
    
$old fopen($tmp'w+');
    
fwrite($oldjoin(''$arr));
    
fclose($old);

    
$out sizeof($arr);
    return 
$out;

A ver este codigo lo guardo como php? pero le agrego las citas <? o que onda es a lo que me refieor o se lo agrego a mi template del chat?
  #11 (permalink)  
Antiguo 01/05/2009, 14:10
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Contador de visitas Online

dos cosas:

si lo vas a guardar en otro archivo, obviamente necesita <?php y ?> para que se interprete como PHP ¿no lo crees ??? (de esta forma tendrías que usar include para poder usarlo)

si lo quieres copiar directamente en tu script donde va a funcionar, pues hazlo! (sigue el pseudo-ejemplo que coloque anteriormente)


¿¿nunca has trabajado con funciones o includes antes??

me extraña, siendo algo tan básico...
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #12 (permalink)  
Antiguo 01/05/2009, 14:14
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Respuesta: Contador de visitas Online

Disculpa pero ahi muestra el error que me tira. ya habia puesto las citas y me sigue saliendo el mismo error.

Lo que intento es que el Activos lo muestre a fuera de otra pagina no se si me entiendas. Y si ya agregue todas las funciones y todo como tu pseudo ejemplo.

Última edición por DarkCo0oL; 01/05/2009 a las 14:23
  #13 (permalink)  
Antiguo 01/05/2009, 14:25
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Contador de visitas Online

NOTA que si la necesitas agregar en alguna librería de funciones, pues hazlo.... pero no olvides que ya no es necesario re-agregarla en cualquier otro script, solo debes incluir tu script de funciones y utilizar la función...

¿¿que error te sale??
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #14 (permalink)  
Antiguo 01/05/2009, 14:55
 
Fecha de Ingreso: abril-2009
Mensajes: 27
Antigüedad: 15 años
Puntos: 0
Respuesta: Contador de visitas Online

Ya funciono, lo que ocurria es que era la direccion tan compleja que le habia puesto, me deje de problemas y lo coloque donde mismo donde esta el archivo template del chat, ahora ando observando, cada cuando el activo deja de ser ahora si inactivo?

Edit: Ok dura 15min, ok ahora quiero saber si existe algo para que ese tiempo se reestablesca mientras el usuario tenga la ventana abierta? Y como mostrar que hay 0 activos dentro del chat en ese momento.

Última edición por DarkCo0oL; 01/05/2009 a las 16:28
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 18:32.