Jump to content

Problems logging in...


SaranacLake

Recommended Posts

I have built a simple website to share photos with people at work.  And it is based on code - known to work - from a larger website that I built a few years ago.

When you land on the site, you have a login screen, and if the username/password match what is hardcoded, then I set $_SESSION['loggedIn'] = TRUE; and I redirect to the menu.php page.

If your credentials do not match, then I redirect the user to an access-denied.php (403) page.

Here is the problem...

Occasionally, when you try to log in you will get routed to the access-denied page.  But then if you try a second time you end on on the menu page.

I uploaded my otherwise working code to my hosted webserver, and now I can never seem to log in.

It seems to me that something is getting screwed up with the session variable?

Any ideas what could be causing this strange behavior?

Link to comment
Share on other sites

10 hours ago, ginerjm said:

Have you tried adding some debugging statements (echo?) to your login process to see how things are being handled and set?  That would be a good place to start.  That and perhaps giving us something to look at.

I don't know where to begin...  😞

My code seems to work 95% of the time locally, but there is a problem when it is on my webserver.

I found some links late last night where other people are having similar issues and the theme seems to be with the way you handle sessions in PHP, but I am trying to sort out what they say.

Here is what is happening...

I go to mydomain.com and the index.php page loads which is basically a login form.  I log in using the hard-coded credentials, and I set the SESSION['loggedIn'] = TRUE and I redirect as seen below...

 

index.php

	<?php
    // Initialize Session.
    session_start();
	    // Access Constants.
    require_once('../secure_outside_webroot/config.php');
	
    // Handle Form.
    if ($_SERVER['REQUEST_METHOD']=='POST'){
        // Form was Submitted (Post).
	        // Initialize Errors Array.
        $errors = array();
	        // Trim all form data.
        $trimmed = array_map('trim', $_POST);
	
        // Validate Form Data.
        // Check Username.
        if (empty($trimmed['username'])){
            // No Username.
            $errors['username'] = 'Enter your Username.';
	        }else{
            // Username Exists.
            $username = $trimmed['username'];
        }
	        // Check Password.
        if (empty($_POST['pass'])){        // <<===== Use untrimmed $_POST
            // No Password.
            $errors['pass'] = 'Enter your Password.';
	        }else{
            // Password Exists.
            $pass = $_POST['pass'];     // Do NOT trim password!!
	        }//End of VALIDATE FORM DATA
	
        // Attempt to Log-In Member.
        if (empty($errors)){
            // Valid Form Data.
	            // Compare Passwords.
            if (($username == USERNAME) && ($pass == PASSWORD)){
                // Passwords Match.
	                // Log In Member.
                // Set Session variables.
                $_SESSION['loggedIn'] = TRUE;
	
                // Determine Redirect.
                header("Location: " . BASE_URL . "/client1/menu");
	        // End script.
                exit();
	            }else{
                // Invalid Login.
                $errors['pass'] = 'Username and Password do not match those on file.';
	            }//End of COMPARE PASSWORDS
	        }else{
            // Drop through to display Errors.
	        }//End of ATTEMPT TO LOG-IN MEMBER
	    }else{
        // Form was not Submitted (Get).
        // Drop through to display Form.
	    }//End of HANDLE FORM
?>
	<!DOCTYPE HTML>
<html lang="en">
	</html>
	

 

Here is a snippet of the relevant code in my .htaccess file...

 

htaccess

	#Prevent Directory Listings.
Options -Indexes
 
	#Handle Access-Denied.
ErrorDocument 403 "/utilities/access-denied.php"
	#Handle Page-Not-Found.
ErrorDocument 404 "/utilities/page-not-found.php"
 
	#Turn on mod_rewrite
RewriteEngine on
	
# Addresses issues with how Apache handles mod_rewrites!!
RewriteBase /
 
	# REMOVE INDEX.PHP
RewriteCond %{REQUEST_URI} ^.*/index\.php 
RewriteRule ^(.*)index.php$ $1 [L,R=301]
 
	# REWRITE WITH .PHP EXTENSION
	RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .* $0.php [L]
 
	# REWRITE PHOTO-DETAILS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule client1/gallery/(.+)/(.+)$ client1/galleries/photo-details.php?gallery-id=$1&photo-id=$2 [L]
 
