Почему setcookie выдает ошибку

Пытаюсь реализовать простую авторизацию на сайте. Но setcookie не работает, выдаётся такое предупреждение:

Warning: Cannot modify header information — headers already sent by (output started at T:homelocalhostwwwTICSPsitephpsend_autorisation.php:1) in T:homelocalhostwwwTICSPsitephpsend_autorisation.php on line 8

Вот php код:

<?php
$login = filter_var(trim($_POST[«login»]), FILTER_SANITIZE_STRING);
$password = filter_var(trim($_POST[«password»]), FILTER_SANITIZE_STRING);
$mysql = new mysqli(‘localhost’, ‘root’, », ‘ticsp’);
$result = $mysql->query(«SELECT * FROM `autorisation` WHERE `login` = ‘$login’ AND `password` = ‘$password'»);
$user = $result->fetch_assoc();
if (count($user) != 0) {
setcookie(‘admin’, ‘name’, time() + 3600, «/»);
echo «correct_data»;
}
else {
echo «incorrect_data»;
exit();
}
$mysql->close();
?>

Помогите, пожалуйста, разобраться в проблеме. Спасибо.

I’ve made a login, that sets a cookie with a value of the imputed email address, so in the global.php file, it stores an array of the users data using:

$email = $_COOKIE["PeopleHub"];
$getuserdata = mysqli_query($con, "SELECT * FROM Earth WHERE email='$email'");
$userdata = mysqli_fetch_array($getuserdata, MYSQLI_ASSOC);

The cookie isn’t being set, I know this because I made a test file:

echo $_COOKIE["PeopleHub"];

It just made a blank page.

The login code (where the cookie is set):

<?php 
include "global.php";    
?>
<h2>Login</h2>
<?php 
    echo "We currently have <b>" . $usercount . "</b> members, <b>" . $onlinecount . "</b> of which are online. "; 
?>
<br>
<br>
<?php 
    if(isset($_POST["email"])){ 
        $email = $_POST["email"];
        $password = sha1($_POST["password"]);
        $check = mysqli_query($con, "SELECT * FROM Earth WHERE `email`='$email' AND `password`='$password'");
        $check = mysqli_num_rows($check);
        if($check == 1){
        setcookie("PeopleHub", $email, 0, '/');
        echo "We logged you in!";
        }
        else { 
            echo "We couldn't log you in!";
        }
    }
?>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
    Email <input name="email" placeholder="Email Address" required="" type="text"><br>
    Password <input name="password" placeholder="Password" required="" type="password"><br>
    <input type="reset" value="Start Over">
    <input type="submit" value="Login">
</form>

Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

1

08.09.2010, 14:38. Показов 20269. Ответов 25

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Вот у меня код:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
include("connect.php");
$result=mysql_query("SELECT login,password FROM users");
while ($myrow=mysql_fetch_assoc($result)) {
    if ($_POST['login']==$myrow['login'] and $_POST['password']==$myrow['password']) {
        setcookie("log","AAA",time()+10);
        $_SESSION['userloggedin']=true;
        $_SESSION['login']=$myrow['login'];
        break;
    }
}
 
if ($_SESSION['userloggedin']!=true) {
    $_SESSION['mistace']="not_right_password";
    if ($_POST['login']) {$_SESSION['sentlogin']=$_POST['login'];}
    header("Location: ".$_SERVER['HTTP_REFERER']);
    exit();
} else {
    $_SESSION['mistace']="user_logged_in";
    if ($_SERVER['HTTP_REFERER']) {
        header("Location: ".$_SERVER['HTTP_REFERER']);
    } else {
        header("Location: ../index.php");
    }
    exit();
}

Но куки не ставятся((( В чём дело?

Добавлено через 5 минут
Дело в том, что куки видны только для данной страницы, на странице в пред. каталоге не рабоает, хотя хост тот же.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

08.09.2010, 14:38

Ответы с готовыми решениями:

Не работает setcookie
Доброго времени суток.Дело в том,что при переносе кода на хостинг у меня возникла проблема с…

SetCookie и БД
Приветствую вас, братья программисты! :handshake: У меня появилась проблема в написании одного…

setcookie
Проблема в куках. На одной странице они создаются, на другой выводятся. Код первой страницы:…

Ошибка setcookie
Здравствуйте. Такая проблема. Скрипт голосования не сохраняет куки. Скрипт:
&lt;?php
include_once…

25

Nazz

WEB-developer

898 / 729 / 80

Регистрация: 12.03.2009

Сообщений: 2,804

Записей в блоге: 2

08.09.2010, 15:49

2

а так что пишет?

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
error_reporting(E_ALL);
include("connect.php");
$result=mysql_query("SELECT login,password FROM users");
while ($myrow=mysql_fetch_assoc($result)) {
        if ($_POST['login']==$myrow['login'] and $_POST['password']==$myrow['password']) {
                setcookie("log","AAA",time()+10);
                $_SESSION['userloggedin']=true;
                $_SESSION['login']=$myrow['login'];
                break;
        }
}
 
if ($_SESSION['userloggedin']!=true) {
        $_SESSION['mistace']="not_right_password";
        if ($_POST['login']) {$_SESSION['sentlogin']=$_POST['login'];}
        header("Location: ".$_SERVER['HTTP_REFERER']);
        exit();
} else {
        $_SESSION['mistace']="user_logged_in";
        if ($_SERVER['HTTP_REFERER']) {
                header("Location: ".$_SERVER['HTTP_REFERER']);
        } else {
                header("Location: ../index.php");
        }
        exit();
}



1



Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

08.09.2010, 18:36

 [ТС]

3

Nazz,

PHP
1
Warning: Cannot modify header information - headers already sent by (output started at Z:homelocalhostwwwcursphpscriptscomein.php:8) in Z:homelocalhostwwwcursphpscriptscomein.php on line 23

Но и без этого он показывает то же самое. Cookies создаются только для этой страницы!



0



1957 / 796 / 89

Регистрация: 03.11.2009

Сообщений: 3,066

Записей в блоге: 2

08.09.2010, 18:48

4

Hagrael, это весь код? Просто в ошибке сказано, что вывод был в 8 строке этого файла… А там

Цитата
Сообщение от Nazz
Посмотреть сообщение

$_SESSION[‘login’]=$myrow[‘login’];

Добавлено через 2 минуты
Hagrael, а в браузере есть устанавливаемая кука?Или она удаляется при переходе на другую страницу? В таком случае, нужно посмотреть, как Вы используете эту куку на другой странице…



1



БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

08.09.2010, 19:35

 [ТС]

5

romchiksoad, извините, но я не понял.



0



1957 / 796 / 89

Регистрация: 03.11.2009

Сообщений: 3,066

Записей в блоге: 2

08.09.2010, 20:59

6

Hagrael, ничего страшного Вы весь код скопировали на форум?
Как Вы работаете с куками на других страницах?



1



Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 13:34

 [ТС]

7

romchiksoad, я пишу

PHP
1
print_r($_COOKIE)

выводит только PHPSESSID.

Добавлено через 11 секунд
И да, это весь код.



0



68 / 61 / 11

Регистрация: 10.08.2009

Сообщений: 226

09.09.2010, 16:40

8

Лучший ответ Сообщение было отмечено Kerry_Jr как решение

Решение

Ошибка говорит о том, что перед вызовом setcookie где-то что-то уже выводится. А этого быть не должно. Куки должны устанавливаться до любого другого вывода.

И еще. Автор извини, но это бредовый способ проверять логин-пароль, прокручивая в цикле все строки базы. SQL жеж нуна использовать по прямому назначению.



0



Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 16:55

 [ТС]

9

ILA, типа

PHP
1
$result=mysql_query("SELECT password FROM users WHERE login='".$_POST['login']."'");

так надо?



0



WEB-developer

898 / 729 / 80

Регистрация: 12.03.2009

Сообщений: 2,804

Записей в блоге: 2

09.09.2010, 17:51

10

да, именно так будет лутше))



0



БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 18:47

 [ТС]

11

)) Действительно, а то так сервер загружает это. Но тут проблема, а что если данного логина нет? Тогда $result=false, и надо выполнять проверку перед mysql_fetch_array(), да?



