Cookie does not work in class, where is the problem?

Cookie does not work in class, where is the problem?


class Registration {

private     $user_name                  = "";

public function __construct() {

        private function registeredUserEditUser() {
        setcookie("user_name", $_POST['user_name']);
        if (empty($_POST['user_name']) ) {
            $this->errors[] = "Kullanıcı adı alanı boş";

        // elseif and continues...


@$registration = new Registration();

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="registerform" />
 <input type="text" name="user_name">
 <input type="submit" name="register" value="CREATE ACCOUNT">

You can start with getting rid of the error suppressor and never using it again and stop using PHP_SELF which is vulnerable to an XSS Attack. From the little you posted you are well on your way to a poorly written/designed class. I would suggest you learn about the SOLID Principles and take it from there. You also have no logic that checks if the form has been submitted,

1 Like

Just leave the action blank or put the name of php page that it’s being directed to. Here’s my login form as an example:

        <form class="login" action="login.php" method="post">
                <legend>Login Form</legend>
                <input type="hidden" name="action" value="{$token}">
                <label for="username">Username</label>
                <input id="username" type="text" name="username" value="" tabindex="1" autofocus>
                <label for="password">Password</label>
                <input id="password" type="password" name="password" tabindex="2">
                <input type="submit" name="submit" value="enter" tabindex="3">

This really shouldn’t be a class to begin with in my opinion as simple function would be all that is really needed.

My codes are too long, sample short code shared

No problem sending POST in class

However, the cookie does not work here

setcookie("user_name", $_POST['user_name']);

Works out of class

Where’s the mistake for the cookie?

I solved the problem
I misplaced the cookie code

Thank you for your interest

When debugging, sometimes it is easier to start with something simple that works and build on it from there.


class reg
    public function __construct($username)
        $this->username = $username;

    public function setCookie()
        return setcookie("TestCookie", $this->username);

$_POST['user_name'] = 'myUsername';
new reg($_POST['user_name']);

In case of error I wanted to use cookies for automatic filling of fields
However, this is not a cookie for the process, It was supposed to be as follows:
value="<?php if(isset($error)){ echo htmlspecialchars($_POST['user_name'], ENT_QUOTES); } ?>"

Sponsor our Newsletter | Privacy Policy | Terms of Service