# REWRITE PHOTO-GALLERY
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule client1/gallery/(.+)$ client1/galleries/photo-gallery.php?gallery-id=$1 [L]

 

After logging in (successfully), I should be redirected to menu.php and a menu of available galleries should be displayed...

 

menu.php

	<?php
    // Initialize Session.
    session_start();
	    // Access Constants.
    require_once('../../secure_outside_webroot/config.php');
	    // Initialize Variables.
//unset($_SESSION['loggedIn']);
	
    // Check if Logged-In.
    if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == TRUE){
        // Member Logged In.
        // Continue processing...
	    }else{
        // Not Logged In.
        // Redirect to Access-Denied.
        header("Location: " . BASE_URL . "/utilities/access-denied");
	        // End script.
        exit();
	    }//End of CHECK IF LOGGED-IN
?>
	<!DOCTYPE HTML>
<html lang="en">
 
	</html>
	

 

Unfortunately when I am on my webserver, it seems like 95% of the time I end up on my Access Denied (403) page...

	        header("Location: " . BASE_URL . "/utilities/access-denied");
	

 

In DEV I am running the latest version of MAMP which has Apache 2.2 but on my webserver it runs Apache 2.4

 

Either cPanel or Apache or my php.ini or .htaccess file is breaking my PHP session, but I'm not sure why, because this code has been working fine locally on my laptop?

 

Please help!!!

 

Link to comment
Share on other sites

22 hours ago, SaranacLake said:

Occasionally, when you try to log in you will get routed to the access-denied page.  But then if you try a second time you end on on the menu page

this symptom is typical of a changing host-name/sub-domain in the URL (a www. vs no www) and the result of being "redirect happy" and redirecting all over a site. if you initially visit a site with a url that does/doesn't have a www, then perform a redirect that uses a different host-name/sub-domain than the initial url used to reach the site, the default session id cookie domain setting will cause the session id cookie to no-longer match, and the initial session id is no longer sent from the browser to the server. after the initial redirect, all the variations of the URL are now the same and the session id cookie works as expected.

so, 1) be consistent in all the URL's that you use in links, form actions, redirects, ... on a site (this alone won't solve the problem since someone can type any variation of a url or have a short-cut/book-mark with any variation), 2) set the session id cookie domain setting to match all variations of your domain, and 3) set up a htaccess redirect to cause all requests to goto the same variation of your domain name.

 

Link to comment
Share on other sites

22 hours ago, mac_gyver said:

this symptom is typical of a changing host-name/sub-domain in the URL (a www. vs no www) and the result of being "redirect happy" and redirecting all over a site. if you initially visit a site with a url that does/doesn't have a www, then perform a redirect that uses a different host-name/sub-domain than the initial url used to reach the site, the default session id cookie domain setting will cause the session id cookie to no-longer match, and the initial session id is no longer sent from the browser to the server. after the initial redirect, all the variations of the URL are now the same and the session id cookie works as expected.

What consitutes "redirect happy"?

 

22 hours ago, mac_gyver said:

so, 1) be consistent in all the URL's that you use in links, form actions, redirects, ... on a site (this alone won't solve the problem since someone can type any variation of a url or have a short-cut/book-mark with any variation),

I have a constant called BASE_URL and I needed to tweak that to match up like you say above.

I also had to tweak my mod_rewrites because they apparently weren't working as expected.

 

22 hours ago, mac_gyver said:

 2) set the session id cookie domain setting to match all variations of your domain,

How do I do that?  Not following you...

 

22 hours ago, mac_gyver said:

and 3) set up a htaccess redirect to cause all requests to goto the same variation of your domain name.

 

Yes, after looking over my code and mod_rewrites, I think I go things fixed.

However, can you or someone comment if I am doing SESSIONS properly in the code above?

I know I found several hits in a Google search about my issue - but didn't have time to read them.  It seems like they were saying you have to do more creating adn using SESSIONS than what I have.

Comments??

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.