0



romchiksoad

1957 / 796 / 89

Регистрация: 03.11.2009

Сообщений: 3,066

Записей в блоге: 2

09.09.2010, 19:29

12

Hagrael, если такой записи в таблице нет, то mysql_query вернет ноль строк. FALSE вернется при ошибке в запросе. Таким образом, можно ограничиться такой проверкой:

PHP
1
2
3
4
5
6
if ( mysql_num_rows ( $query ) == 1 ) {
//Продолжаем работу
}
else {
//Пользователь не найден
}



1



БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 20:03

 [ТС]

13

Ясно. А что собственно с setcookie() ?



0



LORDofLINEAGE

39 / 39 / 17

Регистрация: 19.01.2013

Сообщений: 190

10.07.2015, 16:54

14

PHP
1
setcookie("log","AAA",time()+10, '/');

нужно указать путь, где должна «работать» кука



0



pav1uxa

10.07.2015, 20:26

Не по теме:

LORDofLINEAGE, Вы что, серьезно? Теме 5 лет.



0



22 / 20 / 5

Регистрация: 29.02.2016

Сообщений: 590

20.07.2016, 09:21

16

нашёл 50% ответа!!! команда создания кук работает только вверху страницы! или в странице пустой.



0



Kerry_Jr

20.07.2016, 09:37

