How to get member page like reddit (/u/cscodismith)?

I am looking to use a url like reddit has for their member page(s) (like /u/cscodismith) but am not sure how I can $_get the username from a url like that. I know I can get the username from a link if I had a url that looked like www.heartfx.org/memberpage?member=lowheartrate by just using $_get['member'].

What I came here to ask though is how can I setup a url like reddit so member pages will look like: http://www.heartfx.org/u/lowheartrate and how to $_get the username from that sort of url?

I tried to research how to do it already but can’t seem to find a solution / question similar to this. I may just be searching wrong keywords but couldn’t come across anything that helped…

Thanks,
Codi B. - Smith

Simple. This mainly is working with Apache. Here is your solution.

.htaccess

RewriteEngine On

RewriteRule ^u/([a-zA-Z0-9-_]*)$ /memberpage.php?member=$1

The above regex is allowing only alphanumeric (0 - 9 and a - z/ A - Z), dashes, and underscores.

And on your memberpage.php, you can simply print the output from $_GET to make sure everything works.

print_r($_GET['member']);

Once it works, you can then use that username to grab what’s in the database. Remember though, escape your user inputs.

2 Likes

Thanks but for some reason when looking at the url (localhost/heartfx/u/lowheartrate) it seems to print_r($_GET['username']); fine but the rest of the page doesn’t seem to look like the rest does. It doesn’t show the header as the other pages do and all of the styles look broken. Here is a preview of what I am talking about:

https://puu.sh/sCB6Q/9242f5f9ac.png


Maybe its because of what you said?

Remember though, escape your user inputs.

but I am not quite sure what you mean by that? What inputs am I escaping on my page?

Here is my .htaccess file:

RewriteEngine On

RewriteRule ^u/([a-zA-Z0-9-_]*)$ memberpage.php?member=$1

Here is my memberpage.php file:

<?php
// include common.inc.php file
include 'core/common.inc.php';
// show header
showHeader('l');

// print member...
print_r($_GET['member']);
?>

No. It has nothing to do with outputting $_GET and then removing it after testing it out. It has to do with your general files you are not including in it. If your core/common.in.php file does not include any style sheets, you’ll have to add that into your memberpage.php file manually.

Technically, you are supposed to escape the $_GET variables when you are applying it to your database. But I also believe you are supposed to validate or sanitize it. I think escaping is for outputting the data. So I suppose sanitizing the $_GET variable is what I should of said.

This ensures that the final variable you are going to use in reference to $_GET['member'] does not have any illegal characters you don’t want it to have such as Latin characters or random special characters. And maybe even exceeding the amount of characters within a username that you allow.

When you are selecting from the database, that is when you should be using Prepared Statements as this will reduce the risk of SQL Injections.

1 Like

But the thing is the showHeader(''); function that is in the memberpage.php function does include stylesheets. I call it on every page and it includes all my stylesheets and everything else from the <head> tags.

$_GET parameter shouldn’t be messing around with your style sheets. Unless you print the output before your HTML tags are started, that’s the only reason why it should happen.

Please paste your View Source Code. I believe there might be a PHP error causing this issue.

Here is the source code for localhost/heartfx/u/lowheartrate.

edit: I think I found the issue. When viewing the source code of the page (localhost/heartfx/u/lowheartrate) and I click on the css.css it gives me a 404 error because its looking for the stylesheet in /u/ directory for some reason - probably due to the .htaccess (specifically the following line: RewriteRule ^u/([a-zA-Z0-9-_]*)$ memberpage.php?member=$1).

I am not sure how I would go about fixing this because if I change the directory in the header, its going to mess around with ALL of the pages that has the showHeader(''); function :frowning:

Ok, I see where the problem is. Since the REQUEST_URI will be different, you can’t have a linked style sheet or Javascript like

<link rel="stylesheet" href="includes/css.css" type="text/css" />

You have to put in the full domain like so.

<link rel="stylesheet" href="http://localhost/includes/css.css" type="text/css" />

It’s basically because when you use the Rewriterule, the u/ basically acts like a sub-directory. So it tries to find the style sheets and links within that sub-directory. I suggest creating a constants with the main domain and link it every style sheet you have. This will in turn give you the appropriate link that is needed when browsing u/ and when uploading to a live server.

This is what I normally like to do.

define('LINK', 'http://' . $_SERVER['SERVER_NAME'] . '/');

