How to get user/visitor name and write it on the screen?

Asked

Viewed 228 times

0

Do you know how to ask the user name and use? I’m setting up a website that is also a virtual store. I want the store to be nice to whoever comes in, Asking for a name, being nice, saying, "Okay, that item went to your cart, Amanda." But I’d like to know, how do I ask the person’s name, and save it on a cookie? And How can I use the name in the entire site with the cookie? I’ve looked, but just ask the name, and don’t use it. Just welcome. I would like to use the code throughout the site, paying off the user, talking to him. For this, I believe a cookie is needed.

Thank you.

  • 2

    Hugo, I think what you need is to use Sesssions ($_SESSIONS in php), not cookies. Take a look here: http://blog.thiagobelem.net/learning-a-usar-sessoes-no-php/

  • Interesting comment. But it’s not what I’m looking for. Thank you :)

  • 2

    Okay, good luck then =)

3 answers

2

To save a name to the cookie:

setcookie("nome", "Nome da Pessoa", time()+3600, "/");

To use the cookie:

echo $_COOKIE["nome"];

You can set the time to as much as you want. In the example is about to expire in an hour (3600 seconds).

  • I am not the author of the question and I am sorry to relive this question, but your answer was of great help to me, I thank you very much

  • 1

    Thanks for the feedback @Victorgomes, it’s always nice to be able to help..

1

I don’t see what problem you’re having.

window.String.prototype.novaString=function(de,ate){
    try{
        return this.split(de)[1].split(ate)[0];
    }catch(e){}
    return;
}
if(!document.cookie.novaString("nome=",";")){
    document.cookie="nome="+prompt("Digite seu nome:","");
}
document.getElementById("carrinho").onclick=function(e){
    alert("Pronto, Esse item foi para seu carrinho, "+document.cookie.novaString("nome=",";")+".");
}
<input value="Adicionar ao carrinho" type="button" id="carrinho">

http://jsfiddle.net/wdurzz3s/

1

An alternative with Javascript is to use window.sessionStorage or window.localStorage, the explanation for deciding when to use one or the other has already been answered here.

DEMO at Jsfiddle

if(window.sessionStorage){

    if(!sessionStorage.getItem("nome")){
        // Não há um valor definido ainda, então é exibido o prompt para ser inserido o nome.
        // Se o usuário não preenchê-lo, será utilizado o valor "usuário" para referir-se a ele.
        var nome = prompt("Qual o seu nome?") || "usuário";
        sessionStorage.setItem("nome", nome);
    }

    // Há um valor definido, então a mensagem é exibida.
    alert("Olá " + sessionStorage.getItem("nome") + "!");
}

PS: For what you are intending to do, the solution and the link pointed in the comments by rafaels88 is the best choice.

Browser other questions tagged

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