Friendly URLs - rewriting mods and php redirects

So far I have done this:

RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?load=$1 [QSA,L] 

Then on my index page (in the root directory) I use PHP to determine the page to load:

 // Swap to variables $load = $_GET['load']; // Home page if (!$load || $load == "") { include('home.php'); exit(); } // Dashboard if ($load == "dashboard") { include('dashboard.php'); exit(); } // About if ($load == "about") { include('about.php'); exit(); } // Username $data_array = array(':username' => $load); $select_account = $connect->prepare("SELECT * FROM `users` WHERE `username` = :username"); $select_account-> execute($data_array); $account_amount = $select_account->rowCount(); if ($account_amount > 0) { include('profile.php?name=$load'); exit(); } // Redirect to 404 if there are no results include('404.php'); exit(); 

Everything still works, but users can upload photos to the gallery, and I want them to look like this:

 www.mysite.com/[username]/gallery/ 

But if you wrote it as a url, the rewriter reads [username]/gallery/ as one section, which means $load = [username]/gallery , which would give me "404".

Perhaps the best solution is to get the desired results, but I'm not too good at .htaccess and rewriting. I would like to add that I also like this rewrite, as I have subdirectories called signup and signin , which both have subdirectories in them too, but if I go to the url:

 www.mysite.com/signup www.mysite.com/signin 

It ignores the rewriting and goes to the directory instead of running it through the $load statements that I want.

In addition, when registering an account, any username that matches strings like dashboard or about etc. does not allow them to use it, this stops usernames and $load if / else expressions and their inclusion is mixed, etc. d.

EDIT

Another thing that I forgot to mention is that they can call the gallery on their own, they need to search to see if this gallery exists, for example:

 www.mysite.com/username/my+first+album 

First you need to check if the username exists, and then check if the album exists, and then display it if it does, or 404 / redirect to where possible, if it is not. Thus, both parameters / queries will be dynamic. Not only this, but individual photos in this album should work the same way, for example:

 www.mysite.com/username/my+first+album/my+picture 

I hope this makes sense ...

+6
source share
4 answers

Using both Aatch and Sally and a few URL routing search results, I have the following method to achieve what I was after, so I decided to share it with everyone if someone wants to use it ...

First of all, I need to mention that the site I'm working on is within 2 subdirectories of the mysite.com/sub/folder/index.php root folder, so why on arrays do I start with [3]

With that said, my .htaccess file looks like this:

 RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . sub/folder/index.php [QSA,L] 

This, as far as I am, gets everything that is written after sub/folder/ , and redirects the page directly to index.php, however it masks the URL in the address bar.

The only time he ignores this is that the subdirectory actually exists. For example, I have a folder /sub/folder/signup/ , if I had to enter it in the address bar, because the directory exists, then you are not redirected to the index.php file, but sent to the requested directory, as usual.

