Jump to content

SaranacLake

Members
  • Posts

    648
  • Joined

  • Last visited

Posts posted by SaranacLake

  1. 3 minutes ago, requinix said:

    How about this:

    Tell me in English what you want the rewriting to do. Make it sound like the way I described your two examples above.

    Well, I did above, but here goes again...

    IF a user requests my website (i.e. domain name)

    starting with either a "www." OR with no "www."

    AND the request lacks an "https://"

    THEN ultimately I want the url to read "https://www.mydomain.com"

    SO THAT

    it uses my server's SSL certificate

    AND is properly formatted like a url should be.

     

    The last two code samples I gave should do that, PLUS they do it with one condition like you said I should do.

    So did I not apply your advice properly to get what I wanted?

     

     

    3 minutes ago, requinix said:

    See this page.

    I will have to ask my webhost how to determine the SERVER_NAME variable and how to set it to - in my case - www.mysite.com 

    That is the proper format of the SERVER_NAME constant, right?

     

    Is there any issue hard-coding my domain as www.mysite.com ??

     

  2.  

     @requinix,

    Is this what you wanted me to do...

    RewriteCond %{HTTP_HOST} !^www\. [OR]
    RewriteCond %{HTTP_HOST} ^www\. 
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://www.mysite.com/$1[L,R=301]
    

     

    Or maybe also this...

    	RewriteCond %{HTTP_HOST} ^(www\.)?
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://www.mysite.com/$1 [L,R=301]
    	

     

     

    Also, you said...

    5 hours ago, requinix said:

    All you need is one rule that checks if either it's HTTP or it's non-WWW. Then you redirect to the right domain, which you specify with the SERVER_NAME or by hardcoding it - not using HTTP_HOST.

     

    Is SERVER_NAME an Apache constant?

    Or is it a PHP constant?

    If the former, then how do I find it on my VPS which runs cPanel?

     

     

     

  3. 15 minutes ago, requinix said:

    Describe to me precisely what Apache and mod_rewrite would do if the request was for https://mysite.com. Not what it should do but what it will do.

    Well, based on the code I posted above, I guess my code doesn't handle that scenario.

    When I was testing the above rewrites, I typed mysite.com into the address bar, let my website load, and then I added/deleted variants listed above to see if things worked - especially since I was complaining earlier that my SESSIONS were getting broken earlier.

    My SESSIONS now work, and nothing breaks when I try the variants above, but I'm just being picky and do not want things to go from mysite.com to https://mysite.com

     

    15 minutes ago, requinix said:

    Once you fix that, you'll be potentially issuing multiple redirects. That's not good. It needs to be just one redirect to solve all the problems, not one redirect at a time fixing one problem at a time.

    Is it correct that when you have multiple mod_rewrite rules, one per line, that each new line adds an AND condition?

    Is doing an OR condition as simple as adding the word "OR" on the same line?

     

  4. 4 minutes ago, requinix said:

    You can do it with the magic of the word "or". As in "if they try to go to http://something or they try to go to something://mysite.com then redirect them to https://www.mysite.com".

    It sounds like you are proposing a way to make my mod_rewrite more "efficient", but why would this code not work as-is?

    # NON-WWW to HTTPS://WWW
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [L,R=301]
    
    # WWW to HTTPS://WWW
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]
    	

     

  5. 4 minutes ago, requinix said:

    All you need is one rule that checks if either it's HTTP or it's non-WWW. Then you redirect to the right domain, which you specify with the SERVER_NAME or by hardcoding it - not using HTTP_HOST.

    I don't follow your response....

    A user could type in any of these combinations...

    mysite.com
    www.mysite.com
    ----
    http://mysite.com
    http://www.mysite.com
    ----
    https://mysite.com
    https://www.mysite.com
        

     

    Where I always want them to end up is...

    https://www.mysite.com
    	

     

    That being said, how can you accomplish all of that in ONE rule or ONE rewrite?

    I would say that you cannot...

     

  6. Correction:

    The above code does NOT break my SESSION, however it doesn't work completely as expected.

     

    If you go to www.mysite.com then things redirect to https://www.mysite.com

    This is correct.

    However, if you go to mysite.com then things redirect to https://mysite.com

    While this is secure, it isn't what I want.  I want to always end up with: https://www.mysite.com

    Thanks.

     

     

     

     

     

  7. I want a mod_rewrite that will take either a non-WWW or a WWW request and change it to an HTTPS://WWW

    I thought the below code would accomplish that, but it seems to be breaking my SESSION sometimes when I try editing the URL...

    	## NON-WWW to HTTPS://WWW
    ##RewriteCond %{HTTP_HOST} !^www\. [NC]
    ##RewriteCond %{HTTPS} off
    ##RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [L,R=301]
    ##
    ## WWW to HTTPS://WWW
    ##RewriteCond %{HTTP_HOST} ^www\. [NC]
    ##RewriteCond %{HTTPS} off
    ##RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]
    	

    What am I doing wrong?

  8. 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??

     

     

  9. 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!!!

     

  10. 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?

  11. 4 hours ago, Barand said:

    So you're getting the file names, getting the creation dates for those files, storing in an array then sorting the array by date - yes?

    I call a function (below) that reads the files in the photo directory and puts them into an array...

    	function getPhotoFilesArray($photoPath){
    	    $photoFiles = array();
    	    // Check for Photo Directory.
        if (is_dir($photoPath)){
          // Photo-Directory Found.
          // Open Directory-Handle.
          $handle = opendir($photoPath);
    	      if($handle){
            // Initialize Key.
            $i = 1001;
            
            // Iterate through Photo-Directory items.
            // Return next Filename in Directory.
            while(($file = readdir($handle)) !== FALSE){
              // File or Directory exists.
              if($file != '.' 
                  && $file != '..' 
                  && $file != '_thumbnails'
                  && $file != '_photos'
                  && preg_match("#^[^\.].*$#", $file)){
                // Not Directory.
                // Not Hidden File.
                // Add to array.
                $photoFiles[$i] = $file;                     // Simple array.
    	            // Increment Key.
                $i++;
              }
            }
            closedir($handle);
          }
    	    }else{
          // Photo-Directory Not Found.
          // Redirect to Page-Not-Found.
          header("Location: " . BASE_URL . "/utilities/page-not-found");
    	      // End script.
          exit();
    	    }//End of RETRIEVE GALLERY-IMAGES
    	        return $photoFiles;
    	    }//End of getPhotoFilesArray
    	

     

    Then in the HTML section, I iterate through the array using a FOR-EACH loop.

    Locally in my DEV environment this works fine, but on the web server something is getting messed up.

     

  12. I have a php page that creates a photo gallery with thumbnails.  It is populated by code that reads all photo files from a specified photo directory.

    This was working fine in DEV, but now that I have uploaded to my test web server, the pictures are in reverse order.

    Not the end of the world, yet annoying, because they should be in chronological order.

    Files names are straight off my iPhone (e.g. IMG_2203.jpg, IMG_2204.jpg, IMG_2207.jpg)

    What is happening, and how can I fix this?

    Thanks!

  13. 22 hours ago, Psycho said:

    What he said. There is no way to positively determine if an element is a folder or file by the name. A files doesn't have to have an extension. It's kind of difficult to create a file w/o an extentiosn, but not impossible. But, the function is_dir() [or the converse is_file()] will positively make that distinction.

    Working on fixing some other issues but will circle back to this...

  14. Hello.  I have code that goes into a directory and reads all filenames.

    I could use some help tweaking my code - using a regex - to prevent including any folders.

    Here is what I have so far...

    	while(($file = readdir($handle)) != FALSE){
    	  if($file != '.'
    	          && $file != '.'
    	          && $file != '..'
    	          && $file != '_small'
    	          && $file != '_med'
    	          && $file != preg_match("#^[^\.].*$#, $file)){
    	      $photoFiles[] = $file;
    	   }
    	

     

    I couldn't figure out a working regex to prevent folders/subfolders so I had to hard-code the above folders which is of course limiting!

    Thanks.

     

  15. I hate array...   😞

    So I had a block of code inside my photo-gallery.php script that took the path to my photos directory, and went to that directory, and then read all of the photo filenames into an array.  Then in my HTML, I iterate through this array to display all of the photos for my gallery.

    Now I would like to move that code to an included file so multiple scripts can access it and always be working with the same array.

    It seems to me that I need to encapsulate my code inside a function?

    Then I could call my getPhotoFilesArray back to my callings cript, and use that array for whatever.

    I haven't coded PHP in like 4 years and I am struggling to return the entire array back to my caling script.

    This is what I have so far...

    	function getPhotoFilesArray($photoPath){
    	     $photoFiles = array();
    	     <code to find corresponding files>
    	     $photoFiles gets populated in a loop
    	     return $photoFiles;
    	}
    	

     

    Then in my calling script, I have...

    	<?php
    	     require_once('../../../secure_outside_webroot/config.php');
    	     require_once(WEB_ROOT . 'utilities/functions.php');
    	     getPhotoFilesArray($photoPath);
    	     var_dump($photoFiles);
    	

     

    I get some error...

    	Notice: Undefined variable: phtoFiles in photo-gallery.php line 133 (which is my var_dump).
    	

     

    <br>

    Would appreciate help getting this to work!

     

     

  16. 8 minutes ago, requinix said:

     

    Yes: by creating an array where you define the first entry.

    But I'm not sure of how to do that,

    I create my array in a llop...

    	while(($file = readdir($handle)) != FALSE){
    	     $photoFiles[] = $file;
    	}
    	

     

    If I was doing this out of a loop I guess my first entry could be...

    $photoFiles[1001] = something;

     

    But how do I do that in the loop and not have everything be $photoFiles[1001] ?

     

  17. @requinix,

    In an earlier thread of mine this week, I think you - or maybe it was @Psycho - suggested putting my code which create an array of my photo files into an include file.

    I think the logic was that then when either my "photo-gallery.php" OR "photo-detils.php" scripts call that code, that the array will always synched because it is the same array.

    Ring a bell?

    So super newbie question, but I am rusty on includes...  How does this sound...

     

    1.) Create an "/includes/retrieve-photos.php" script?

     

    2.) Reference that in each script, I would do this...

    	require_once('../../includes/retrieve-photos.php
    	

    right?

     

    3.) To use that code, I would then just reference the populated array...

    	foreach($photoFiles as $photoKey => $photoValue){
    	 
    	}
    	

    Right?

     

  18. First off, what are the names for the types of arrays?

    What do you call an array that uses integers for the key?

    I think when the key is text it is called an associative array?

    Anyways...

     

    Is there a way to create an array where they keys are integers, but you are defining the first entry?

    I would like my array to either start with a "1" or maybe "1001".

    How do I do that?

     

  19. 13 minutes ago, requinix said:

    Still the same thing.

     

    23 minutes ago, SaranacLake said:

    How about this...

     

    
    foreach($photoFiles as $photoKey => $photoValue){
           $fileNameArray = pathinfo($photoValue);
           $photoName = $fileNameArray['filename'];
           $photoExt = $fileNameArray['extension'];
           $newname = $photoName . "_med." . $photoExt;
    }
    	

     

     

  20. 1 minute ago, requinix said:

    As long as your files only ever have the one period in their names, I guess.

    Otherwise I would tell you to get the name without the extension, add your suffix, and then add the extension. pathinfo() would help with that.

    Can I use pathinfo() just on a filename and not a path?

     

  21. Hello.  I have a simple array with a key/value pair like this...

    	foreach($photoFiles as $photoKey => $photoValue){
    	 
    	}
    	

     

    The $photoValue would be the file-name (e.g. "IMG_2340.JPG") and is used in my photo-gallery.

    Now I am building a photo-details page and what I would like to do is have that larger image be "IMG_2340_large.JPG"

    Is it possible to split up the array value, insert "_large" and then re-assemble the $photoValue so I can use it here...

    	   <a href='client1/galleries/$galleryID/{$photoValue}'><image here</a>
    	

     

     

    Thanks.

     

     

  22. 13 minutes ago, kicken said:

    Personally, I'd go with the DirectoryIndex solution I mentioned above, I think it's the best overall solution if you want to keep your current folder structure. It means your URL will end with a /, but that fine IMO.  Just isolate the configuration to your gallery directory by putting it in it's own .htaccess file or in a <Directory> block in your VirtualHost configuration. 

    I trust that it works, it just looked Greek to me and since this is a favor website for my co-workers, I'm trying to not spend forever on it.

     

    13 minutes ago, kicken said:

    If that trailing / is really a problem for you, then my second choice solution would be to just move your gallery directories into a sub-folder or something so they don't match your pretty URLs.

    Or prepend it with X_ which works...

     

    13 minutes ago, kicken said:

    Rewriting is common, but usually a person's pretty-url's don't match actual filesystem paths.  Either the content is in a database and not in a filesystem at all, or it's stored differently in the filesystem (such as with an extension that is added by the rewrite).  Usually if a url maps to a valid file/directory people want that file/directory to be served which is why you see a lot of RewriteCond's checking for !-d and !-f.

    True

     

    13 minutes ago, kicken said:

    Your problem is due to the specific condition of having your desired pretty URL's match your filesystem which is causing a conflict between what mod_dir wants to do and what mod_rewrite wants to do.  There's a handful of cases of this issue I saw searching google, but not very many.  Maybe there's a solution that will resolve the conflict while keeping your structure, but I couldn't find it and don't feel much like continuing the search when there are simple alternatives.

     

    What I thought was maybe I could tell Apache, "If you come across "client1/gallery/(.*)"  (e.g. "/client1/gallery/2019-holiday-party") then do NOT treat it the normal way like a directory, but instead make an exception and treat (.*) like is a file.

    That seems doable, although I'm not experienced enough with mod_rewrites to do that for fear of blowing things up.

    Thoughts?

     

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