Make <a> change href=" button on each new visitor ( IP ) on a given page

Asked

Viewed 375 times

1

I have a little doubt in a project that I’m developing.

The following happens, I have 2 buttons on the page, like these ( identical in different positions ):

Top of the page:

<a target="_blank" class="btn-primary" href="http://localhost/exemplo/"> Clique Aqui </a>

End of page:

<a target="_blank" class="btn-primary" href="http://localhost/exemplo/"> Clique Aqui </a>

I need to make sure that each time the page containing these buttons is accessed by a new visitor, increase the number in the folder. Example:

If a person visited this page the first time: ( Note that the link contains /01/ )

http://localhost/exemplo/01/

When a another person accesses for the second time: ( Note that the link contains /02/ )

http://localhost/exemplo/02/

And so consecutively: (/03/, /04/, /05/, /06/, etc....)

To each new visitor on this page, that is, (with each new IP) increase the link value, increasing.

  • 4

    related http://answall.com/q/157907/4793

  • I’m gonna go check on Dani :)

  • Daniel, yes, that’s another example (adds +1 to each "F5" reload), in this example, I want you to add just to each new visitor "IP".

  • 1

    You already have the logic that solved the old question. Use that same logic and adapt it to this new business rule (the schema with IP).

  • What exactly do you need different Ips for? Another method to detect if that user has already been to the site is not enough?

  • 3

    I agree with @Danielomine the question is practically identical, just adapt the logic checking only the IP, IE can change the $file = 'exemplo.txt'; for $file = $_SERVER['REMOTE_ADDR'].'.txt';

  • 2

    @Guilhermenascimento is clearly duplicate. But since this is someone else’s, you can’t use the comments to detail the service.

  • @Guilhermenascimento But if you make this change, it will not work, as +1 will be added to each reload in the file, causing all visitors to start with "http://localhost/example/01/" and if they update, they will add +1, and the question is just add +1 for each visitor, if it is not a new visitor, the number that is written in this TXT file remains the same.

  • 2

    The $_SERVER['REMOTE_ADDR'] that @Guilhermenascimento said is precisely to resolve what you just said. It separates by IP if use as in the given example.

  • Yes @Bacco it writes a file. TXT renamed with the visitor’s IP, but what happens... As I said before, in case I access the first time, it will be "1", if I access the second "2", and so consecutively for all, IE, all will start with "1", and the right is to start from where you left off. The right would be to check if there is a file . TXT created with the IP number, if not, it will add +1 in another file . TXT, in this case this $file = 'exemplo.txt';.

  • That I don’t know how to do :(

  • 2

    is the meso example of the @Jorgeb answer. there in the other question http://answall.com/a/158024/3635 just change the $file = 'exemplo.txt'; by the visitor’s IP, and will continue where it left off, this in both file_get_contents and file_put_contents

  • I did what you said, it turns out that it creates a new file with the IP number, only that this file ex: (123.432.445.43.txt) always starts with "1". I mean, any visitor will start with http://localhost/exemplo/01/, and if reloading will increase the number, and what I want is precisely to prevent it to be increased without need, just start from where you left, and if there is no file . txt with the display IP, if +1 is added to another file exemplo.txt.

  • I guess I’ll have to ask a question about that.

  • According to this reply you just use the .htaccess, to pass the link.

  • 1

    @Alexandrelopes you have already solved the matter?

  • 1

    Yes @Jorgeb. :D Here.

  • 1

    It seems that it was solved in the duplicate question: http://answall.com/questions/167993/php-cria-arquivo-txt-com-log-de-ips-dos-visitors

Show 13 more comments

5 answers

5

I would save each IP in the database making the condition to add only if it is not already registered.

The function <? echo $_SERVER["REMOTE_ADDR"];?> takes the IP.

If this IP is not already in the bank is a new one. So the number of records in the bank is the number of different visitors.

  • Gabriel, could you make an example? I’m new to PHP :/

2

In my view, you will need to capture all individual accesses to always add +1 on this link according to the number of the visit. You can do this by maybe saving in a database very light the access number (You can record the visitor’s IP to know that it is a different visitor).

Or write to a physical file on the server.

  • Mario, could you make an example? I’m new with PHP :/

  • Preferably this example that writes to a physical file, in case it would be a correct txt? :D

1

I was just going to edit the reply of @Gabriel Gomes but ended up getting bigger than I expected.

I would record each IP in the database making the condition to add only if he is not already registered.

The function takes the IP.

If this IP is not already in the bank is a new one. So the number of bank records is the number of different visitors.

In the file . php:

$visitante = $_SERVER["REMOTE_ADDR"];
function verificarVisitasDoIP($visitante){
  if(jaExisteNoBanco($visitante)){
    return --código para pegar o numero de visitas desse IP--;
    }
    else{
      --código para salvar o $visitante em um novo registro. Faça o valor inicial ou DEFAULT ser 1 para dar certo.--;
    return 1;
    }
}

In the . js file (using jQuery):

$.post("arquivo.php, function(data,status){
  if(status == "success"){
    $(".btn-primary").attr("href", "http:\//localhost/exemplo/"+data);
  }
});