Now on my index.php file (remember that I start with $ uri [3] because I'm in subfolders!)

 $uri = $_SERVER['REQUEST_URI']; // This brings back /sub/folder/foo/bar/test/ $uri = explode("/", $uri); // Separate each one $var_one = $uri[3]; // foo $var_two = $uri[4]; // bar $var_three = $uri[5]; // test switch ($var_one) { case '': case 'home': include('home.php'); exit(); break; case 'signout': case 'logout': include('signout.php'); exit(); break; case 'dashboard': case 'dash': include('dashboard.php'); exit(); break; } // By Username $data_array = array(':username' => $var_one); $select_account = $connect->prepare("SELECT * FROM `users` WHERE `username` = :username"); $select_account -> execute($data_array); $account_amount = $select_account->rowCount(); if ($account_amount > 0) { include('profile.php'); exit(); } // By Account ID $data_array = array(':id' => $var_one); $select_account = $connect->prepare("SELECT * FROM `users` WHERE `id` = :id"); $select_account -> execute($data_array); $account_amount = $select_account->rowCount(); if ($account_amount > 0) { include('profile.php'); exit(); } include('page_not_found.php'); 

The switch keys are simple include, if the URL is: / sub / folder / dashboard /, then dashboard.php is displayed. If none of the cases match, we could look at the profile. The first checks to see if it can be a username; if it exists, a view profile page is displayed. He then checks to see if he can be the only identification number for this profile and performs the same check.

Finally, if no results are returned with any of them, we will be shown a page with 404 pages not found.

If it was a profile page, in the profile.php file I can check for $var_two and see if they uploaded a photo album with that name, for example /sub/folder/joe/holiday/ , if so, then run the query to get everything if not, display message / redirect or something else.

Then, if there is even more, say the specific image ( $var_three ) in this folder ( $var_two ), for example /sub/folder/joe/holiday/beach/ - then run it through a similar query showing the results.

This may not be the best method, but it’s pretty straightforward, and everything works as I would like, so I can’t complain.

0
source

Simple solution: EDIT HTACCESS

 RewriteBase / RewriteCond %{REQUEST_URI} !/signup RewriteCond %{REQUEST_URI} !/signin RewriteRule ^([^/]*)/([^/]*)$ index.php?load=gallery&username=$1&gallery=$2 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?load=$1 [QSA,L] 

Now that the part of PHP (for index.php):

 $load = $_GET['load']; switch ($load){ default: include('home.php'); exit(); break; case 'dashboard': include('dashboard.php'); exit(); break; case 'about': include('about.php'); exit(); break; case 'gallery': $username = $_GET['username']; $gallery = $_GET['gallery']; //check for the username and gallery header("Location: your-gallery-location-goes-here"); break; } 

Hope it helps :)

+3
source

What you want is what is known as a URL router, it requires you to analyze the URL and make decisions based on the content. Most systems do this by providing you with a url pattern and a function to call if the URL matches. Usually a function passes any subpatterns in the url template.

For example, Django uses regular expressions for its url routing and passes named matches as arguments to a given function (or class).

If this is too complicated for your needs, you can simply use certain regular expressions to parse the URL, in the case of your gallery:

 $matches = array(); $re = "/\/([\w\d])+\/([\w\d+%])+\/?/"; preg_match($re, $load, $matches); $username = $matches[0]; $gallery = $matches[1]; 

you can use $username and $gallery as you wish.

Note

The above assumes that it will match, you will need to check the return value of preg_match to make sure. In addition, I did not check the regex, it may be incorrect or use functions that are not included in this syntax.

Link

+2
source

Here is a simple example to get you started:

.htaccess

 RewriteEngine On RewriteRule ^includes/.*$ index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [QSA,L] 

First, you must prevent direct access to .php files, you can put them in a separate folder, for example, '/ includes', and redirect any call to this folder in index.php. Secondly, allow direct access to files (e.g. images or javascripts). The last rule redirects anything else to index.php.

Php

Basically, you should have a set of rules for checking the URL and some controller to process the result.

 define( 'WEB_ROOT', rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' ) ); define( 'INCLUDES_ROOT', 'includes/' ); // examples of rewrite rules ( $key = action, $value = regular expression ) $rules = array( 'pages' => "/(?'page'dashboard|about|signin|signup)", // eg '/about' 'gallery' => "/(?'username'[\w\-]+)/gallery", // eg '/some-user/gallery' 'album' => "/(?'username'[\w\-]+)/(?'album'[\w\-]+)", // eg '/some-user/some-album' 'picture' => "/(?'username'[\w\-]+)/(?'album'[\w\-]+)/(?'picture'[\w\-]+)", // eg '/some-user/some-album/some-picture' 'home' => "/" // eg '/' ); // get uri $uri = '/' . trim( str_replace( WEB_ROOT, '', $_SERVER['REQUEST_URI'] ), '/' ); // test uri foreach ( $rules as $action => $rule ) { $pattern = '/^'.str_replace( '/', '\/', $rule ).'$/'; if ( preg_match( $pattern, $uri, $params ) ) { /* now you know the action and parameters so you can * include appropriate template file ( or proceed in some other way ) * NOTE: variable $params vill be visible in template ( use print_r( $params ) to see result ) */ include( INCLUDES_ROOT . $action . '.php' ); // exit to avoid the 404 message exit(); } } // nothing is found so handle 404 error include( INCLUDES_ROOT . '404.php' ); 

The next step is to check the received parameters.

0
source

Source: https://habr.com/ru/post/907450/


All Articles