Basically, we just get the server name which usually is just the domain itself. Doesn’t include www. and http:// so you’ll have to add those in if you want.

Then basically, we just link the styles like so.

<link rel="stylesheet" href="<?php print(LINK); ?>includes/css.css" type="text/css" />

For this snippet, you don’t have to do /includes/ because in our constants, we added the forward slash before-hand.

Using the code you provided unfortunately after viewing source code of the page it the <head> tags look like:

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="google-signin-client_id" content="618381226281-f3ht6d47jl818rjmr0p3rh3idftoaka7.apps.googleusercontent.com">
  <link rel="stylesheet" href="<?php print(LINK); ?>includes/css.css" type="text/css" />
  <link rel="stylesheet" href="includes/media_queries.css" type="text/css" />
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Oxygen:400,300,700" rel="stylesheet" type="text/css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="includes/js.js"></script>
  <script src="https://www.google.com/recaptcha/api.js"></script>
  <script src="https://apis.google.com/js/platform.js" async defer></script>
  <title>'.$title.'</title>
</head>

You can view my entire showHeader(''); function here.

Try it now.

// display all header stuff at beginning of page(s)
function showHeader($title) {
  define('LINK', 'http://' . $_SERVER['SERVER_NAME'] . '/');
 
  echo '
  <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta name="google-signin-client_id" content="618381226281-f3ht6d47jl818rjmr0p3rh3idftoaka7.apps.googleusercontent.com">
      <link rel="stylesheet" href="' . LINK . 'includes/css.css" type="text/css" />
      <link rel="stylesheet" href="' . LINK . 'includes/media_queries.css" type="text/css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700" rel="stylesheet">
      <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
      <link href="https://fonts.googleapis.com/css?family=Oxygen:400,300,700" rel="stylesheet" type="text/css">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
      <script src="' . LINK . 'includes/js.js"></script>
      <script src="https://www.google.com/recaptcha/api.js"></script>
      <script src="https://apis.google.com/js/platform.js" async defer></script>
      <title>'.$title.'</title>
    </head>
 
    <body>
    <header>
       <nav>
          <div class="navbar-left">
             <a href="index.php">
                <img src="http://i.imgur.com/4Cp2bQn.png" alt="heart[fx] logo" width="100px" />
             </a>
          </div>
  ';
 
          checkLogin();
 
  echo '
       <!-- closing tag for nav.navbar -->
       </nav>
    </header>
  ';
}
1 Like

Close but when I echo LINK; it seems to be pointing to http://localhost instead of http://localhost/heartfx as it should :frowning:

Then define that in the constants.

define('LINK', 'http://' . $_SERVER['SERVER_NAME'] . '/heartfx/');

The constants LINK is mainly supposed to be there as a reference for all your style sheets so that they don’t get error 404s. You can simply change this out when you upload it to your live server. To make this even more easier, you could just declare this constants in your common.inc.php file and you’ll be able to access that constants outside of that function.

1 Like

Thanks, got it working! Must I use this method for all of <a href=""> links as well. Seems when I try to access some of the navigation menu button(s) and such, it trys to access a link that isn’t there because again the /u/.

Yes. You will most likely have to due to /u/ acting as a sub-directory. I am not entirely sure if you want to do it like this, but I believe it’s the only way to keep /u/ if you want to do something like Reddit’s /u/ URLs.

1 Like

Thanks for all of your help but I will feel all of this is a bit much and may be a bit much for a simple url like reddit’s. I think I will just stick a url like /action.php?lookup_user=lowheartrate or something of the sort. Appreicate you walking me through this and helping me come up with a solution though!

No problem. Though I should also mention that it isn’t too hard to get used to actually. It’s just the same thing as typing the full URL like https://sitepoint.com/community/.

Unless you have Sitepoint bookmarked, you’ll end up typing sitepoint.com/community/ and that’s basically the same thing as

<?php print(LINK); ?>css/styles.css

I do it all the time with my main source codes. It’s actually useful when you want to transfer files. I mean yes, having no starting URL is also helpful, but having the full URL path generated for you and including it in your assets isn’t that hard.

1 Like

There are other approaches besides htaccess and regular expressions. There are a number of routing components which can make things easier. They do require a bit more infrastructure but once they are running, give you a great deal more functionality. Consider giving a micro-framework such as Silex a try: http://silex.sensiolabs.org/

Might be surprised at how much work it can save you.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.