Search code examples
phpsetcookie

It it proper to use the setcookie function inside a user defined function?


Are there any reasons why I should not use the PHP setcookie function inside a user defined function?

I'm using a setcookie function for a login script. Whenever the user logs in the script calls the function and sets the cookie.

user_login ($login_username){
setcookie("logged_in", $value, time()+3600, "/~rasmus/", "example.com", 1);
}

There are several examples in the PHP Manual where setcookie() is used inside user defined functions. http://php.net/manual/en/function.setcookie.php

However, the examples are user contributed examples and not part of the official PHP Manual.

Thank you in advance.


Solution

  • You're free to use setcookie() inside a user function.

    But. In your example, there are some things that should not work :

    1. the keyword function is missing before user_login.
    2. the $value is not defined.

    So it should be :

    function user_login ($login_username){
        setcookie("logged_in", $login_username, time()+3600, "/~rasmus/", "example.com", 1);
    }