PHP Based Site Access Authentication - Help - How to block parts of your web-site ??

free web hosting
Free Web Hosting > Computers & Tech > Programming > Scripting > PHP

PHP Based Site Access Authentication - Help - How to block parts of your web-site ??

sohahm
How can i program my web page using php that when the value of the login box is equal to some string then go to my success.html
otherwise on my fail.html????help me guys!


------------------------------------
It would help the readers far better to understand what your problem is - if you state the nature of it in short in your topic title, instead of just "Php help". It'll also get you a lot more responses. Am changing your topic title to give you an example.
All the best smile.gif
m^e

Reply

marijnnn
go for this:
CODE

<?php
// first part: settings. change these like you want and like they should be
define("CORRECT_LOGIN","..."); // instead of the ..., put the username you are talking about.
define("PAGE_CORRECT","success.html"); //change this one in something nobody will guess so they can't skip the login page. it's not really safe, but it's something
define("PAGE_WRONG","fail.html");
//second part. code. don't change here
if (isset($_POST["login")){
  if($_POST["login"]==CORRECT_LOGIN){
     header("Location: ".PAGE_CORRECT);
     exit;
  }
  else{
     header("Location: ".PAGE_WRONG);
     exit;
  }
}
else{
//next part is just html, you can change here if you want to adjust layout and ****. be carefull when changing the form though
?>

<html><head><title>blabla</title></head><body>
<form method="post">
login: <input type="text" name="login"><br>
<input type="submit" value="login">
</form>
</body>
</html>
<? } ?>


it's not tested though. i'm to lazy to start up linux to do so and i still can't access my ftp of astahost, so i can't test it there either ;(
but except for some small mistakes, it should work

 

 

 


Reply

miCRoSCoPiC^eaRthLinG
    [/tab]marjinn - your code works but there's one big flaw. Once you know the name of this page (if you are a regular visitor you'd know for sure) - then you can totally bypass this authentication page and go to that success.html directly. Nothing can stop you....even if you give the page an extremely cryptic name - all you need to do it note it down (just copy paste it tongue.gif )...

Here's another solution I found - and gave it a try too on my server.. It works without a hitch. The authentication is done in the AstaHost cPanel style - exactly like the box that pops-up in your browser asking for login/pass combo. The concept is to NOT HAVE the authentication code in another web-page that loads your "success.html" - but to have it embedded in the success.html ITSELF. That'll completely block you out from success.html if you don't enter a pair of valid credentials. This way even if you know the name of the page - ie success.html here - your page won't be displayed to you unless you can verify yourself....

Here's the working code from what I learnt today.
CODE

<?php
// HTTP Header-based Authenticatoion test


// This is the actual function that matches the username/password combo with a list
// in some database or flat file
function validate_user ($username, $password)
{

       // This is just a sample array containing two username/passes
       // In your real program, you should ideally load a matching password
       // from some database or file depending on the username entered and check
       // accordingly
       $userlist = array('micro' => 'pass',
                               'earth' => 'pass');

       // Checks if the password matches the corresponding user
       if (isset($userlist[$username]) && ($userlist[$username] == $password))
       {
               return true;   // If match --> return true
       }
       else
       {
               return false;  // No match --> return false
       }

}


// This is the actual code that makes the browser pop-up the authentication box and then
// display the rest of your page if authentication goes fine.
if (!validate_user($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))
{
       // Feel free to modify the Basic realm="......" part, i.e. the string within the
       // quotes (""). I've used "Protected Zone" here --> you can change it to whatever...That's
       // what will appear in your pop-up login box.
       header('WWW-Authenticate: Basic realm="Protected Zone"');
       header('HTTP/1.0 401 Unauthorized');
       // Display a custom error message - change it to whatever you feel like
       echo "You didn't say the magic word. Access denied.";
       exit;
}
else
{
       // Show a welcome message if user/pass combo is correct
       echo "Welcome to the Protected Zone.";
       // Rest of your protected page goes here
       // ............
       // ............................
       // .......................................

}

?>



[tab]I don't think much is needed in the way of an explanation - coz I inserted a good amount of comments in there... Still here's a brief note on the parts that I missed out on. The $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] are global variables that contain the username and password supplied by the user during the auth. process. Notice the
QUOTE
        header('WWW-Authenticate: Basic realm="Protected Zone"');
        header('HTTP/1.0 401 Unauthorized');

