How to restrict some links to be click without valid login

Discussion in 'PHP' started by vishalonne, Aug 25, 2012.

  1. #1
    I already have the php code for login and varification done using mysql database.
    I have some links which should not work if user click them without VALID LOGIN.
    My index.html page contain menu -
    Home Computer Science Informatics Practices Take Test(login required) Software Register Get Together(login required)
    Structure of my web site
    index.html---- Login Box and Register Page Link
    Computer Science (Menu)
    XI (Sub Menu)
    Unsolved Question Papers (Link) login not required
    Project Samples (Link) login not required
    Solved Materials (Link) login required
    Forum (Link) login required

    XI I (Sub Menu)
    Unsolved Question Papers (Link) login not required
    Project Samples (Link) login not required
    Solved Materials (Link) login required
    Forum (Link) login required


    Here is the code - login.php (login form)
    <script type="text/javascript" src="sha512.js"></script>  // contain encryption code
    <script type="text/javascript">
    function formhash(form, password) {
       // Create a new element input, this will be out hashed password field.
       var p = document.createElement("input");
       // Add the new element to our form.
       
       p.name = "p";
       p.type = "hidden"
       p.value = hex_sha512(password.value);
       // Make sure the plaintext password doesn't get sent.
       password.value = "";
       // Finally submit the form.
       form.appendChild(p);
       form.submit();
    }
    </script>
    <?php
    if(isset($_GET['error'])) { 
       echo 'Error Logging In!';
    }
    ?>
    </head>
    <body><form action="process_login.php" method="post" name="login_form">
       Email: <input type="text" name="email" /><br />
       Password: <input type="password" name="password" id="password"/><br />
       <input type="button" value="Login" onclick="formhash(this.form, this.form.password);" />
    </form>
    </body>
    PHP:
    process_login.php (checking validity)

    <?php
    define("HOST", "localhost"); // The host you want to connect to.
    define("USER", "root"); // The database username.
    define("PASSWORD", ""); // The database password. 
    define("DATABASE", "check1"); // The database name.
     
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    echo "Process Login";
    include 'functions.php';
    sec_session_start(); // Our custom secure way of starting a php session. 
     
    if(isset($_POST['email'], $_POST['p'])) { 
       $email = $_POST['email'];
       $password = $_POST['p']; // The hashed password.
       if(login($email, $password, $mysqli) == true) {
          // Login success
          echo 'Success: You have been logged in!';
       } else {
          // Login failed
          header('Location: ./login.php?error=1');
       }
    } else { 
       // The correct POST variables were not sent to this page.
       echo 'Invalid Request';
    }
    ?>
    PHP:
    For reference online demo site is http://www.cbsecsnip.in/
     
    vishalonne, Aug 25, 2012 IP
  2. InstaCoders

    InstaCoders Peon

    Messages:
    53
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    The way I would do it is by checking for a session to make sure it's set and then doing an option for the navigation

    Simple example is:

    if(isset($_SESSION['user'])){

    do your logged in nav here... (this contains the links to push to a normal page)

    }
    else{
    do the required login here... (this contains the links to push to a login page)
    }
     
    InstaCoders, Aug 25, 2012 IP
  3. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    Thank you InstanCoder for looking into my Issue.
    What I understand from your reply is -
    <?php
    if(isset($_SESSION['user'])){ ?>
    <div id="nav" class="image002-03">
    		<span id="smalltext" 
                style="bottom: 0px; margin-bottom: 0px; padding-bottom: 0px; font-family: Calibri; font-size: large; text-align: center;">Service Menu</span>
    		<ul id="ul1" class="serviceul">
                <li class="serviceli"><a href="unsolvedCSQPXI.php">Unsolved Question Papers</a></li>
                <li class="serviceli"><a href="unsolvedCSSPXI.php">Unsolved Sample Paper</a></li>
                <li class="serviceli"><a href="#">Notes</a></li>
                <li class="serviceli"><a href="prosamCSXI.php">Projects Samples</a></li>
                <li class="serviceli"><a href="#">Presentations</a></li>
                <li class="serviceli"><a href="#">Uploads</a></li>
                <li class="serviceli"><a href="downloads.php">Solved Materials</a></li>
                <li class="serviceli"><a href="#">Forum</a></li>
                <li class="serviceli"><a href="#">Live Chat</a></li>        </ul>
    </div>
    <?php
    }
    else{
    do the required login here... (this contains the links to push to a login page)
    }?>
    PHP:
    But the links which doesn't require login what about them?
    Am I right??
     
    vishalonne, Aug 25, 2012 IP
  4. HuggyEssex

    HuggyEssex Member

    Messages:
    297
    Likes Received:
    4
    Best Answers:
    2
    Trophy Points:
    45
    #4
    Make a function to display a link if the session is active.

    
    function show_link($link) {
    if(isset($_SESSION['user'])) {
    echo $link;
    }
    }
    
    PHP:
    Nav code

    
            <ul id="ul1" class="serviceul">
                <li class="serviceli"><a href="unsolvedCSQPXI.php">Unsolved Question Papers</a></li>
                <li class="serviceli"><a href="unsolvedCSSPXI.php">Unsolved Sample Paper</a></li>
                <li class="serviceli"><a href="#">Notes</a></li>
                <li class="serviceli"><a href="prosamCSXI.php">Projects Samples</a></li>
                <li class="serviceli"><a href="#">Presentations</a></li>
                <li class="serviceli"><a href="#">Uploads</a></li>
                <li class="serviceli"><a href="downloads.php">Solved Materials</a></li>
                <li class="serviceli"><a href="#">Forum</a></li>
                <li class="serviceli"><a href="#">Live Chat</a></li>
    <?php
    #hidden link
    show_link('<li class="serviceli"><a href="#">Live Chat</a></li>');
    ?>
    </ul>
    
    PHP:
     
    HuggyEssex, Aug 25, 2012 IP
  5. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #5
    OK I am trying as you guided
     
    vishalonne, Aug 25, 2012 IP
  6. InstaCoders

    InstaCoders Peon

    Messages:
    53
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #6
    
    
    
    <?php
    if(isset($_SESSION['user'])){ ?>
    <div id="nav" class="image002-03">
            <span id="smalltext" 
                style="bottom: 0px; margin-bottom: 0px; padding-bottom: 0px; font-family: Calibri; font-size: large; text-align: center;">Service Menu</span>
            <ul id="ul1" class="serviceul">
                <li class="serviceli"><a href="unsolvedCSQPXI.php">Unsolved Question Papers</a></li>
                <li class="serviceli"><a href="unsolvedCSSPXI.php">Unsolved Sample Paper</a></li>
                <li class="serviceli"><a href="#">Notes</a></li>
                <li class="serviceli"><a href="prosamCSXI.php">Projects Samples</a></li>
                <li class="serviceli"><a href="#">Presentations</a></li>
                <li class="serviceli"><a href="#">Uploads</a></li>
                <li class="serviceli"><a href="downloads.php">Solved Materials</a></li>
                <li class="serviceli"><a href="#">Forum</a></li>
                <li class="serviceli"><a href="#">Live Chat</a></li>        </ul>
    </div>
    <?php
    }
    else{
    
    <div id="nav" class="image002-03">
            <span id="smalltext" 
                style="bottom: 0px; margin-bottom: 0px; padding-bottom: 0px; font-family: Calibri; font-size: large; text-align: center;">Service Menu</span>
            <ul id="ul1" class="serviceul">
                <li class="serviceli"><a href="login.php">Unsolved Question Papers</a></li>
                <li class="serviceli"><a href="login.php">Unsolved Sample Paper</a></li>
                <li class="serviceli"><a href="#">Notes</a></li>
                <li class="serviceli"><a href="prosamCSXI.php">Projects Samples</a></li>
                <li class="serviceli"><a href="#">Presentations</a></li>
                <li class="serviceli"><a href="login.php">Uploads</a></li>
                <li class="serviceli"><a href="downloads.php">Solved Materials</a></li>
                <li class="serviceli"><a href="login.php">Forum</a></li>
                <li class="serviceli"><a href="#">Live Chat</a></li>        </ul>
    </div>
    
    
    
    
    
    }?>
    
    
    PHP:

    Notice the two sets of links in the above setup. The first set checks if the user is logged in and if they are they get the pages
    if they aren't (in the second section) it pushes them to the login page first. :)
     
    InstaCoders, Aug 25, 2012 IP
    vishalonne likes this.
  7. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #7
    And how I will include multiple pages to process_login.php if user is valid Take Example if user click on menu Computer Science->XII which is on index.html he will move to CSXII.php where user can see all the link then user click on the secured link I will take him back to login page where user will validate himself, NOW how he will come back directly to CSXII.php.
     
    vishalonne, Aug 25, 2012 IP
  8. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #8
    Confused you gave 2 different codes Which one I should test?
     
    vishalonne, Aug 25, 2012 IP
  9. InstaCoders

    InstaCoders Peon

    Messages:
    53
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #9
    Your pages should have a check to see if that session variable has in fact been set. Usually it's best to create a function for the check and then add that function to the top of the pages.
    In the function itself it will redirect a user if the session isn't valid. Here's a simple example

    In a functions.php file

    
    
    <?php
    session_start();
    
    function checkUser($_SESSION['user']){
    
    // Query the db to check for a valid user:
    
         $sql = "SELECT * FROM users WHERE username='{$_SESSION['user']}'";
         $res = mysql_query($sql);
    
    // Get a # of returned rows - we need 1
         $num = mysql_num_rows($res);
    
    // This could work both ways - meaning 0 users found with that name
    // or there was more than one user found with that name
    // bottom line is it checks for a value of 1
           if($num != 1){
    
    
             // No matches found - get them out of here!
                   header("Location: login.php");
                   exit;
    
    
    
          }
    
    
    }
    ?>
    
    PHP:

    Then what you do is this:

    on your secondary page (whatever it's called) my_logged_in_page.php
    you simply add this to the top

    
    
    <?php
    session_start();
    
    include('functions.php');
    
    checkUser($_SESSION['user']);
    
    ?>
    
    
    
    PHP:
    Because you included the functions file - the checkUser($_SESSION['user']); will then check in the functions.php file
    to find out what it's supposed to do and then execute it.

    The executed function will pass the variable $_SESSION['user'] to the function, fill in the sql line as needed,
    and then the sql will check the database to see if the user is there thus returning a 0, 1, or another #

    As long as the # matches '1' nothing happens and the my_login_page.php is rendered as it should be.
    But if it's not a 1 - then it will force them back to a login.php
     
    InstaCoders, Aug 25, 2012 IP
  10. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #10
    Lots of thanx for your co operation I tested something like this just tell me whether I am on right way or not.
    At top of
    
    <?php
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    echo "Process Login";
    sec_session_start();
    ?>
    
    PHP:
    Then as you guided me
    
    <?php
    if(login_check($mysqli) == true){ ?>
    <div id="nav" class="image002-03">
            <span id="smalltext" 
                style="bottom: 0px; margin-bottom: 0px; padding-bottom: 0px; font-family: Calibri; font-size: large; text-align: center;">Service Menu</span>
            <ul id="ul1" class="serviceul">
                <li class="serviceli"><a href="unsolvedCSQPXI.php">Unsolved Question Papers</a></li>
                <li class="serviceli"><a href="unsolvedCSSPXI.php">Unsolved Sample Paper</a></li>
                <li class="serviceli"><a href="#">Notes</a></li>
                <li class="serviceli"><a href="prosamCSXI.php">Projects Samples</a></li>
                <li class="serviceli"><a href="#">Presentations</a></li>
                <li class="serviceli"><a href="#">Uploads</a></li>
                <li class="serviceli"><a href="downloads.php">Solved Materials</a></li>
                <li class="serviceli"><a href="forum.php">Forum</a></li>
                <li class="serviceli"><a href="#">Live Chat</a></li>        </ul>
    </div>
    <?php
    }
    else{        ?>
    
    <div id="nav" class="image002-03">
            <span id="smalltext" 
                style="bottom: 0px; margin-bottom: 0px; padding-bottom: 0px; font-family: Calibri; font-size: large; text-align: center;">Service Menu</span>
            <ul id="ul1" class="serviceul">
                <li class="serviceli"><a href="unsolvedCSQPXI.php">Unsolved Question Papers</a></li>
                <li class="serviceli"><a href="unsolvedCSSPXI.php">Unsolved Sample Paper</a></li>
                <li class="serviceli"><a href="#">Notes</a></li>
                <li class="serviceli"><a href="prosamCSXI.php">Projects Samples</a></li>
                <li class="serviceli"><a href="#">Presentations</a></li>
                <li class="serviceli"><a href="login.php">Uploads</a></li>
                <li class="serviceli"><a href="login.php">Solved Materials</a></li>
                <li class="serviceli"><a href="login.php">Forum</a></li>
                <li class="serviceli"><a href="#">Live Chat</a></li>        </ul>
    </div>
    <?php } ?>
    
    PHP:
    Its working as I wanted but if I enter wrong password it is not showing the false block, because I am doing something wrong in process_login.php

    
    <?php
    define("HOST", "localhost"); // The host you want to connect to.
    define("USER", "root"); // The database username.
    define("PASSWORD", ""); // The database password. 
    define("DATABASE", "check1"); // The database name.
     
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    echo "Process Login";
    include 'functions.php';
    sec_session_start(); // Our custom secure way of starting a php session. 
     
    if(isset($_POST['email'], $_POST['p'])) { 
       $email = $_POST['email'];
       $password = $_POST['p']; // The hashed password.
        [B]if(login($email, $password, $mysqli) == true) {
          // Login success
          include("XICS.php");
       }[/B] else {
          // Login failed
          header('Location: ./login.php?error=1');
       }
    } else { 
       // The correct POST variables were not sent to this page.
       echo 'Invalid Request';
    }
    ?>
    
    PHP:
     
    Last edited: Aug 25, 2012
    vishalonne, Aug 25, 2012 IP
  11. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #11
    This is sec_session_start(); // Our custom secure way of starting a php session. in function.php file
    
    function sec_session_start() {
            $session_name = 'start_your_session_id'; // Set a custom session name
            $secure = false; // Set to true if using https.
            $httponly = true; // This stops javascript being able to access the session id. 
     
            ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. 
            $cookieParams = session_get_cookie_params(); // Gets current cookies params.
            session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); 
            session_name($session_name); // Sets the session name to the one set above.
            session_start(); // Start the php session
            session_regenerate_id(true); // regenerated the session, delete the old one.     
    }
    PHP:
     
    vishalonne, Aug 25, 2012 IP
  12. InstaCoders

    InstaCoders Peon

    Messages:
    53
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #12
    quickly couple things come to mind:

    header('Location: ./login.php?error=1');

    make that this:
    header('Location: login.php?error=1');

    Next thing is at the top you have:

    echo "Process Login";

    But if the script fails you need it to process a header.
    Little information on headers are that NOTHING else can be
    done first prior to a location call - if there is - then it faults out.

    So one of two ways to fix it.

    1.) Fix it so there is nothing that is being printed to the browser first (ex: no echo "Process Login";)
    2.) Use a javscript redirect instead of header on the fault out for something wrong. ;)
     
    InstaCoders, Aug 25, 2012 IP
  13. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #13
    Modified as per your instruction
    removed echo "Process Login";
    and changed this
    header('Location: ./login.php?error=1');
    to this
    header('Location: login.php?error=1');

    problem is same not show the links. What I think we must look this part of the process_login.php
    
    if(isset($_POST['email'], $_POST['p'])) { 
       $email = $_POST['email'];
       $password = $_POST['p']; // The hashed password.
        if(login($email, $password, $mysqli) == true) {
          // Login success
          include("XICS.php");
       }else {
          // Login failed
          header('Location: login.php?error=1');
       }
    } else { 
       // The correct POST variables were not sent to this page.
       echo 'Invalid Request';
    }
    
    PHP:
    Here I am including XICS.php if login is valid so automatically it means that if login is not valid this file will not take the user to XICS.php where all the link is available. So how to handle this problem please guide me, I am half the way.
     
    vishalonne, Aug 25, 2012 IP
  14. InstaCoders

    InstaCoders Peon

    Messages:
    53
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #14
    Try this - I just saw this:

    Change this:
    if(isset($_POST['email'], $_POST['p'])) {

    to this

    if(isset($_POST['email']) && isset($_POST['p'])) {

    You have to check both variables...

    another way would be:
    if(!empty($_POST['email']) && !empty($_POST['p'])){

    That should do it
     
    InstaCoders, Aug 25, 2012 IP
  15. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #15
    No..!:(
    Same result

    Should I change this line
    else {
    // Login failed
    header('Location: login.php?error=1');

    to
    else {
    // Login failed
    header('Location: XICS.php?error=1');
     
    vishalonne, Aug 25, 2012 IP
  16. InstaCoders

    InstaCoders Peon

    Messages:
    53
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #16
    what error are you getting?!
     
    InstaCoders, Aug 25, 2012 IP
  17. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #17
    Sorry for delay some problem came. I am not getting any error if I enter wrong password just it is taking back to the login page form page
    with a message
    Error Logging In!
    ID TexstBox
    Password TextBox

    And if I enter correct ID & Password

    it takes me to XICS.php page which is OK but give back this -
    Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\secure\functions.php on line 13
     
    vishalonne, Aug 25, 2012 IP
  18. vishalonne

    vishalonne Member

    Messages:
    51
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #18
    Can you please give some time if you don't mind
    I am not getting any error if I enter wrong password just it is taking back to the login page form page
    with a message
    Error Logging In!
    ID TexstBox
    Password TextBox

    And if I enter correct ID & Password

    it takes me to XICS.php page which is OK but give back this -
    Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\secure\functions.php on line 13
     
    vishalonne, Aug 25, 2012 IP
  19. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #19
    One minor point -- if every blasted LI is getting the same class, NONE of them need classes.

    I'm seeing this same re-re markup in like 20 different posts now, is there some idiotic BS CMS out there vomiting up this idiotic crap of static style and presentational ID on a span, classes on every LI for no good reason, and div around both for christmas only knows what -- apart from the ineptitude of the developers?

    Well, I guess that just goes hand in hand with the opening and closing PHP for no good reason, multiple copies of the same markup slowing down the initial parse and increasing the code size, etc, etc... but again, I'm the nut who wants <?php and ?> removed from the specification.

    Personally, I'd use one echo statement with inline conditionals for this.

    
    <?php
    
    $loggedIn=(login_check($mysqli) == true);
    
    echo '
    	<div id="nav">
    		<h2>Service Menu</h2>
    		<ul>
    			<li><a href="unsolvedCSQPXI.php">Unsolved Question Papers</a></li>
    			<li><a href="unsolvedCSSPXI.php">Unsolved Sample Paper</a></li>
    			<li><a href="#">Notes</a></li>
    			<li><a href="prosamCSXI.php">Projects Samples</a></li>
    			<li><a href="#">Presentations</a></li>
    			<li><a href="',(
    				$loggedIn ? '#' : 'login.php'
    			),'">Uploads</a></li>
    			<li><a href="',(
    				$loggedIn ? 'downloads.php' : 'login.php'
    			),'">Solved Materials</a></li>
    			<li><a href="',(
    				$loggedIn ? 'forum.php' : 'login.php'
    			),'">Forum</a></li>
    			<li><a href="#">Live Chat</a></li>
    		</ul>
    	</div>';
    
    ?>
    Code (markup):
    What was that I was saying about most people writing PHP not knowing enough HTML/CSS to be writing PHP in the first place?
     
    deathshadow, Aug 25, 2012 IP
  20. fortunechanger

    fortunechanger Peon

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #20
    You can use isset function to check the session value of the variable which can be setup when its a correct login and if its not set then you can redirect using header("Location:"), I hope this will help you to solve your problem
     
    fortunechanger, Aug 25, 2012 IP