Jump to content

[SOLVED] My loop/function times out the page; cookies


dink87522

Recommended Posts

This code gives the maximum 30 second execution error. I am confused as to why, however one possible solution may be if the cookie does not exist if the user had not visited the site before (however I have the cookie and still get this same error). How do I fix the below code so it works  and how do I check for a cookie on a user's computer (I know how to call a cookie, although how do you check if it does or does not exist? ) .Thanks.

 

<?php
$rnd = rand(1, 203); 
//recentQuestionsPop($rnd); 
$checked = ""; 
$recentlyAnswered = $_COOKIE["Recently_answered"];
$recentQuestions = explode("|", $recentlyAnswered)
while ($checked != "1"){ //
$rnd = rand(1, 203); 
recentQuestionsPop($rnd); 
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function recentQuestionsPop($rnd){
$checked = "1";
switch ($rnd){
case "$recentQuestions[0]"; 
if ($rnd == $recentQuestions[0]){
	$checked = "0";
} 
break;
case "$recentQuestions[1]"; 
if ($rnd == $recentQuestions[1]){
	$checked = "0"; 
} 
break;
case "$recentQuestions[2]"; 
if ($rnd == $recentQuestions[2]){
	$checked = "0"; 
} 
break; 
}
return $checked;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  */ ?>

You are returning the checked variable from the function so you should use it in the global scope.

Your script times out because it is a never ending loop as checked is always empty.

$recentQuestions = explode("|", $_COOKIE["Recently_answered"]);
while(!$checked) {
  $rnd = rand(1, 203); 
  $checked = recentQuestionsPop($rnd); 
}

 

Also, are you sure you want to be treating integers as strings?

// strings
$checked = "0";
$checked = "1";
// integers
$checked = 0;
$checked = 1;

The problem is you have a infinity loop, you need to change this

   $rnd = rand(1, 203); 
   recentQuestionsPop($rnd); 

To

   $rnd = rand(1, 203); 
   $checked = recentQuestionsPop($rnd); 

return does not return the variable you pass it but the value of the variable. You need to capture the returned value when you call the function.

 

and how do I check for a cookie on a user's computer (I know how to call a cookie, although how do you check if it does or does not exist? )

To see if a cookie is set you use

if(isset($_COOKIE['name_here']))
{
    // code for when the cookie is set
}
else
{
    // code for when the cookie is not set
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.