Не по теме:

D7ILeucoH, еще один умник :wall:. На дату крайнего перед вашим сообщения смотреть нужно.



0



D7ILeucoH

22 / 20 / 5

Регистрация: 29.02.2016

Сообщений: 590

20.07.2016, 12:09

18

и что? теме 6 лет и ни одного дельного ответа! а я нашёл! надо вот так делать, правда симбиоз с JS:

PHP
1
2
3
4
echo('<script language="JavaScript">
var dated = new Date(new Date().getTime() + 60*1000*60*24*365); //кука на год
document.cookie = "'.$name.'='.$value.'; path=/; expires=" + dated.toUTCString();
</script>');



0



Эксперт PHP

4845 / 3857 / 1599

Регистрация: 24.04.2014

Сообщений: 11,317

20.07.2016, 12:23

19

Цитата
Сообщение от D7ILeucoH
Посмотреть сообщение

и что? теме 6 лет и ни одного дельного ответа!

А твой ответ разве дельный?



0



Эксперт PHP

5750 / 4131 / 1506

Регистрация: 06.01.2011

Сообщений: 11,279

20.07.2016, 12:50

20

Не по теме:

Цитата
Сообщение от D7ILeucoH
Посмотреть сообщение

команда создания кук работает только вверху страницы! или в странице пустой.

Надо срочно разработчикам всяких симфоней и ларавелей сообщить. А-то они зачем-то весь проект по разным файлам разбрасывают.
А нужно же в одном! Причём cookie посылать первой строкой и устанавливать с помощью JS.
Чел

код Библии

Web взломал!

Если без шуток — D7ILeucoH, прочтите хотя бы документацию на http://php.net.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

20.07.2016, 12:50

20

Looks like it should be working:

if ($_POST['stayloggedin'] == 'stayloggedin') {

    setcookie("user", $_POST['mail'], time()+7*24*60*60, '/', 'subdomain.example.com', false, true);
    setcookie("hash", md5(sha1(md5($_POST['pw']))), time()+7*24*60*60, '/', 'subdomain.example.com', false, true);

}

header("Location: /"); 
exit();

I have put ob_start() on top of the code, so that shouldn’t be the point.

asked Feb 26, 2011 at 11:20

icant's user avatar

10

make sure your php.ini file allows cookies.. Also, you should NEVER store sensitive data in a cookie or a session variable.

Suggestion:
store a unique id instead, then query the database for details like usernames and passwords. You are just asking to get hacked doing it the way you are doing it.

Not to be negative, just a helpful preventative tip.

answered Jul 6, 2011 at 1:53

Kevin Florida's user avatar

Kevin FloridaKevin Florida

6,6413 gold badges23 silver badges20 bronze badges

1

Make sure that you aren’t sending any output to the browser before the setcookie() function is called. ob_start() should stop the «output before setcookie()» error, but it might not be implemented correctly.

answered Dec 20, 2011 at 0:25

Zak Henry's user avatar

Zak HenryZak Henry

2,0652 gold badges25 silver badges36 bronze badges

1

mike is right. You are both leaving the page and killing the PHP execution before you even ouput anything. ob_start() is in fact the problem: it opens the output buffer (instead of actually sending the data). If you want something to be sent, you have either to flush the buffer (with ob_end_flush()) or to wait for the normal end of the PHP script. So in your case, the cookies are not sent at all.

answered Oct 5, 2012 at 9:05

barakadam's user avatar

barakadambarakadam

2,1591 gold badge16 silver badges15 bronze badges

Looking at that code snippet I’d say the problem is that the cookie is never sent to the user’s browser. Cookies are stored clientside, not serverside; you’re creating two new ones but then immediately calling exit() which kills the PHP script before any response is dispatched from the server to the user.

answered Aug 29, 2012 at 15:17

Mike's user avatar

MikeMike

61810 silver badges22 bronze badges

Try this

setcookie("user", $_POST['mail'], time()+7*24*60*60, '/', '.example.com');
setcookie("hash", md5(sha1(md5($_POST['pw']))), time()+7*24*60*60, '/', '.example.com');

answered Feb 26, 2011 at 13:12

azat's user avatar

azatazat

3,5451 gold badge28 silver badges30 bronze badges

The PHP setcookie() function is used to create cookie data in your web applications.

Any cookie value you set can then be accessed using the $_COOKIE global variable.

This tutorial provides solutions to try when the setcookie() function is not working:

Make sure you refresh the page after setcookie() call

The PHP superglobal variable $_COOKIE is populated when PHP runs the code.

This means that when you call the setcookie() function in a PHP script, the $_COOKIE variable is already assigned.

To access the cookie data, you need to make PHP runs another script by refreshing the page or executing another script.

To test your cookie data, run the script below:

<?php
// 👇 cookie name and value
$name = "username";
$value = "Nathan";

// 👇 set cookie for 1 day (86400 seconds)
setcookie($name, $value, time() + 86400, "/");
?>
<html>
  <body>
    <?php // 👇 check if cookie exists and print the value
    if (!isset($_COOKIE[$name])) {
        print "Cookie called '" . $name . "' is not set";
    } else {
        print "Cookie '" . $name . "' has been set<br>";
        print "Value: " . $_COOKIE[$name];
    } ?>
  </body>
</html>

The first time you load the page above, PHP should respond with “Cookie called ‘username’ is not set”.

Refresh the page, and you will see the following response:

Cookie 'username' has been set
Value: Nathan

This is because PHP populates the $_COOKIE variable before running the script.

If you need the cookie data to be accessible immediately, you can manually assign the cookie values to the $_COOKIE variable:

// 👇 cookie name and value
$name = "username";
$value = "Nathan";

// 👇 set cookie for 1 day (86400 seconds)
setcookie($name, $value, time() + 86400, "/");

// 👇 manually set the cookie
$_COOKIE[$name] = $value;

Now you can access the cookie data immediately without sending another request to the server.

Make sure setcookie() is called before any output

The setcookie() function modifies the HTTP headers to include that cookie in your request.

This means that the function must be called before you produce any output in your script.

An output can be raw HTML or the echo / print construct in your PHP file.

Suppose you have a PHP script as shown below:

<?php
echo "Hello";
setcookie("username", "Nathan", time() + 3600, "/");
?>

Then PHP will produce a warning in the output as follows:

Warning: Cannot modify header information - headers already sent by ...

The same warning appears when you have raw HTML output before calling setcookie():

<html>
  <body>
  <h1>Hello World!</h1>
  <body>
<html>
setcookie("username", "Nathan", time() + 3600, "/");

To solve this warning, you need to call the setcookie() function before any output:

<?php
setcookie("username", "Nathan", time() + 3600, "/");
echo "Hello";
?>

This way, the HTTP headers will have the cookie data set using setcookie().

You still need to send another request to access the cookie with $_COOKIE though.

Output buffering to set the cookie after output

If you really need to set the cookie after some output code, then you can use the output buffering function.

The output buffering function command PHP to store any output in the buffer until you manually release it.

The function to start output buffering is ob_start() and the function to release the buffer is ob_end_flush().

Here’s how you buffer output in PHP:

<?php
// 👇 buffer the output
ob_start();

echo "Hello World!";

// 👇 set the cookie
setcookie("username", "Nathan", time() + 3600, "/");

// 👇 release the buffer
ob_end_flush();

This solution works because PHP won’t send the HTTP headers until you release the buffer (PHP sends HTTP headers along with the output)

And now you’ve learned what to do when the setcookie() function is not working.

I hope this tutorial has been helpful to you. 👍

  • Почему samsung account выдает ошибку
  • Почему rockstar games launcher выдает ошибку
  • Почему recaptcha на сайте выдает ошибку
  • Почему play market пишет ошибка подключения
  • Почему play market не скачивает приложения а пишет произошла ошибка