part. When your browser receives the 401 header, it pops up that dialog box for user/pass. On validation, it loads the rest of your page - if its a mismatch or Cancel is pressed - the code exits right then and denies access to the rest of the page. The Basic realm in the first line of the header makes the current page a part of the authenticated realm you are trying to enter. Note: ANY OTHER PAGE with the same Basic realm="xxx" header will be thus accessible with JUST ONE LOGIN. If you want to protect another set of pages for a different group of users, just use a different Basic realm name for those pages.

    Also, once you enter a set of valid credentials, your browser wouldn't ask you again - even if you reload the page. You're authenticated for good till you close that window and exit the site in process. That's the only flip side of this code - it doesn't provide you with a clean method to LOGOUT, although you could use a combination of cookies/session with this to achieve a logout effect. More on that later...

Hope this helps smile.gif

Reply

Hercco
I have programmed my own system for PHP authentication. It uses PHP sessions and MySQL database.

If you're not using HTTP authentication PHP sessions is the way to go. You mihgt have noticed that most PHP systems (like forums) do the authentication with sessions.

However sessions aren't that secure... If you just set a certain sessions variable (like $_SESSION['logged_in']=true;) it is actually quite easy to go in without knowing the password. Session IDs are passed at the end of url (if cookies are not available) and people pass links to each other... There are countless of pages in the web about session insecurity so I'm not going to repeat everything here...

As sessions aren't secure enough, you need something to go with it. To avoid these sessions hijackings, saving the users IP address and checking against it on everytime login is checked helps. My system includes this. On login it simply dumps the session ID and user IP to a database table. Then of course timestamp needs to be updated everytime the users logs in or login is checked, otherwise the old sid's and IPs would mess up the system.

This solution isn't perfect... People are behind same IP addresses (proxies) and IP spoofing is possible. But it's still better than basic session or let alone cookie system. Just remember that you should be using a authentication system adequate to your system.

Reply

CrazyPensil
Registering:

CODE
<?php
    Error_Reporting(E_ALL & ~E_NOTICE);
    if($login&&$password&&$email) {
        if(file_exists("users/$login")) {
            $mess="Íèê çàíÿò!";
        }
        else {
            mkdir("users/$login", 0777);
            $fp=fopen("users/$login/main.txt", "w");
            fwrite($fp, "$password|$email");
            fclose($fp);
            $mess="Óñïåøíî.";
        }
    }
    else {
        $mess="Ðåãèñòðàöèÿ";
    }
?>
<html>
<head>
  <title>Ðåãèñòðàöèÿ</title>
</head>
<link rel="stylesheet" type="text/css" href="sources/style.css">
<body onload="java script: a=document.getElementsByTagName('img');for(n=0;n<a.length;n++){i=a[n]; if(i.width==468&&i.height==60){i.style.display='none';}}void 0;" style="margin-top: 130px;" background="sources/reg.jpg">
<center>
<table style="background-image: url(sources/perg.jpg);">
<form action="reg.php" method="post">
<tr colspan="2">
<td colspan="2" class=hid><center><?=$mess;?></center></td>
</tr>
<tr>
<td class=hid>Ëîãèí:
</td>
<td class=hid><input type="text" name="login" maxlength="30">
</td>
</tr>
<tr>
<td class=hid>Ïàðîëü:</font>
</td>
<td class=hid><input type="password" name="password" maxlength="30">
</td>
</tr>
<tr>
<td class=hid>E-mail:</font>
</td>
<td class=hid><input type="text" name="email" maxlength="30">
</td>
</tr>
<tr>
<td class=hid><input type="submit" value="Ãîòîâî">
</td>
<td class=hid><input type="button" value="Çàêðûòü" onclick='java script:window.close();'>
</td>
</tr>
</form>
</table>
</center>
</body>
</html>


Checking when enters:
CODE
<?php
Error_Reporting(E_ALL & ~E_NOTICE);
if($login&&$password) {
        if(file_exists("sources/list.txt")) {
            $fp=fopen("sources/list.txt", "r");
            $lis="";
            while(!feof($fp)) {
                $lis.=fread($fp, 5016);
            }
            fclose($fp);
            $all=explode("|",$lis);
            foreach($all as $usr) {
                if($usr==$login) {
                    $t=$usr;
                    break;
                }
            }
            if($t) {
                $fp=fopen("users/$t/main.txt", "r");
                $line=fgets($fp, 1024);
                $u=explode("|", $line);

            if($u[0]==$password) {
            $tr=1;
            }
            else {
                $mess="Îøèáî÷íûé ïàðîëü!";
            }
            }
            else {
                $mess="Îøèáî÷íûé íèê!";
            }
        }
        else {
            $mess="Çàðåãèñòðèðóéòåñü!";
        }
    }
    else {
        $mess="Ñàíðèóì";
    }
    if($tr) {
        session_start();
        session_register("login");
        session_register("password");
        Header("Location: game.php?PHPSESSID=$PHPSESSID");
    }
