I am really struggling understanding how to modify URL using Rewrite rules. I have seen the following link : Directly adding username to URL PHP - but the following knowledge does not seem to work for me.
I need the url to say eg. http://localhost/profile_page/Freddy
Rather than: http://localhost/profile_page.php
.htaccess (Which is located in in the default Wamp folder, C:\wamp\www)
RewriteEngine On
RewriteBase /wamp/www/
RewriteRule ^/?$ profile_page.php
RewriteRule ^/me?$ profile_page.php
RewriteRule ^/profile_page.php/([a-zA-Z0-9_\-]+)/?$ profile_page.php?u=$1
RewriteRule ^/profile/([a-zA-Z0-9_\-]+)/?$ profile_page.php?u=$1
RewriteRule ^/([a-zA-Z0-9_\-]+)/?$ profile_page.php?u=$1
I have the following questions:
1. With the rules above, although I have limited knowledge in this field, I expect it to convert the url of http://localhost/profile_page.php
to display the name of the user logged in i.e. http://localhost/profile_page/Freddy
.
Details of the user who are logged in can be gained from the session variable $username
or the variable $user
which obtains the username of the user after "u=" in the url (see below). However, the url does not display the name of the user logged in, it just says http://localhost/profile_page.php
when, if logged in as Freddy, I want it to say http://localhost/profile_page/Freddy
.
<?php
$user = "";
if (isset($_GET['u'])) {
$user = ($_GET['u']);
if (ctype_alnum($user)) { //check if the user exists
$check = mysqli_query($connect, "SELECT * FROM users WHERE username='$user'");
if (mysqli_num_rows($check) === 1) {
$get = mysqli_fetch_assoc($check);
$user = $get['username'];
$fname = $get['first_name'];
echo "<h2>Profile page for: $user</h2>";
} else { // refresh page
echo "<meta http-equiv=\"refresh\" content=\"0; url=http://localhost/index.php\">";
exit();
}
}
}
?>
2. If, in the URL, I type http://localhost/profile_page.php?u=Fred
, it echo's it is on Fred's page, but displays the profile page of the user logged in, so it displays posts and information for Freddy, rather than Fred, as specified in the URL.
You can replace your .htaccess with this:
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^(me)?/?$ profile_page.php [L,NC]
RewriteRule ^profile(?:_page)?/([\w-]+)/?$ profile_page.php?u=$1 [L,QSA,NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ profile_page.php?u=$1 [L,QSA]