Explanation about $.load() at this link.

With that, I believe you can change.

  • Got me into this "-code for" Kkkkk, how would that be?

  • You need to store this information in a database. The "code for" would be a connection to the bank saving and bringing this information. You should keep at least the visitors' Ips and make a counter visits. When checking the visit, you search the bank if the IP has already been recorded. If not, you save the new IP and add another visit to the counter. If the IP already exists in the records, you leave the counter as is.

  • I don’t know how to do this :'(

  • But there is a catch, "If the IP already exists in the records, you leave the counter as is." , and if someone else visits, it will increase +1, so that first visitor will also get +1 if he reloads the page ?

  • 1

    Each time the page loads, the function checks the visit. The first time the registration will not be there. With an F5, the registration already counts. About not knowing database, it’s another question. You would need to implement or have someone do it for you.

  • I’m gonna test you, buddy :)

  • 1

    @Cleitonoliveira I don’t know if I got it wrong, but when posting a different answer, you did the right one, because you’re not allowed to edit answers that you’re not the author and add information that the author hasn’t posted. This is just a hint :)

Show 2 more comments

1

I strongly recommend that you follow the advice of the above comments and use a database, but only by science can you use scandir (http://php.net/manual/en/function.scandir.php) to get the last created folder.

php > var_dump(scandir('./', SCANDIR_SORT_DESCENDING));

array(5) {
  [0]=>
  string(2) "03"

  [1]=>
  string(2) "02"

  [2]=>
  string(2) "01"

  [3]=>
  string(2) ".."

  [4]=>
  string(1) "."
}

Then take the first index of the vector (Note the informed ordering argument):

$newFolderId = ((int) $scan[0]) + 1;

And finish creating a new folder with the id obtained. (http://php.net/manual/en/function.mkdir.php)

mkdir('./' . $newFolderId, 0700);

Okay, you can take advantage of the variable used to create the folder to print the link to it.

0

Dude, I made the logic for you, now just implement there and create the database, I made using mysql.

<?php
//Função que pega IP
function pegaIP(){
    $http_client_ip       = $_SERVER['HTTP_CLIENT_IP'];
    $http_x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote_addr          = $_SERVER['REMOTE_ADDR'];

    // Verifica se o IP existe na internet
    if(!empty($http_client_ip)){

        $ip = $http_client_ip;

    } elseif(!empty($http_x_forwarded_for)){// Verifica se o acesso veio de um proxy

        $ip = $http_x_forwarded_for;

    } else {//Caso não encontre das outras maneiras, pega do jeito tradicional

        $ip = $remote_addr;

    }
    return $ip;
}

//Conexão com o banco
$servidor = '';
$banco = '';
$usuario = '';
$senha = '';
$link = mysql_connect($servidor, $usuario, $senha);
$db = mysql_select_db($banco,$link);

mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');

if(!$link){
    echo "Erro ao conectar com o bando de dados!<br/>";
    echo mysql_error();
}

$IP = pegaIP();

//Query para pesquisar no banco se essa pessoa ja entrou
$querySelect = "SELECT * FROM minhaTabela WHERE ip = ".$IP;
//Executa a query
$resultSelect = mysql_query($querySelect);

//Verifica se houve erros na query
if($resultSelect){

    //Verifica se o IP ja acessou o banco (se retornar 0 não acessou porque não existe registro desse IP)
    if(mysql_num_rows($resultSelect) == 0){

        //Query para inserir o ip na tabela
        $queryInsert = "INSERT INTO minhaTabela ('ip') VALUES ('".$IP."')";
        //Executa a query
        $resultInsert = mysql_query($queryInsert);
        //Verifica se houve erros na query
        if($resultInsert){
            //Pega o id do ultimo registro inserido
            $numero = mysql_insert_id();
        }else{
            echo mysql_error();
        }

    }else{
        //Pega os dados da consulta
        $coluna = mysql_fetch_assoc($resultSelect);

        //Adciona o id da pessoa na variavel numero
        $numero = $coluna['id'];

    }

}else{
    echo mysql_error();
}

//gera o link com o ID da pessoa
echo '<a href="http://localhost/exemplo/'.$numero.'/">Link</a>';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.