Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Roy Jossfolk Jr.
3,981 PointsPHP and authentication
Hey everyone!
I have created an enterprise iPad application to distribute to select users. I did not want to use an Ad-Hoc build as I may exceed the 100 user limit at some point.
I currently set up a webpage that uses .htaccess and .htpasswd to enter the page with a login and password. It works great but I want to make this page only accessible one time by a user/pass combination. This way they can not pass the link, username and password along to others for them to download. They would have to contact me for a brand new user/pass combo.
Does anyone have any ideas? I was researching and saw .PHP may help me but I do not know a lot about .php. Is there any resource out there I can use to learn this specific thing I need or maybe a code snippet somewhere? Thanks in advance!
15 Answers
Mike Gabriel
8,402 PointsAn .htaccess file will not allow you to do this.
What you would need is to use a combination of a server side language and a database. PHP / MySQL, Rails / MySQL, etc.
A rough idea of the workflow would be you create a database with a username and a password column inside users table. Your PHP/Ruby script would validate from the database, create an active session and then destroy the username/password from the database so they would not be able to authenticate again.
Alternatively to destroy, you could add a third column - active - that changes from True to False after the first login, this way if a user emails you requesting their account to be reactivated, you just need to edit this column for their username.
PHP is the creature you desire, I'm sure the lessons on Treehouse will be able to get you started in the right direction.
Roy Jossfolk Jr.
3,981 PointsThanks Mike!
I actually found a script that does just what you are saying and I created the database and all. Unfortunately I have not been able to get it to work yet. I just don't know enough in order to be able to edit the code.
I will make my way over to the php lessons on the website and hopefully it will help me with understanding what I am doing wrong. I keep getting a 404 whenever I put in the username and password and click send.
Roy Jossfolk Jr.
3,981 PointsWell I went through every video of the building a simple php application today and even though I learned a ton I still am unable to figure out to get this working. Basically when I type in the username and password I created on the database it takes me to a page that says:
*The requested URL /salesgame/< was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.*
any ideas? I feel like this is something very simple that I am missing but I just don't understand the code line for line so I am having trouble fixing this.
Mind if I share the code?
script.js
<?php require_once('/salesgame/rsLogin.php');?> <?php // *** Validate request to login to this site. session_start();
$loginFormAction = $_SERVER['PHP_SELF']; if (isset($accesscheck)) { $GLOBALS['PrevUrl'] = $accesscheck; session_register('PrevUrl'); }
if (isset($_POST['username'])) { $loginUsername=$_POST['username']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "salesgame/test.html"; $MM_redirectLoginFailed = "http://www.google.com"; $MM_redirecttoReferrer = false; mysql_select_db($database_rsLogin.php, $rsLogin.php);
$LoginRS__query=sprintf("SELECT username, password FROM login WHERE username='%s' AND password='%s'", get_magic_quotes_gpc()? $loginUsername : addslashes($loginUsername), get_magic_quotes_gpc()? $password : addslashes($password));
$LoginRS = mysql_query($LoginRS__query, $rsLogin.php) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = "";
$RemoveRS__query=sprintf("DELETE FROM login WHERE username='%s' AND password='%s' LIMIT 1", get_magic_quotes_gpc()? $loginUsername : addslashes($loginUsername), get_magic_quotes_gpc()? $password : addslashes($password));
mysql_query($RemoveRS__query, $rsLogin.php) or die(mysql_error());
//declare two session variables and assign them $GLOBALS['MM_Username'] = $loginUsername; $GLOBALS['MM_UserGroup'] = $loginStrGroup;
//register the session variables session_register("MM_Username"); session_register("MM_UserGroup");
if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } ?>
rsLogin.php
<?php
$host="my_host"; $username="my_username"; $password="my_password"; $db_name="my_dbname";
mysql_connect("$host", "$username", "$password")or die("cannot connect to server"); mysql_select_db("$db_name")or die("cannot select db");
?>
login.html
<!DOCTYPE html> <html lang="en"> <head> <title>Download Sales Game for Parisi Speed School</title>
<script type="text/javascript" src="salesgame/script.js"></script> </head>
<body>
<form action="<?php echo $loginFormAction;?>" method="POST" name="login" id="login"> <p>username <input name="username" type="text" id="username"> </p> <p>password <input name="password" type="text" id="password"> </p> <p> <input type="submit" name="Submit" value="Submit"> </p> </form>
</body>
</html>
Roy Jossfolk Jr.
3,981 Pointsdeleted
Roy Jossfolk Jr.
3,981 PointsSorry it looks so bad I do not know how to use the markdown short codes
Mike Gabriel
8,402 PointsI cannot validate if the script you found actually works in the first place, it looks a little weird - script.js which is a javascript file with a bunch of php code inside of it isn't going to parse properly.
But, the 404 means the action property on the form is posting to a location that doesn't exist on your web server.
An example of a 2 page, one that shows the login form, login.php, and one that handles the users submitted information, authenticate.php, would look something along these lines.
login.php
<form action="authenticate.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
authenticate.php
<?php
if (isSet($_POST['submit']) }
// Connect to MySQL Database, query by $_POST['username']
// and $_POST['password'], if they match, start a session
}
?>
Obviously the PHP isn't all there but that's the basics to it.
Roy Jossfolk Jr.
3,981 PointsAlright well I guess that is what I get for trying to use something I found online. At least I know that what I am trying to do is possible, that I am happy about.
To be honest I started on this at 8am and it is now 1am so I am not sure why I used script.js I think that is what I saw that went along with the code I found.
I do not think there is any lessons on this site that teach what I need to know. Do you know of any good tutorials that cover this? I will be needing to maintain this for the rest of the year and maybe beyond and need to know what I am doing.
I changed the login.html to login.php and I no longer get a 404, it just takes me back to login.php again. So maybe I am getting somewhere!
my form action="<?php echo $loginFormAction;?>"
and
$loginFormAction = $_SERVER['PHP_SELF'];
So i know it will show whatever $_SERVER['PHP_SELF']; is which I assume is login.php ? How do I get it to show test.html ?
as I have it in
$MM_redirectLoginSuccess = "salesgame/test.html";
Mike Gabriel
8,402 PointsScrapping everything you had, this will do the basics. Untested but I don't think I made any typos.
login.php
<form action="authenticate.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
authenticate.php
<?php
if (isSet($_POST['submit'])) {
// connect to MySQL Database
$db = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die("Cannot connect to server";
mysql_select_db("database_name", $db)or die("Cannot select database");
// query by $_POST['username'] and $_POST['password']
$result = mysql_query("SELECT * FROM table_name WHERE `username`='$_POST[username]' AND `password`='$_POST[password]'");
// no results are found, display an error
if (mysql_num_rows($result) == 0)
{
echo "No matching username or password found.";
}
else
{
// result was found in database
while ($row = mysql_fetch_array($result))
{
// username and password match found
// display the data you want viewable to the user within these braces
// at the end, do another mysql_query to destroy or inactivate the username
}
}
}
?>
Obviously you'll have to fill in the data you want to feed to the user inside the while loop, as well as change the mysql_connect commands mysql_user, mysql_password and database_name to match your setup. Also the table_name.
Roy Jossfolk Jr.
3,981 PointsTrying this now.
Thanks a lot, I did not expect so much help. Much appreciated.
Roy Jossfolk Jr.
3,981 PointsBeen playing around with this and I am getting an error:
Parse error: syntax error, unexpected '{' in /home/content/27/7291127/html/salesgame/salesgame/authenticate.php on line 2
I searched around and it seems this is caused by two things. 1) there is a mispelled word, ";""," or "{" where it is not supposed to be 2) has to do with my version of php. I did a phpinfo( ) and it looks like i am running the latest version of php.
any ideas? Sorry for all the questions
Mike Gabriel
8,402 PointsMy bad in the typo,
Line 2 as the error says.
{ instead of } at the end
Roy Jossfolk Jr.
3,981 PointsMan, hate to say this but it is still showing an error
Parse error: syntax error, unexpected '{' in /home/content/27/7291127/html/salesgame/salesgame/authenticate.php on line 2
Not sure what is up.
I'd really like to find out if there are any good documentation out there going over the various scripts for authentication and also performing the one-time access like I am looking for.
Even though the code you gave me will work as a way to get to the download I still want to be able to lock users out after one login and I feel writing the rest of that code may prove to be even more difficult then what I am going through now. I keep searching one time login with php on google but not really getting what I am looking for. Do you know how to explain what I am trying to do in better terms so i can go on a better search?
I really appreciate your help!
Mike Gabriel
8,402 PointsSorry Roy,
That's the problem with typing out this stuff at the early hours in the morning.
if (isSet($_POST['submit'])) {
I don't know of any scripts or a better way to search for what you are looking to accomplish.
Roy Jossfolk Jr.
3,981 PointsThanks Mike. With that fix and a few others it seems to be working. Was not able to get to the link to download the app but I do know the authentication is working as it is taking me a to blank page.
I will be looking around for the next few hours to see if I cant find what I am looking for.
I appreciate all the time you spent! Thank you.
Roy Jossfolk Jr.
3,981 PointsIf anyone else is looking at this, I found the script here at this link.
http://www.kirupa.com/forum/showthread.php?282105-php-amp-SQL-one-time-access