?>

Checking while travelling on the site:
CODE
<?php
Error_Reporting(E_ALL & ~E_NOTICE);
if($login&&$password) {
        if(file_exists("sources/list.txt")) {
            $fp=fopen("sources/list.txt", "r");
            $lis="";
            while(!feof($fp)) {
                $lis.=fread($fp, 5016);
            }
            fclose($fp);
            $all=explode("|",$lis);
            foreach($all as $usr) {
                if($usr==$login) {
                    $t=$usr;
                    break;
                }
            }
            if($t) {
                $fp=fopen("users/$t/main.txt", "r");
                $line=fgets($fp, 1024);
                $u=explode("|", $line);

            if($u[0]==$password) {
            $tr=1;
            }
            else {
                Header("Location: index.php");
            }
            }
            else {
                Header("Location: index.php");
            }
        }
        else {
            Header("Location: index.php");
        }
    }
    else {
        Header("Location: index.php");
    }
?>


P.S. Don't forget about session_start(); in the beginning wink.gif

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

Recent Queries:-
  1. realm based authentication yahoo - 34.81 hr back. (1)
  2. site give u access any login - 85.04 hr back. (1)
Similar Topics

Keywords : php, based, site, access, authentication, block, parts, web, site

  1. Automated Product Suggestion Script
    Compare user lists and suggest related items based on pattern matching (2)
  2. Getting Certain Parts Of A Record
    The character data (17)
    Ok I need help on this puzzling problem. At first I thought that this person stored the dates in the
    MySQL database like this: August 27, 2007 That kinda freaked me out a little, because string dates
    are hard to manipulate. Then I found out that he stored both th string data and numerical date,
    which I found a little bit odd, but it was like this: 2007-08-27 I need to build a PHP program to
    manipulate the data, but I need to access the year, month and day respectively by themselves. I
    think that isolating the first 4 characters for the year, last 2 characters for da....
  3. Extplorer
    A PHP -and JavaScript- based File Manager (7)
    Browsing the ExtJS examples website i found this excellent web-based file manager called
    eXtplorer . eXtplorer allows you to browse your webserver folders with an intuitive Layout which
    makes working with files very easy, and thanks to the great ExtJS Javascript Library you can drag
    & drop folders and files, filter directories and sort the file list using various criteria. You can
    use eXtplorer to for example: browse directories & files on the server. edit, copy, move, delete
    files. search, upload and download files. create and extract archives. create new fil....
  4. Php - Browser Based Editor
    (3)
    I'm trying to set up some tools for a number of developers to use in the creation of a
    text-based MMORPG. I'd like to be able to show directory structure and allow them to easily see
    which files are where - then to be able to edit the pages from their browser. It would also be a
    neat feature that they could upload some files from their computer. Last time I needed this I built
    it myself, but it was restricted to 2 directories only and I ended up storing the file structure in
    text files. Anyways I'm debating rebuilding the entire thing but I can't help ....
  5. Authentication Script
    PHP Help #2 -- I need help tweaking it - it won't work (1)
    Okay, my first issue about the MySQL echo problem has been solved, thank you to those who helped.
    /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> Now I am focusing
    on the login portion of my site, and I have this so far: CODE // we must never forget to start
    the session session_start(); $errorMessage = ''; if (isset($_POST ) && isset($_POST ))
        {    $username = $_POST ;    $password = $_POST ; //Connect to database $con =
    mysql_connect("localhost","myDatabaseUsername","myDatabasePassword"); if (!$con)   {   die('Co....
  6. Should This Great Site Offer Imagemagick ?
    May be the admin of this site think over it. (3)
    Hi As we all know that this website is very good and offering good services. I just wanna know if
    other people also want ImageMagick to be installed on this server with free accounts... so please
    let me know and lets check if the Admin of this site can isntall it..... Fun....
  7. User Authentication Session Handling Problems
    Authorization server variables not staying across pages (14)
    This is quite a bit of problem I am facing, and I cannot point exactly where I am going wrong. I
    have been lurking around here at the Asta Host forums with regard to login and user authentication
    scripts and I have got as far as this: - Starting a session - Registering a session variable -
    Using the variable to check if the user is authenticated or not. - Authenticating the user through
    MySQL database - Logging of the user, by setting the session variable to un-authenticated I have
    been able to achive the following things too that I think is not related to this proble....
  8. Connecting Ms Access To Php Using Odbc
    (5)
    Dear Friends I have been trying to connect Ms Access using PHP for couples of days. Finally I have
    done it. It was dome using Open DataBase Connectivity, popularly known as ODBC (pronounced as
    separate letters). With an ODBC connection, you can connect to any database, on any computer in your
    network, as long as an ODBC connection is available. Here is how to create an ODBC connection to a
    MS Access Database: Open the Administrative Tools icon in your Control Panel. Double-click on the
    Data Sources (ODBC) icon inside. Choose the System DSN tab. Click on Add in the....
  9. Dynamic Site Design - Where Do I Start ?
    (7)
    I am new to php. I have some programing background in html, javascript, and c++ but have never done
    anything in php Can someone reccomend some good sites or books etc that can help someone who is
    completely new? My ultimate goal is to make a game like/similar to ponyisland.net....
  10. PHP: How Can I Create An Authentication System?
    (8)
    I'm making a financial site based on PHP/MySQL, there are two sections in that site, first
    one which is a free section have news, stocks calculator and chat. second section which is paid
    section has the same fetures plus a portfolio manager for each member, financial analysis also it
    has a game which is available to members only too. The Problem i face at the moment is i need to
    code a php/mysql authentication system so only paid members can access the pages which is in the
    second section, i tried to code it but never succeded, any help is so welcomed /smile.gif"....
  11. How Can I Make A PHP-based Web Gallery
    (4)
    how can i make a gallery in php like this one; but it has to show the images in the maps under it
    too; CODE    # Do we have a path? if not, it's the current directory    $path = $_GET ;
       if( !isset( $path ) || $path == "" )  {      $path = ".";    }    # Initialise list arrays,
    directories and files separately and array counters for them    $d_arr = array(); $d = 0;    $f_arr
    = array(); $f = 0;    # Open possibly available directory    if( is_dir( $path ) ) {      if(
    $handle = opendir( $path ) ) {          while( false !== ( $file = readdir( $handle ) )....
  12. Need Help Is Adding A PHP Based News Module To My Site
    (2)
    Hey guys i need a simple help i'm builing a homesite and i have a little spot for news. Well i
    just place there the Topics and add a link to another page "news.php". Well its obvious that i dont
    want to build a file for each news that i have so i know that exists a way to work with SQL & PHP. I
    will show want i'm doing CODE        require ('mysql.php');       
    $query="SELECT * FROM News ORDER BY `data` ASC LIMIT 0,5 ";        $result=mysql_query($query);
               $num=mysql_num_rows($result); mysql_close(); echo " Outras Other News "; $i=....
  13. Multilingual Site: Send The User To Page Of Choice
    (6)
    If you have one site in diferent laanguages, this simple script can redirect the user to the correct
    page acording to his/her language: CODE // Enslish EUA elseif ($HTTP_ACCEPT_LANGUAGE ==
    "en-us"){ header("Location: index_eng.html"); } // Inglês UK elseif ($HTTP_ACCEPT_LANGUAGE ==
    "en-gb"){ header("Location: ingles_enuk.html"); } // Portuguese if ($HTTP_ACCEPT_LANGUAGE ==
    "pt-br"){ header("Location: index_ptbr.html"); } //German elseif ($HTTP_ACCEPT_LANGUAGE ==
    "de-de"){ header("Location: index_ger.html"); } // Swedish elseif ($HTTP_ACCEPT....
  14. How To Do POP Access In PHP + Need AJAX Info
    (4)
    I'm writing a mail checker in PHP. I need to access the POP server. In PHP, I can send mail. But
    I didn't know how to receive mail yet. So, please help me. I also need some document about
    AJAX. This topic really interests me. But I don't know where to start.....
  15. How Do I Make PHP Based Image Gallery Like This?
    Help Needed (20)
    is it possible to make a page in php, with a url like this:
    httq://www.mysite.com/viewer.php?http://www.mysite.com/galleries/01 (This is a sample link, read
    below) so that in what i change the last part the gallery will change with it? so that i just have
    to make one php-page and this page just shows all the imaes in the map thats in the url after the
    questionmark?? thanks,....
  16. Using Bitflags To Restrict Site/page Permissions
    (1)
    My professor is designing a website that uses bit-flag checking to allow access to certain pages.
    You login, validate login, and store their allowed bit flag into a session variable. Then you
    compare to see if they have access or not. It's fairly new to me, but it's apparently very
    common with linux users. Sounds interesting to me, just wondering if any one has used this, or is
    it a little too much for simple pages. His site however is going to be more of "software" for
    several users. Is it very secure and does it work well?....
  17. Extremely Secure Authentication System
    (9)
    Today, I was thinking of experementing with Authentication tricks in PHP. I just came up with this
    thing. Firstly, Validating the username and password in the database. Once that is done, In order
    to track the user (the main place where most hackers get successful) We can set 2 cookies. 1>
    Member ID 2> MD5( REMOTE_IP and USER-AGENT and USERNAME and SALT ) Any hacker who tries to obtain
    session ID or even tries to setup a fake cookie with ID, will have to take additional pain to
    determine the IP address of the target. Not only that, he will have to even fake User-age....
  18. How To Use Cookie In Your Web Site ?
    this semple code to use and get cookie (1)
    what is the cookie ? the cookis it is some info sent and save in user computer whare i can use the
    cookies? becouse the cookies it like the header you can not send it after any output wes sent so
    you must send the cookies before any output like as ,echo and any other code i well make an E.X.
    to use the cookies you must have 2 file index.php update.php ---------- in the index.php add this
    code CODE    // This section must go at the top of the page that will display    // the
    users favorites.  These are the 'default' URLs that the user    // will se....
  19. Do You Want A Mail Form In Your Site
    (2)
    Repeat post. Credits reduced by 5 days. Learn to USE THE SEARCH BUTTON before you make such posts.
    did you want to have in your web site mail form that allow the user to send mails to anther mail
    from his mail e.g. the compose in yahoo CODE from to
    cc bcc subject
    function param($Name)         {         global $HTTP_POST_VARS;        
    if(isset($HTTP_POST_VARS ))            return($HTTP_POST_VARS );         return("");       ....
  20. Help: Trying To Create Web-based Compiler W/ Php
    (9)
    Hi guys, Need some serious scripting help. I'm trying to come up with a web-based compiler.
    here's how it's going to work. 1. The user is given a form with a large textarea to enter
    code (lets assume C++). 2. Upon submit the script takes the entire text from the textarea and writes
    it to a file. 3. Then it calls GCC the linux C compiler and passes this file as an arguement to it,
    as well as another arguement which is the name of the output file. 4. It then chmods the output file
    to make it executable. 5. Then it runs the output binary and pipes the console....
  21. Php Access Log In Reverse Order
    Request For Help. (8)
    So I need help getting data entered into my log correctly. I want the newest entry to be at the
    beginning (top) of the log instead of at the end (bottom). Here's what I have: CODE
    function access_log(){  // Enter data in usage log. $filename = "access.log"; $entry = gmdate("M
    d, Y H:i:s T").": ". getenv("REMOTE_ADDR").": ". getenv("HTTP_USER_AGENT")." \n";
    fwrite(fopen($filename, "a"), $entry); fclose(fopen($filename, "a")); }  //  End function
    access_log() ?> And it outputs: Mar 29, 2005 07:57:16 GMT Standard Time: 192.168.1.1:
    Mozilla/5.0 (Window....
  22. Own Links On Site
    (6)
    I'm thinking of having some kind of system so the users can register and then put up their
    links. Everything should be saved in some kind of database. Anyone now any tutorial or guide or
    something like that of how to do that?....
  23. Site Counters - Help Needed
    (13)
    I want a good Site counter(to keep track of visitors) for my site..... can nebody temme.....
    where will i get free stuff on this... (dont ask me to google..and try out..i am doing that..just in
    case u know someplace) OR Can how do i design my own (which seems quite....difficult for me) Plz
    help!! Satya....
  24. Php Script To Download File From Another Site
    (9)
    hi i need a php or java script code for downloading files from other sites to my site for example:
    http://download.com/file.zip to http://mysite.com/file.zip thanks....
  25. How Do U Make Members Only Web-site
    (7)
    how do u make it that only a member of that site can view that page?....

    1. Looking for php, based, site, access, authentication, block, parts, web, site






*SIMILAR VIDEOS*
Searching Video's for php, based, site, access, authentication, block, parts, web, site
advertisement




PHP Based Site Access Authentication - Help - How to block parts of your web-site ??