Why is this HTTP request continually looping? - php

I'm probably overlooking something really obvious here.
Comments are in to help explain any library specific code.
public function areCookiesEnabled() {
$random = 'cx67ds';
// set cookie
cookie::set('test_cookie', $random);
// try and get cookie, if not set to false
$testCookie = cookie::get('test_cookie', false);
$cookiesAppend = '?cookies=false';
// were we able to get the cookie equal ?
$cookiesEnabled = ($testCookie === $random);
// if $_GET['cookies'] === false , etc try and remove $_GET portion
if ($this->input->get('cookies', false) === 'false' AND $cookiesEnabled) {
url::redirect(str_replace($cookiesAppend, '', url::current())); // redirect
return false;
}
// all else fails, add a $_GET[]
if ( ! $cookiesEnabled) {
url::redirect(url::current().$cookiesAppend);
}
return $cookiesEnabled;
}
Firstly, I wanted an easy way to check if cookies were enabled. I achieved this, but in the event of no cookies, there was an ugly ?cookies=false in the URL.
That was OK, but then if you reloaded the page and did have cookies enabled again, I wanted to redirect the user so it stripped off ?cookies=false in the URL (allowing the method to recheck and learn that cookies now are enabled.).

After $cookiesEnabled = ($testCookie === $random);, there are 4 cases:
$cookiesEnabled is true and $_GET['cookies'] === 'false' is true
$cookiesEnabled is true and $_GET['cookies'] === 'false' is false
$cookiesEnabled is false and $_GET['cookies'] === 'false' is true
$cookiesEnabled is false and $_GET['cookies'] === 'false' is false
Case 1 is handled by the first if block. The return statement is intended to handle cases 2 and 3; the second if block is intended to handle only case 4, but it catches both case 3 and 4. In case 3, the URL already has ?cookies=false, but since $cookiesEnabled is false, we redirect to add ?cookies=false, and cycle back into case 3.

You must be leaving something out since there is no loop in that code. If you meant that the browser is looping (e.g. getting continuous redirects), then I recommend installing the Live HTTP Headers extension to Firefox and watch what the browser and server are actually saying to each other. Putting in some logging code in the snippet above might also be instructive.
Update for comment:
Then I really recommend putting in print statements inside the ifs so you can see which ones you're going through and what the various values are. Clearly something is not getting set the way you thought it would be, so now you need to find out what it actually is.
One thing I have encountered several times is that the code itself is OK, but there is a .htaccess file that is working against you, so go double check any .htaccess files in any of the directories, starting from DOCUMENT_ROOT.

Related

How to share variable in PHP from webpage script to script running permanently from the command line

I have a script running permanently from command line on a web server.
There is a loop checking new stuff in DB.
To save some load I need to add a condition not to check the DB if there is no reason.
When the change occurs I need immediate reaction, however it might happen that there is no change for a few hours.
And yes, it is not possible to do it in the webpage_script.php :)
The idea is to use some kind or a SUPERGLOBAL variable and in webpage_script.php save TRUE to that variable and then check it in that condition in permanently_running_script_on_the_same_server.php.
However I didn't find any variable that can be used for that reason... when I try to use session_id('whateverisinhereblahblab') - to share the session, the webpage_script.php will not get loaded as the session is probably continually occupied...
webpage_script.php
$the_shared_variable['whatever'] === FALSE;
if ($something_happens){
$the_shared_variable['whatever'] === TRUE;
}
permanently_running_script_on_the_same_server.php
while (true) {
if($the_shared_variable['whatever'] === TRUE){
}
}

How to toggle this option PHP

