开发者

Why isn't this simple PHP Forloop working?

First here's the code:

<?php

$qty = $_GET['qty'];

开发者_如何学运维for($i=0; $i < $qty; $i++)
{
    setcookie('animals', $_COOKIE['animals'].'(lion)', time()+3600);
}

?>

Here's what I'm trying to do:

I want to set the value of the "animals" cookie to "(lion)". The number of instances of "(lion)" that should be in the cookie is determined by the "qty" GET parameter's value. So for example if the pages url is:

http://site.com/script.php?qty=10

then the value of the cookie should be:

(lion)(lion)(lion)(lion)(lion)(lion)(lion)(lion)(lion)(lion)

but now it just sets the value once despite the setcookie function being inside the loop, why isn't it working?


Due to the way that cookies work (the browser needs to send the value back to the server as a part of the page request), you can't read and update the contents of the cookie in a single page load like you're attempting to.

As such, instead of attempting to append values to the variable in the $_COOKIE array, simply use a temporary variable as such:

<?php
    $quantity = intval($_GET['qty']) ? intval($_GET['qty']) : 10;    

    $tempString = '';
    for($loop=0; $loop < $quantity; $loop++) {
        $tempString .= '(lion)';
    }

    setcookie('animals', $tempString, time()+3600);
?>


$_COOKIE only contains the cookies passed to the script:

An associative array of variables passed to the current script via HTTP Cookies.

setcookie only changes the HTTP response headers. See also the documentation:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array.

I.e. it does not modify the $_COOKIE array.

You can do:

$str = '';
for($i=0; $i < $qty; $i++)
{
    $str .= '(lion)';
}
setcookie('animals', $str, time()+3600);


$_COOKIE variables aren't available until the next request. Setting a cookie doesn't set the variable.

From http://php.net/manual/en/function.setcookie.php :

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

(Emphasis mine.)


Why don't you do something like:

<?php

$qty = $_GET['qty'];

$animals = '';

for($i=0; $i < $qty; $i++)
{
    $animals.='(lion)';
}

setcookie('animals', $animals, time()+3600);

?>


You can use the built-in str_repeat() function for this:

$qty = $_GET['qty'];
setcookie('animals', str_repeat("(lion)", $qty), time()+3600);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