I can't create cookies in 000webhostapp

Hello. I have a problem that I don’t know what causes it and therefore I can’t solve it.

I am working with PHP and using the MVC pattern to create a website whose API is in the same domain. I want to create cookies with the setcookie() function, using the basic parameters needed as indicated in the documentation on the official PHP website (https://www.php.net/manual/en/function.setcookie.php). When I try to create cookies on localhost and 000webhost, using a basic example script of no more than 3 lines to test this behavior, the result is different.

Screenshot_1
Screenshot_2

Localhost: works perfectly whenever I write the mentioned statement (setcookie).

Screenshot_4

000webhost: only works if I write the statement at the beginning of the PHP script. If I write even an echo before the statement (setcookie) the cookie is not created.

Screenshot_3

When using the MVC pattern, the APP performs validations and mandatory system processes before trying to create the cookies, moreover, the need to have cookies depends on situations that arise in the lifetime of the APP, therefore, there is no possibility to write the setcookie() function as the first statement of the script.

I can’t find any documentation or examples on the internet, maybe I haven’t searched well or there really aren’t any. What I want to do is to create cookies at some point in the life of the APP. The fact that it works on localhost makes me think it is possible and that it is a conflict I am having with 000webhost. Please, I am asking for help because I am stuck.

I appreciate your attention and help.

Hi!

000webhost: only works if I write the statement at the beginning of the PHP script. If I write even an echo before the statement (setcookie) the cookie is not created.

It works on localhost because your environment is very permissive. However normally it shouldn’t behave like that.

PHP sessions work based on cookies sent to the client. Cookies are sent via headers, and according to HTTP specs, headers must always be sent before body data. That is, setcookie/header/session funcs should always be invoked before echo/print/print_r.

You can append php_flag output_buffering true to .htaccess and hopefully mitigate this issue without digging too deep into your code :slight_smile:

1 Like

By making that adjustment, I get just the result I’m looking for. I am very grateful to you.