I want to toggle this option. When the option is true, I want to update it to false.
update_option('maintenance', true);
I've tried the following:
if(get_option('maintenance') == true) {
update_option('maintenance', false);
}
if(get_option('maintenance') == false) {
update_option('maintenance', true);
}
But for some reason this does not work, and is overcomplicated. I'm sure there's a better way to do this.
Does anyone got suggestions?
You are toggling it twice each time. If it was true, you are updating it to false, then reading it again, finding it to be false, then setting it to true.
Just do it once in a one liner as such (replace all your code):
update_option('maintenance', !get_option('maintenance'));
This says: Update it to the inverse of what it is right now.
What #zed writes is exactly what I'd propose too. But you can use a variable, or even 'normal' ifs, if you think it's a bit too complex to do it in one line.
With a variable inbetween. This allows you to more easily inspect the variable (for debugging), or to combine multiple values if you would need to.
$newvalue = !get_option('maintenance');
update_option('maintenance', $newvalue);
Or, if you want to have an if, use `else to prevent the second piece to be executed right away:
if(get_option('maintenance') == true) {
update_option('maintenance', false);
} else {
update_option('maintenance', true);
}
Needless to say that in this particular and simple case, zed's suggestion is the most straightforward.

Constant, isset and empty evaluation

Does anyone know how isset and empty is interpreted by the translator, or how the translator treats undefined variables?
To expand on my question, I have the below code in my include file:
define('USER_AUTH', !empty($_SESSION['username']) && !empty($_SESSION['status'])); //user is verified
define('ACC_IS_PENDING', $_SESSION['status'] == '0');//checks to see if user status is pending which has a status of 0
USER_AUTH is used as a quick hand to check if user is authenticated. ACC_IS_PENDING is used as a quick hand for when the account status is pending. However, PHP gives me a notice to advise me that $_SESSION['status'] in my second line of code is undefined. I know that it is undefined, but I haven't used it yet! How dare you tell me what I already know. LoL
However, when I trick the code with the below:
define('USER_AUTH', !isempty($_SESSION['username']) && !isempty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Where isempty() is a custom made function that will always return FALSE. Then no notice!
Alternatively, if I use the below code:
define('USER_AUTH', notempty($_SESSION['username']) && notempty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Where notempty() always return TRUE, then again no notice.
Am I right in saying that the translator checks that the variable has been tested once, and that if the test resulted in true, then the translator sees this as the variable has been defined?
If this was the case, then what about isset and empty? They both seem to give me notices no matter if the evaluation is true or false.
define('USER_AUTH', isset($_SESSION['username']) && isset($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
and
define('USER_AUTH', empty($_SESSION['username']) && empty($_SESSION['status']));
define('ACC_IS_PENDING', $_SESSION['status'] == '0');
Apologies for the long winded question. This seems trivial, but it would be nice to have a quick defined constant without having to get notices! Any help in explanation or a better solution for such trivial task would be appreciated, thanks!
PHP complains because the index 'status' is not defined in the array. You would need to write
!isset($_SESSION['status']) || empty($_SESSION['status']
When you "trick" the code as described, PHP will never try to access the non-existing array index, which is why you don't get any notice.
In the fourth code example (with isset), you are still accessing the non-existing array index in the second line of code, so I suspect that's why there's still a notice.
a) If you wants to use $_SESSION['status'], you have to check first that the variable is not empty ( see http://www.php.net/manual/fr/function.isset.php for more details) :
if (isset($_SESSION['status'])) {
// here the value exists and can be used
Do something...
} else {
// here the value does not exist and cannot be used
}
b) I believe that
empty($_SESSION['username']) && !empty($_SESSION['status'])
is not constant : it varies from one run to the other. You may want to use
$user_is_logged = empty($_SESSION['username']) && !empty($_SESSION['status']);
and use the variable $user_is_logged instead of a constant. See this section http://www.php.net/manual/fr/language.constants.php for a speek about constants.

Is `if($_POST)` a reliable means of checking if a script has been posted?

As per the title: is if($_POST) reliable?
Is it reliably true even if no data was posted but the HTTP POST method was used?
Is if('post' === strtolower($_SERVER['REQUEST_METHOD'])) a more reliable method, or is it overkill?
No.. because:
array() == false
So if no data is posted, the condition will turn out false. So check against the REQUEST_METHOD. Note that it would have taken you less time to test this, than for me to type this out.

How to check if a webpage exists. jQuery and/or PHP

I want to be able to validate a form to check if a website/webpage exists. If it returns a 404 error then that definitely shouldn't validate. If there is a redirect...I'm open to suggestions, sometimes redirects go to an error page or homepage, sometimes they go to the page you were looking for, so I don't know. Perhaps for a redirect there could be a special notice that suggests the destination address to the user.
The best thing I found so far was like this:
$.ajax({url: webpage ,type:'HEAD',error:function(){
alert('No go.');
}});
That has no problem with 404's and 200's but if you do something like 'http://xyz' for the url it just hangs. Also 302 and the like trigger the error handler too.
This is a generic enough question I would like a complete working code example if somebody can make one. This could be handy for lots of people to use.
It sounds like you don't care about the web page's contents, you just want to see if it exists. Here's how I'd do it in PHP - I can stop PHP from taking up memory with the page's contents.
/*
* Returns false if the page could not be retrieved (ie., no 2xx or 3xx HTTP
* status code). On success, if $includeContents = false (default), then we
* return true - if it's true, then we return file_get_contents()'s result (a
* string of page content).
*/
function getURL($url, $includeContents = false)
{
if($includeContents)
return #file_get_contents($url);
return (#file_get_contents($url, null, null, 0, 0) !== false);
}
For less verbosity, replace the above function's contents with this.
return ($includeContents) ?
#file_get_contents($url) :
(#file_get_contents($url, null, null, 0, 0) !== false)
;
See http://www.php.net/file_get_contents for details on how to specify HTTP headers using a stream context.
Cheers.
First you need to check that the page exists via DNS. That's why you say it "just hangs" - it's waiting for the DNS query to time out. It's not actually hung.
After checking DNS, check that you can connect to the server. This is another long timeout if you're not careful.
Finally, perform the HTTP HEAD and check the status code. There are many, many, many special cases you have to consider here: what does a "temporary internal server error" mean for the page existing? What about "permanently moved"? Look into HTTP status codes.
I've just written a simpler version using PHP:
function url_check($url) {
$x = #fopen($url,"r");
if ($x) {
$reply = 1;
fclose($x);
} else {
$reply = 0;
}
return $reply;
}
Obviously $url is the test URL, returns true (1) or false (0) depending on URL existence.
Maybe you could combine domain checker, and jQuery, domain checker (PHP) can respond 1 or 0 for non-existent domains.
eg. http://webarto.com/snajper.php?domena=stackoverflow.com , will return 1, you can use input blur function to check for it instantly.

Categories