treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Nice Profile URL?

  • I put this in the PHP section, but it might as well be .htaccess . So I have this basic profile page, kind of like facebook's:
    /profile.php?id=1

    By using PHP, I want to get the username for that ID (which I know how to do), and then go like this:

    Redirect
    /profile.php?id=1
    to go to
    /Schart

    My "get username from id" code:

    <?php

    $id = $_GET['id']; //ID of page, (profile.php?id=1)


    /* Also, a session with user information:
    $username = $_SESSION['username']; // Username of logged in user
    $password = $_SESSION['password']; // Password of logged in user
    */

    $write = mysql_query("SELECT username FROM husers
    WHERE id = '$id'");
    $uname = "";
    while ($row = mysql_fetch_assoc($write)) {
    $uname .= $row['username']; // Username of the profile page.
    }
    ?>


    http://underbakke.net/profile.php?id=1
    http://underbakke.net/index.php
  • Expanding on the code i gave you in the other thread at https://css-tricks.com/forums/discussion/15865/if-id-does-not-exists-php#Item_5

    PHP can do the redirect for you with a header rewrite - but, and this is important, the header rewrite only works if you have not yet outputted anything else so this PHP code needs to come at the very top of your php file with no whitespace before it
    <?php
    $id = mysql_real_escape_string($_GET['id']);
    $sql = "SELECT * FROM users WHERE id=$id";
    $result = mysql_query($sql);

    if (mysql_num_rows($result)==0) {
    echo ('User never existed');
    }
    else if (mysql_num_rows($result)==1) {
    $userinfo = mysql_fetch_array($result);
    if (!$userinfo['active']) {
    echo ('User no longer exists.');
    }
    else {
    $username = $userinfo['username'];
    header('Location: http://www.yoursite.com/'.$username);
    }
    }
    ?>
  • I get how you are thinking put then I have to create a page for every user won't I?
  • oh i see you want the url to change and then it to pull the correct page then you would need some .htaccess rules to make that work else each username will need a page
  • Yeah, I know. Not exactly sure how though, that's my problem.
  • No one? Really :o
  • And the original code would need to be expanded to account for username variables too so

    oh i see you want the url to change and then it to pull the correct page. Then you need to do something like the following

    <?php

    if (isset($_GET['id'])) {

    $id = mysql_real_escape_string($_GET['id']);
    $sql = "SELECT * FROM users WHERE id=$id";
    $result = mysql_query($sql);

    if (mysql_num_rows($result)==0) {
    echo ('User never existed');
    }
    else if (mysql_num_rows($result)==1) {
    $userinfo = mysql_fetch_array($result);
    if (!$userinfo['active']) {
    echo ('User no longer exists.');
    }
    else {
    $username = $userinfo['username'];
    header('Location: http://www.yoursite.com/'.$username);
    }
    }
    }

    else if (isset($_GET['username'])) {

    $uname = mysql_real_escape_string($_GET['username']);
    $sql = "SELECT * FROM users WHERE username=$username";
    $result = mysql_query($sql);

    if (mysql_num_rows($result)==0) {
    echo ('User never existed');
    }
    else if (mysql_num_rows($result)==1) {
    $userinfo = mysql_fetch_array($result);
    if (!$userinfo['active']) {
    echo ('User no longer exists.');
    }
    else {
    echo('Welcome to your Profile Page '.$userinfo['full name');
    }
    }
    }
    ?>
  • I got something decent:
    http://underbakke.net/profile.php?id=1
    goes to
    http://underbakke.net/profile/1

    If it hadn't, I would have had to change a LOT of code
  • Now how do I redirect this? Can't do it in PHP the way you wrote, it goes in to a loop. How do I redirect with .htaccess ?
    /profile.php?id=****
    to go to
    /profile/****
  • How about: RewriteRule ^profile.php?id=(.*) /profile/$1 ?
  • Would think so, but it didn't change anything :/
  • Oh, sorry, htaccess rewrite is just serversite. You should have a site like go.php?id=ID that makes an active redirect to a site and have a htaccess like this: : RewriteRule ^profile.php?id=(.*) go.php?id=$1 and go.php should be a php script that gets the ID-parameter and redirects to /profile/1234

    Anyway that would result in an error, if you have RewriteRule ^ /profile/(.*) /profile.php?id=$1 because it would always redirect to each other. maybe you should have a copy of profile.php with another name and do this:
    RewriteRule ^profile.php?id=(.*) go.php?id=$1
    RewriteRule ^ /profile/(.*) /profilecopy.php?id=$1
  • or you could try just within your profile.php via $_SERVER['PHP_SELF'] to redirect to /profile/1234 if the url is /profile.php?id=1234. Of course you'd also need RewriteRule ^ /profile/(.*) /profile.php?id=$1 in your htaccess
  • I "totally" understood that. Could you maybe set up an organized instruction :)? Thanks :D
  • Wow, this totally just missed my mind:

    $url = $_SERVER['REQUEST_URI'];
    if (strpos($url, "profile.php")!==false){
    header("Location: http://domain.com/profile/$id&quot;);
    }


  • <?
    $location = htmlspecialchars($_SERVER['PHP_SELF']);
    $location = substr($location, 0, 6);
    if($location != '/profile/'){
    $id = htmlspecialchars($_GET['id']);
    header("Location: /profile/$id");
    }
    ?>

    just include this in first place in your profile.php and put RewriteRule ^ /profile/(.*) /profile.php?id=$1 in your htaccess
  • You got it
  • @31M1K97 - Incredibly new - this website is my "training grounds" ;)
  • Sorry if i confused you with my earlier suggestion, I was suggesting you'd need a combination of both mod rewrite and the php. You'd obviously need to make sure the mod rewrite was selective enough not to catch the full redirected URL that php needs also and the header rewrite would need to be redone to avoid the double redirect.

    On a different thought, if you were doing ajax you could alternately use a hashtag like "site#username" and then pull the pages with a get request to PHP but this would only work if you were using ajax as hashtags don't get passed server side to PHP.
  • Before we end this discussion, anyone have an idea of how I can get PHP variables using .htaccess ? The reason is that I would like to use the username instead of the ID on the new page. I know it's possible, because you can change them using .htaccess - I'm just too much of a noob to figure this out.
  • @schart : I would've been glad to know this site when I started :D

    @bungle : I'd suggest rather not to use Ajax with hashtags until history.pushState is widely supported to use Ajax and give parameters to Php on reload. It's also the way Facebook and Github do it, Facebook just also provides it with hashtags for older browsers
  • @31M1K97 - It's great help ;)
  • you can have the php run the queries from either id or username anyway

    so "site/profile/username" becomes rewritten to site/profile.php?u=username"

    and the php then does

    $username=mysql_real_escape_string($_GET['u']);
    "SELECT * from users where username=$username"
  • Why you don't just deliver the name instead of the Id to the profile.php?
  • Bungle was faster than me, because of my phone, this German autocorrect is killimg me!
  • I would have to change lots of code, it's a profile page so everything is recognized by the ID.
  • "select Id from Table where Name='$name'" and you have the id
  • I don't think you can set the handler of .htaccess because that is done in .htaccess. There's no way of using Php within .htaccess
  • Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /customers/9/7/5/underbakke.net/httpd.www/profile.php on line 25 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /customers/9/7/5/underbakke.net/httpd.www/profile.php on line 92
  • It's logical to just swap ID and Name, but for some reason, the above happens.
  • You know what? I don't care, /profile/$id looks great too :) - Thank's for your help everyone :D
  • "Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /customers/9/7/5/underbakke.net/httpd.www/profile.php on line 25 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /customers/9/7/5/underbakke.net/httpd.www/profile.php on line 92"

    Your mysql_query() must be returning false rather than an array.

    I would guess that is because your query needs to query username = "something" where as id can successfully be queried against a non quoted integer like id = 3

    you would need to modify the query to

    'SELECT * from users WHERE username = "'.$username.'"'

    so that the username is quoted out in the actual query string.
  • I'm gonna try.
  • No luck there
  • Something else must be wrong in the query though, that error means the query is failing

    I would put an echo line in after the query to see exactly what the query that php is running is. You can then run that query manually and have sql tell you what's wring with it.

    $sql='SELECT from blah blah';
    echo $sql;
    $result = mysql_query($sql);
  • <?php
    //This will start a session
    ini_set('session.cookie_domain', '.underbakke.net' );
    session_start();


    //Connect to database
    $connect = mysql_connect("underbakke.net.mysql", "underbakke_net", "*******");
    $select_db = mysql_select_db("underbakke_net", $connect);


    //Define Variables

    $username = $_SESSION['username'];
    $password = $_SESSION['password'];
    $email = $_SESSION['email'];
    $id = $_GET["id"];

    $writes = mysql_query("SELECT `id` FROM `husers` WHERE 1");

    $url = $_SERVER['REQUEST_URI'];
    if (strpos($url, "profile.php")!==false){
    header("Location: http://underbakke.net/profile/$id&quot;);
    }



    //Get ID/Username and stuffzz

    $write = mysql_query("SELECT username FROM husers
    WHERE id = '$id'");
    $uname = "";
    while ($row = mysql_fetch_assoc($write)) {
    $uname .= $row['username'];
    }



    if ($uname == "Schart"){
    echo("<div style='position:absolute;top:0px;right:0px;color:grey;background-color:white;padding:5px;border-bottom-left-radius:5px;'><span style='font-family:icons;color:black !important;font-weight:bold;'>s</span> Admin</div>");
    }



    $asd = mysql_query("SELECT info FROM husers
    WHERE id = '$id'");
    $infoo = "";
    while ($row = mysql_fetch_assoc($asd)) {
    $infoo .= $row['info'];
    }
    $dsa = mysql_query("SELECT email FROM husers
    WHERE id = '$id'");
    $emaill = "";
    while ($row = mysql_fetch_assoc($dsa)) {
    $emaill .= $row['email'];
    }
    $aaa = mysql_query("SELECT img FROM husers
    WHERE id = '$id'");
    $imgsrc = "";
    while ($row = mysql_fetch_assoc($aaa)) {
    $imgsrc .= $row['img'];
    }
    $bbb = mysql_query("SELECT id FROM husers
    WHERE username = '$username'");
    $myid = "";
    while ($row = mysql_fetch_assoc($bbb)) {
    $myid .= $row['id'];
    }

    $ccc = mysql_query("SELECT color FROM husers
    WHERE username = '$uname'");
    $bgcolor = "";
    while ($row = mysql_fetch_assoc($ccc)){
    $bgcolor .= $row['color'];
    }

    $id2 = mysql_real_escape_string($_GET['id']);
    $sql = "SELECT * FROM husers WHERE id=$id2";
    $result = mysql_query($sql);

    if (mysql_num_rows($result)==0) {
    ?>
    <title>User 404</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script&gt;
    <link rel="stylesheet" href="http://underbakke.net/style.css"></link&gt;
    <center>
    <div id="content">
    <span class="title"><center>User 404</center></span>
    <hr />
    <span style="font-size:18px;">The account has never existed, is not available or has been deleted, <i style="color:gray;">sorry</i>!</span>
    </div>
    </center><a href="/index.php" style="position:absolute;left:0px;top:0px;font-family:icons;font-size:20px;padding:2px;border-bottom-right-radius:5px;background-color:#EBEBEB;text-decoration:none !important;">H</a>

    <style>
    body{
    background-color:#EBEBEB;
    }
    </style>
    <script>
    $(document).ready(function(){
    $("#content").hide();
    $("#content").fadeIn(1000);
    });

    </script>
    <?php
    }
    else if (mysql_num_rows($result)==1) {
    $userinfo = mysql_fetch_array($result);
    if (!$userinfo['active']){
    ?>
    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" href="jquery.fancybox-1.3.4.css"></link>
    <script type="text/javascript" src="jquery.fancybox-1.3.4.pack.js"></script>
    <title><?php echo($uname) ?>'s Profile | Underbakke.net</title>
    <link rel="stylesheet" href="/style.css"></link>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script&gt;
    <script src="script.js"></script>
    <link rel="stylesheet" href="http://underbakke.net/bgstyle.php?id=<?php echo($id) ?>" media="screen">
    </head>
    <body bgcolor="<?php echo($bgcolor) ?>">
    <a href="/index.php" style="position:absolute;left:0px;top:0px;font-family:icons;font-size:20px;padding:2px;border-bottom-right-radius:5px;background-color:#EBEBEB;text-decoration:none !important;">H</a>
    <center>
    <div id="content">
    <center><span class="title"> <?php echo($uname) ?><?php if($username != $uname){ ?><a href="<?php echo($imgsrc) ?>" id="single_image" rel="lightbox" title="<?php echo($uname) ?>'s Profile Photo"><?php } ?> <?php if($username == $uname){ ?><a href="#" id="changeImg" class="profilePicture" title="Change picture"> <?php } ?><img src="<?php echo($imgsrc) ?>" style="height:70px;max-width:120px;opacity:0.5;float:right;" class="profilePicture" /><?php if($username == $uname){ ?> </a> <?php } ?><?php if ($username != $uname){ ?> </a> <?php } ?></span></center>
    <hr />
    <br /><br />
    <span style="font-size:18px;"><?php if ($username == $uname){ ?> <a href="#" id="changeInfo" style="font-family:icons;color:green;float:righT;text-decoration:none !important;" title="Change Info">C</a><?php } ?> Info:</span>
    <div id="pbox" <?php if($username == $uname){ ?>style="min-height:100px;"<?php } ?>>
    <?php if($username != $uname){?><span style="font-family:icons;font-size:18px;">i</span><?php } ?> <?php if($username == $uname){ ?><form action="http://underbakke.net/updateinfo.php?id=<?php echo($id) ?>" method="post" name="myform">
    <span style="font-family:icons;font-size:18px;float:left;">i</span>
    <textarea type="text" onkeypress="return check(event)" id="nctx" style="background-color:#ddd;float:left;border:0px solid #d3d3d3;display:inline;min-width:700px;max-width:400px;min-height:100px;max-height:100px;outline: none;" name="img" value="<?php echo($infoo) ?>" >
    <?php echo($infoo) ?>
    </textarea><br />

    <input type="submit" value="Change" id="submizz" />

    </form><?php } ?><?php if($username != $uname){?><?php echo($infoo) ?><?php } ?>

    </div><br />
    <span style="font-size:18px;"><?php if ($username == $uname){ ?><a href="#" id="changeMail" style="font-family:icons;color:green;float:righT;text-decoration:none !important;" title="Change Email">C</a><?php } ?> Contact:</span>
    <div id="pbox">
    <?php if($username != $uname){ ?><span style="font-family:icons;font-size:18px;">E</span><?php } ?> <?php if($username == $uname){ ?> <form action="http://underbakke.net/updatemail.php&quot; method="post">
    <span style="font-family:icons;font-size:18px;">E</span>
    <input type="text" style="border:1px solid #ddd;background-color:#ddd;outline: none;" name="img" value="<?php echo($emaill) ?>" id="nctx2" size="50" title="Press ENTER To Change!" />

    <input type="submit" style="display:none" value="Change" />

    </form> <?php } ?><?php if($username != $uname){ ?><a href="mailto:<?php echo($emaill) ?>"><?php echo($emaill) ?></a> <?php } ?>
    </div><br />
    <?php if($username == $uname){ ?><br /><a href="#" id="changeImg2">Edit/Add</a> Profile Picture | <a href="#" id="changeBg">Change</a> Background <?php } ?>

    <!--
    <div style="padding:10px;">
    ID: <?php echo($id) ?><br />
    Username: <?php echo($uname) ?><br />
    <?php echo($name) ?>
    </div>
    -->
    </div>
    <br />
    <div id="uimg">

    <form action="http://underbakke.net/updatepic.php&quot; method="post">

    <input type="text" name="img" value="Image URL" />

    <input type="submit" value="Change" />

    </form>

    </div>

    <div id="uinfo">
    <form action="http://underbakke.net/updateinfo.php?id=<?php echo($id) ?>" name="myform" method="post">

    <textarea type="text" onkeypress="return check(event)" id="nctx" style="min-width:400px;max-width:400px;min-height:100px;" name="img" value="<?php echo($infoo) ?>">
    <?php echo($infoo) ?>
    </textarea><br />

    <input type="submit" value="Change" />

    </form>

    </div>

    <div id="umail">
    <form action="http://underbakke.net/updatemail.php&quot; method="post">

    <input type="text" name="img" value="<?php echo($emaill) ?>" />

    <input type="submit" value="Change" />

    </form>
    </div>
    <div id="ubg">
    <form action="http://underbakke.net/bgcolor.php&quot; method="post">
    #<input type="text" size="10" name="color" id="bgco" />
    <input type="submit" value="Change" />
    </form>
    <a href="http://www.w3schools.com/html/html_colors.asp">Colors</a&gt;
    </div>

    [...]
  • Couple of different points for you

    In the middle of this you have a series of queries run one after the other using a while loop to and mysql_fetch_assoc each time to fill a variable

    You can fill all of these with a single query and mysql_fetch_array()

    So instead

    $result = mysql_query("SELECT info,email,img FROM husers WHERE id = $id");
    $userinfo = mysql_fetch_array($result);
    $info = $userinfo['info'];
    $email = $userinfo['email'];
    $img = $userinfo['img'];

    will save you running multiple queries

    Also, be careful when including variables in query statements

    PHP will substitute in variables only inside double quotes

    So $sql = 'SELECT * from users where id = $id';

    will not work, instead you need

    $sql = "SELECT * from users where id = $id";

    or

    $sql = 'SELECT * from users where id = '.$id;

    and if you need to include a string rather than an integer then you need to quote that string inside the sql statement

    so $sql = 'SELECT * from users where username = "'.$uname.'"';

    will result in an actual query of SELECT * from users where username = "john" or whatever

    Make sense?
  • I do understand, let me edit and post it here before publishing...

  • <?php
    //This will start a session
    ini_set('session.cookie_domain', '.underbakke.net' );
    session_start();


    //Connect to database
    $connect = mysql_connect("underbakke.net.mysql", "underbakke_net", "*******");
    $select_db = mysql_select_db("underbakke_net", $connect);


    //Define Variables

    $username = $_SESSION['username'];
    $password = $_SESSION['password'];
    $email = $_SESSION['email'];
    $id = $_GET["id"];

    $writes = mysql_query("SELECT `id` FROM `husers` WHERE 1");

    $url = $_SERVER['REQUEST_URI'];
    if (strpos($url, "profile.php")!==false){
    header("Location: http://underbakke.net/profile/$id&quot;);
    }



    //Get ID/Username and stuffzz

    $write = mysql_query("SELECT username FROM husers
    WHERE id = $id");
    $uname = "";
    while ($row = mysql_fetch_assoc($write)) {
    $uname .= $row['username'];
    }



    if ($uname == "Schart"){
    echo("<div style='position:absolute;top:0px;right:0px;color:grey;background-color:white;padding:5px;border-bottom-left-radius:5px;'><span style='font-family:icons;color:black !important;font-weight:bold;'>s</span> Admin</div>");
    }



    $result = mysql_query("SELECT info,email,img FROM husers WHERE id = $id");
    $userinfo = mysql_fetch_array($result);
    $info = $userinfo['info'];
    $email = $userinfo['email'];
    $img = $userinfo['img'];

    $id2 = mysql_real_escape_string($_GET['id']);
    $sql = "SELECT * FROM husers WHERE id=$id2";
    $result = mysql_query($sql);

    if (mysql_num_rows($result)==0) {

    ?>
  • What is this line

    $writes = mysql_query("SELECT `id` FROM `husers` WHERE 1");

    trying to do? That is the source of your boolean error, I had not noticed it before. WHERE needs a match to look for.
  • To be honest, no idea. I probarbly didn't remove it when I experimented.
    So if you scratch that, how does it look?
  • I can't see any reason for it being there.

    Also you need to sanitize your get variables to prevent SQL injection

    so the line that reads

    $id = $_GET["id"];

    needs to become

    $id = mysql_real_escape_string($_GET["id"]);

    or you are leaving yourself wide open when $id gets used in a query.
  • Ok, thanks, going to create a demo.
  • OK, the demo is working, now how do I convert this into username instead?
  • Is the whole site login only? Do you always have access to a session username?

    If so the login page needs to redirect on success to /profile/username

    and then you can just use the session username to fill variables with

    SELECT * from users WHERE username = $username

    If you have session variables always set then you don't need to be passing the username or id back to the profile page, as they will be set in the session.
  • What? - I have a login page, and register and all that, a session too. You can see on the top of my code that I get $username and $password from the session. Now how do I make the page be like profile.php?id=Username
    instead of the real ID, which makes the new profile page be
    profile/username
  • OK well if you have a session you don't need to be passing the id or username to the profile page as they are already stored in the session

    You can have mod rewrite turn profile/username into profile.php and then at the top of profile.php you can run

    $result = mysql_query('SELECT * from users WHERE username = "'.$_SESSION['username'].'"');
    $userinfo = mysql_fetch_array($result);

    to fill $userinfo with all your users details for use on your profile page. You don't need to pass ?id= or ?username= to profile .php to achieve this, that's what the session variables are for.
  • Wait, the session is for the user that is logged in. The "$_GET" is the id of the profile-page. So if you're logged in and visit your own profile you can edit it, if you visit anyone else's, you can't.
  • ok i get what you are doing.

    So if you have profile.php?id=roger

    Then you need to do

    if (isset($_GET['id']) && $_GET['id']!==$_SESSION['username']) {
    $user = mysql_real_escape_string($_GET['id']);
    $result = 'SELECT * from users where username = '"'.$user.'"';
    if (mysql_num_rows($result)==0) {
    echo ('invalid user');
    exit;
    }
    }
    else {
    $result = 'SELECT * from users where username = '"'.$_SESSION['username'].'"';
    }

    $profileinfo = mysql_fetch_array($result); //fill array with profile page info
    echo ('Welcome to '.$profileinfo['name']); // write out the profile page

    This will return a third party profile page if their username is passed, and the users own profile if no username is passed or their own is passed

  • Sorry I haven't responded. I made it work, (on another website). Now the only problem is the .htaccess, kind of. Well, how do I rewrite "/profile.php?name=Schart" to "/Schart" . I've gotten it to work with "/a/Schart" but, how do I make it "/Schart" :)?