user3095133
user3095133

Reputation:

URL Rewriting in PHP causing problems

Here is my .htaccess:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ profile.php?user=$1 [L,QSA]
</IfModule>

here is profile.php:

if(isset($_GET['user']) && strlen($_GET['user'])>0) {
    $userreal = $_GET['user'];
    $stmt = $mysqli->prepare("SELECT username FROM users WHERE username=?");
    $stmt->bind_param('s', $userreal);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows == 1) {
        $user = $_GET['user'];
    }
    else {
        $us = $_SESSION['username'];
        header("Location: profile/" . $us);
        exit();
    }
    $stmt->close();
}
else {
    $us = $_SESSION['username'];
    header("Location: profile/" . $us);
    exit();
}

This is my redirecting part (thought it might be helpful).

but it redirects me to:

http://localhost/PHP/Projects/HassanTech/pages/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/profile/Hassan

when I try to access

http://localhost/PHP/Projects/HassanTech/pages/profile

I want my links:

http://localhost/PHP/Projects/HassanTech/pages/profile?user=Hassan

to

http://localhost/PHP/Projects/HassanTech/pages/profile/Hassan

My .htaccess file is in the pages folder and the profile.php is in the pages folder. Hope you can help me.

Upvotes: 1

Views: 102

Answers (2)

user3095133
user3095133

Reputation:

RewriteEngine On
RewriteRule ^pages/profile/([^/]+)/?$ pages/profile.php?user=$1 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

Did the trick for me. :]

Upvotes: 0

David Smith
David Smith

Reputation: 91

Change your header redirect to use ./ and you will stay in the same directory thus resolving your problem:

header("Location: ./" . $us);

Upvotes: 1

Related Questions