N
N
namikiri2012-03-15 21:26:12
PHP
namikiri, 2012-03-15 21:26:12

Cookies in PHP how?

There was a problem beaten to holes: cookies are not saved. But she's acting very strange.
In general, the first version of the engine saved some data to a file on the server, and gave the user cookies. At the same time, the HTML code was before the PHP code, and the setting of cookies was successful:

<!DOCTYPE html>
<html>
...
<?php


...

// тут какой-то код

setcookie ("authentic", $authentic);

BUT: when I started to transfer my “engine” to MySQL databases, cookies stopped being set, and instead of them this warning appears:
PHP Warning: Cannot modify header information - headers already sent by (output started at /путь к файлу:12) in /путь к тому же файлу on line 275

Line 12 is the beginning of the code (after HTML, there is <?php), and line 275 is the setcookie() function.
The code itself has changed a bit, a line has been added there:
<!DOCTYPE html>
<html>
...

<?php
include("./database.php"); // файл ЧИСТ, там НЕТ вывода вообще, только функции для базы данных, в начале BOM тоже НЕТ


...

setcookie ("authentic");

?>

What could be the problem? I’ve already smashed my whole head on the table and laptop, but I just can’t understand why, when saving in files, everything rolled, but this doesn’t work with the database.
Googled, followed all the advice (there is no BOM, the database.php file does not contain any output at all).
Please, Khabrovites, help!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
H
Hint, 2012-03-15
@namikiri

Due to buffering, no data was sent before the cookie was set. And now there is more data, PHP sends it before the setcookie is executed.
Who does not believe that this is possible, run the script:

Hello world!

<?php setcookie('test', 'test') ?>

This code works for me, cookies are set (no notice).
Now this option:
<?php for ($i = 1; $i < 500; ++$i) echo 'Hello world!
'; ?>

<?php setcookie('test', 'test') ?>

I get:
Warning: Cannot modify header information - headers already sent

In any case, all headers must be sent before the data, and you cannot rely on a standard buffer. Use ob_start.

E
egorinsk, 2012-03-15
@egorinsk

1) Learn the basics of the HTTP protocol, in particular, what are response headers
2) Read about output buffering
In theory, neither the first nor the second scheme should work at all. Cookies must be set before any output starts. MySQL has nothing to do with it.

K
krasulya, 2012-03-15
@krasulya

So you connect database.phpafter the markup begins. It is displayed before setting cookies.

I
Ivan Shalganov, 2012-03-16
@Aco

Cookies are passed in headers, this is the HTTP standard. If you started the output, then the headers are already gone, and they (the headers) cannot be sent again. Here is your problem. Start outputting data after running PHP.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question