PHP - Noob Help Needed - Login Script
I need help with the attached script. I am using ipage.com to host and when I log in with credentials that have been placed in the database I just get the login prompt coming up every time. There is no die action that says access failed or anything.
Similar TutorialsIf you are a PHP expert, then I really your help. I have a question regarding PHP sessions and their security. So here is my story ... I created a login script (login.php) for my website. When a user goes to the login.php page, they see a login form that they must fill with their username and password to login to the members' area and view their profile, etc. On that login page, when the user enters their username and password and then clicks the "Login" button, my script filters the data, sends MySQL query and checks if the login is valid. If the login is NOT valid, then they get a "Login Failed" message. If the login is valid, I register their username and the password in sessions and redirect them to the members.php page. Here is some of my code for my login.php page after mysql confirms the login is valid <?php $query = mysql_query('SELECT * FROM `users` WHERE username='$user' AND password='$pass'"); $numRows = mysql_num_rows($query); if ( $numRows ) { // login is valid $_SESSION['username'] = $user; $_SESSION['pass'] = $pass; // redirect user to members area header('Location: /members.php'); } else { // login is invalid echo "Login failed"; } ?> My question is ... is this login script secured? I mean, I am not generating any session id or any cookie. I am just storing the username and the password in two session variables and those are the things that i will use to display the user's profile, etc. Can attackers attack this script? Is this secured or is there any other way I can make it stronger? Hello, im very green to php and I am having trouble creating a simple log in script. Not sure why this is not working, maybe a mysql_query mistake? I am not receiving any errors but nothing gets updated in the members table and my error message to the user displays. any help is appreciated! here is my php: <?php session_start(); $errorMsg = ''; $email = ''; $pass = ''; if (isset($_POST['email'])) { $email = ($_POST['email']); $pass = ($_POST['password']); $email = stripslashes($email); $pass = stripslashes($pass); $email = strip_tags($email); $pass = strip_tags($pass); if ((!$email) || (!$pass)) { $errorMsg = '<font color="#FF0000">Please fill in both fields</font>'; }else { include 'scripts/connect_db.php'; $email = mysql_real_escape_string ($email); $pass = md5($pass); $sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$pass'"); $log_check = mysql_num_rows($sql); if ($log_check > 0) { while($row = mysql_fetch_array($sql)) { $id = $row["id"]; $_SESSION['id']; $email = $row["email"]; $_SESSION['email']; $username = $row["username"]; $_session['username']; mysql_query("UPDATE members SET last_logged=now() WHERE id='$id' LIMIT 1"); }//Close while loop echo "You are logged in"; exit(); } else { $errorMsg = '<font color="#FF0000">Incorrect login data, please try again</font>'; } } } ?> and the form: <?php echo $errorMsg; ?> <form action="log_in.php" method="post"> Email:<br /> <input name="email" type="text" /><br /><br /> Password:<br /> <input name="password" type="password" /><br /><br /> <input name="myBtn" type="submit" value="Log In" /> </form> Hello guys, Is there on web any updated tutorial on how can I add Facebook login on my simple php login script? Hi I am new to php and I have a login form for users that works ok with a mysql database table for users. The problem I have is that it only takes all loggedin users to the same page and I want to take logged in users to their own page. I should have no more than 5 users at anyone time and for example I will call them simply user1, user2, user3, user4 and user 5. I want user1 to go to user1.php, user2 to go to user2.php and so on. The login.php code is as follows, can someone please tell me in laymans terms how to change it to accommodate this: Code: [Select] <?php include 'dbc.php'; $err = array(); foreach($_GET as $key => $value) { $get[$key] = filter($value); //get variables are filtered. } if ($_POST['doLogin']=='Login') { foreach($_POST as $key => $value) { $data[$key] = filter($value); // post variables are filtered } $user_email = $data['usr_email']; $pass = $data['pwd']; if (strpos($user_email,'@') === false) { $user_cond = "user_name='$user_email'"; } else { $user_cond = "user_email='$user_email'"; } $result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE $user_cond AND `banned` = '0' ") or die (mysql_error()); $num = mysql_num_rows($result); // Match row found with more than 1 results - the user is authenticated. if ( $num > 0 ) { list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result); if(!$approved) { //$msg = urlencode("Account not activated. Please check your email for activation code"); $err[] = "Account not activated. Please check your email for activation code"; //header("Location: login.php?msg=$msg"); //exit(); } //check against salt if ($pwd === PwdHash($pass,substr($pwd,0,9))) { if(empty($err)){ // this sets session and logs user in session_start(); session_regenerate_id (true); //prevent against session fixation attacks. // this sets variables in the session $_SESSION['user_id']= $id; $_SESSION['user_name'] = $full_name; $_SESSION['user_level'] = $user_level; $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']); //update the timestamp and key for cookie $stamp = time(); $ckey = GenKey(); mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error()); //set a cookie if(isset($_POST['remember'])){ setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/"); setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/"); } header("Location: myaccount.php"); } } else { //$msg = urlencode("Invalid Login. Please try again with correct user email and password. "); $err[] = "Invalid Login. Please try again with correct user email and password."; //header("Location: login.php?msg=$msg"); } } else { $err[] = "Error - Invalid login. No such user exists"; } } ?> <td> <button onclick="alertdialog()"><span class="glyphicon glyphicon-trash"> </span></button></td> <script> function alertdialog(){ window.confirm("Are you sure you want to delete this post?"); } </script> This is my code. I need to have a callback to a PHP script when a user decides to delete a post. I think html POST is the most unobtrustive way to do this. What's the easiest / most robust way to send data to a script when the user clicks OK? Appreciated. Mark Hi guys, I am making a bot which only scrapes the source code of the site AFTER logging into the site.The script to login is : Code: [Select] <?php $username="xxx"; $password="iwonttellyou"; $url="http://internet.com/login.php"; $cookie="cookie.txt"; $postdata = "name=".$username."&password=".$password; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt ($ch, CURLOPT_REFERER, $url); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec ($ch); echo $result; ?> I can see different SESSION ID's in cookie.txt everytime i compile this code, which makes me believe its working.However what next? How should i go to that site again, already logged in and scrape the data ? Some suggestions would be nice. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=318572.0 i have the following code in php: [PHP] <?php error_reporting (E_ALL); $host="localhost"; // Host name $username="elemental"; // username $password="rclogin"; // password $db_name="traffic2"; // Database name //$rc_profile_table="rc_profile_table"; // Table name //$rc_profile_relation_table="rc_profile_relation_table"; // Table name mysql_connect("$host", "$username", "$password"); mysql_select_db("$db_name"); $sql="SELECT created_at FROM rc_profile_table where created_at > 2011-04-19 08:00:00"; $result=mysql_query($sql); $count=mysql_num_rows($result); $sql="SELECT created_at FROM rc_profile_relation_table where created_at > 2011-04-19 08:00:00"; $result2=mysql_query($sql); $count2=mysql_num_rows($result); mysql_close(); ?> am i on the right path please? thank you I have a website with a membership script in PHP, on the registration page it asks questions such as name, address, business etc. and some of these fields need to be multip selections, there is also an account page where these fields can be changed as things change. I cannot get the multiple selections to save, they do not go to the database and are not there when you go to the account page. I am attaching my registration.php page the account.php page and the class_user.php is available if needed it wouldn't let me attach all 3
Attached Files
account.php 16.41KB
1 downloads
register.php 11.77KB
1 downloads Hello everyone, The last few weeks I've asked a few questions. From the answers given, I've finished my login script. But, I am a noob at oop php and I have also no clue if there are any security holes. So my question to you guys is: What have i done wrong? What can i do better? And what's missing? I also have a one basic question: I have't declared any variable to public, protected or private. Is it better to declare every variabe? or only a few? Here is my code: Index.php: <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { require('classes/class_lib.php'); if(isset($_POST['username'])){ $username = $_POST['username']; } if(isset($_POST['password'])){ $password = $_POST['password']; } try{ $user = new User; $user->login($username, $password); } catch(MysqlException $error){ echo $error->getError(); } catch(LoginException $error){ echo $error->getError(); } } ?> // form etc. And my class_lib.php: <?php class MysqlException extends Exception{ public function getError(){ $errorMessage = 'Er is een fout opgetreden in '.$this->getFile().' op regel '.$this->getLine().'<br />'; $errorMessage .= 'Foutmelding: <i>'.$this->getMessage().'</i><br />'; return $errorMessage; } } class LoginException extends Exception{ public function getError(){ $errorMessage = $this->getMessage(); return $errorMessage; } } class Mysql{ public function __construct(){ $this->db = new mysqli('localhost','root','','login'); if($this->db->connect_error){ throw new MysqlException('Kan geen verbinding maken.'); } } public function escapeString($string){ $this->string = $this->db->real_escape_string($string); return $string; } } class Query extends Mysql{ public function runQuery($query){ $this->result = $this->db->query($query); if(!$this->result){ throw new MysqlException('Er is iets fout gegaan tijdens het uitvoeren van de query.'); } } public function returnQuery(){ return $this->result->num_rows; if(!$this->result){ throw new MysqlException('Er is iets fout gegaan tijdens het ophalen van de resultaten.'); } } } class User{ public function __construct(){ $this->mysql = new Mysql; $this->query = new Query; } public function login($username, $password){ $this->username = $this->mysql->escapeString($username); $this->password = $this->mysql->escapeString($password); $this->setQuery = "SELECT gebruikerid FROM gebruikers WHERE gebruikersnaam='" . $this->username . "' AND wachtwoord='" . $this->password . "'"; $this->query->runQuery($this->setQuery); if($this->query->returnQuery() > 0){ return true; }else{ if(empty($username) || empty($password)){ throw new LoginException('U moet alle velden invullen.'); }else{ throw new LoginException('Uw logingegevens kloppen niet.'); } } } } ?> Hey everyone. I currently have a login script that uses cookies to check if the user is logged in. But I have been told that even if I have used md5() then the the password is still at risk, so I was wondering if using sessions would be better, or if there was some way to make the passwords in the cookies more secure? Here is the code I currently have to secure passwords in the cookie: Code: [Select] $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); } Hey so this is my login script but when i enter something into the username and password box and submit it, the page just refreshes.
<?php echo " <h1>LOGIN</h1> <form action='' method='POST'> <table> <tr> <td> <b>Username:</b> </td> <td> <input type='text' name='username' placeholder='Enter your username'> </td> </tr> <tr> <td> <b>Password:</b> </td> <td> <input type='password' name='password' placeholder='Enter your password'> </td> <td> <input type='submit' value='login' name='submit'> </td> </tr> </form> "; $host = "localhost"; $username = "root"; $password = ""; $db_name = "website"; mysql_connect("$host", "$username", "$password") or die("Could not connect"); mysql_select_db("$db_name") or die("Could not find database"); if(isset($_POST['submit'])) { if(!empty($_POST['username'])) { $sql = "SELECT * FROM members WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); if($count==1) { $row = mysql_fetch_array($sql); $bancheck = mysql_query($row); if($row['active']==0 && count==0) { include 'userban.html'; } else if($count==1 && $bancheck==1) { $_SESSION['username'] = "$username"; include '/home/user/index.php'; } else { echo "You entered invalid information"; } } } } ?> Hi I need help with my login script it says invalid password even when its correct however if i take out the md5 encryption of the password and use the encrypted password saved on mysql table it works please help? here is the code im using thanks: Code: [Select] <? // Use session variable on this page. This function must put on the top of page. session_start(); ////// Logout Section. Delete all session variable. session_destroy(); $message=""; ////// Login Section. $Login=$_POST['submit']; if($Login){ // If clicked on Login button. $username=$_POST['username']; $md5_password=md5($_POST['password']); // Encrypt password with md5() function. // Connect database. $host="localhost"; // Host name. $db_user="removed"; // MySQL username. $db_password="removed"; // MySQL password. $database="removed"; // Database name. mysql_connect($host,$db_user,$db_password); mysql_select_db($database); // Check matching of username and password. $result=mysql_query("select * from signup where username='$username' and password='$md5_password'"); if(mysql_num_rows($result)!='0'){ // If match. session_register("username"); // Craete session username. header("location:main.php"); // Re-direct to main.php exit; }else{ // If not match. $message="--- Incorrect Username or Password ---"; } } // End Login authorize check. ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title></title> </head> <body> </tr> <? echo $message; ?> <form name="register" method="post" action="<? echo $PHP_SELF; ?>"> <tr> <td height="586" colspan="8" align="center" valign="top"><p> </p> <table> <tr> <td height="45" colspan="2" class="class2 style34"><div align="center"><a href="file:///F|/signin.html">Sign In</a>:</div></td> </tr> <tr> <td colspan="2"><div align="right"></div></td> </tr> <tr> <td width="76" height="45"><div align="right"><span class="class2 style34">Username<span class="style39">..</span></span></div></td> <td width="256"><div align="center"><span class="class2 style34"> <input name="username" type="text" id="username" size="20" height="14" /> </span></div></td> </tr> <tr> <td height="45"><div align="right"><span class="class2 style34">Password <span class="style39">..</span></span></div></td> <td><div align="center"><span class="class2 style34"> <input name="password" type="password" id="password" size="20" height="14" /> </span></div></td> </tr> <tr> <td height="45" colspan="2"><div align="center"><span class="class2 style34"> <input name="submit" type="submit" id="submit" value="Sign In" /> </span></div></td> </tr> </table></td> </tr> </form> </table> </div> </body> </html> MOD EDIT: Database credentials removed, [code] . . . [/code] tags added. Hey, could someone help me with login script ? I've got registration script. It contains 3 files: reg.php <?php require_once 'database.php'; ?> <h1><strong>Register</strong></h1> <form name="register" method="post" action="regcheck.php"> <label> <input type="text" name="user" id="user"> Username<br /> </label> <br /> <label> <input type="password" name="pass" id="pass"> Password<br /> </label> <br /> <label> <input type="text" name="email" id="email"> Email<br /> </label> <label> <input type="submit" name="reg" id="reg" value="Register"> </label> </form> regcheck.php <?php $email = $_POST['email']; if( isset( $_POST['user'] ) && isset( $_POST['pass'] ) && isset( $_POST['email'] ) ) { if( strlen( $_POST['user'] ) < 4 ) { echo "Username is too short"; } elseif( strlen( $_POST['pass'] ) < 4 ) { echo "Password is too short"; } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Bad email address"; } elseif( $_POST['pass'] == $_POST['user'] ) { echo"Username and password can't be the same"; } else { include( 'database.php' ); $username = mysql_real_escape_string( $_POST['user'] ); $password = mysql_real_escape_string( $_POST['pass'] ); $email = mysql_real_escape_string( $_POST['email'] ); $sqlCheckForDuplicateN = "SELECT username FROM user WHERE username = '". $username ."'"; $sqlCheckForDuplicateE = "SELECT email FROM user WHERE email = '". $email ."'"; if( mysql_num_rows( mysql_query( $sqlCheckForDuplicateE ) ) == 0 && mysql_num_rows( mysql_query( $sqlCheckForDuplicateN ) ) == 0 ) { $sqlRegUser = "INSERT INTO user( username, password, email ) VALUES( '". $username ."', '". $password ."', '". $email ."' )"; if( !mysql_query( $sqlRegUser ) ) { echo "You Could Not Register Because Of An Unexpected Error."; } else { echo "You Are Registered And Can Now Login"; } } elseif( !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateE ) ) == 0)) { echo "The Email You Have Entered Is Already Being Used. Please Try Another One."; } elseif( !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateN ) ) == 0)) { echo "The Username You Have Entered Is Already Being Used. Please Try Another One."; } elseif( !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateE ) ) == 0) && !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateN ) ) == 0)) { echo "The Email and Username You Have Entered Is Already Being Used. Please Try Another One."; } } } else { echo "You Could Not Be Registered Because Of Missing Data."; } ?> database.php <? $con = mysql_connect('host','username','password'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db('dbname'); ?> So could someone help me with login ??? hi guys, any help will be much appreciated!! basically i have a login script, that i want to check mutliple tables and i am stuggling to get it to work! what i have is basically: <?php session_start(); $_SESSION['loggedin'] = false; include("functions.php"); extract($_POST); $query = "SELECT * From table1 WHERE email='$email' and password='$password';"; $result = doQuery($query); if($result==false) { $query = "SELECT * From table2 WHERE email='$email' and password='$password';"; $result = doQuery($query); if($result==false) { $query = "SELECT * From table3 WHERE email='$email' and password='$password';"; $result = doQuery($query); if($result==false) { $query = "SELECT * From table4 WHERE email='$email' and password='$password';"; $result = doQuery($query); if($result==false) { } else { if(mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); $_SESSION['loggedin'] = true; $_SESSION['id'] = $_POST['id']; header("Location:1"); } else { header("Location:wrong.php"); } } } else { if(mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); $_SESSION['loggedin'] = true; $_SESSION['id'] = $_POST['id']; header("Location:2"); } else { header("Location:wrong.php"); } } } else { if(mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); $_SESSION['loggedin'] = true; $_SESSION['id'] = $_POST['id']; header("Location:3"); } else { header("Location:wrong.php"); } } } else { if(mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); $_SESSION['loggedin'] = true; $_SESSION['id'] = $_POST['id']; header("Location:4"); } else { header("Location:wrong.php"); } } ?> I am looking to use this for an admin panel.
session_start.php
"session_start()" "if statement" where it checks if a successful login is givenIs it necessary to include "session_start.php" into the top of each script file? If I just include "session_start.php" into the top of the "main" file where the other script files are included inside of the "main" as well, then I have it in ways where the other script files could get called up through the URL.(?) I thought it is a bit too much to include "session_start.php" into each script file. Is there a way where this can be done with more simple ways? I would appreciate the suggestions a lot. Hey ppl I have a login script that I found in a PHP MySQL book. And yesterday I realized that it is easy to hack this script as it use session variables and it can use cookies. DOes anyone have login script for me that is secure and easy to implement? It would really help! Thanks Quote from: scootstah on November 30, 2011, 01:19:13 PM Code: [Select] function hash_password($password, $salt = null) { // create a salt if not already defined if (is_null($salt)) $salt = substr(sha1(uniqid(mt_rand(), true), 0, 10); // $password will be plaintext at this point // $site_key should be a large random string statically // located in a file with secure permissions $hash = hash_hmac('sha512', $password . $salt, $site_key); return array('hash' => $hash, 'salt' => $salt); } $password = 'abcdef'; $pass = hash_password($password); First off I just want to say thank you for the valuable information I have been reading in this topic (for a few days) and I have updated my pages accordingly. My passwords are now salted with a random encrypted string and I am using sha1 but would like to switch to sha512. So I am playing around with some code to learn more about how it works and have noticed that: sha1(test) returns a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 but sha512(test) just crashes the page. Can anyone help me understand why this is? Hello everybody! I am trying to make a forum for my class and I will do it from scratch I am from Denmark so my english could be a little wrong! Sorry! The problem is when i try to login, I allways get the error that I had defined to do.. But only if both password and username dosn't exist... Before i post the code i will give you a translation: Brugernavn = Username kodeord = password brugerid = userid My register.php file works fine! But I will post them both: This is the register form: http://pastebin.com/h6fgHSFB And here are the code for my login.php, the strange thing is, that i do not get any kind of error dont even mysql errors, that i had hope on so i could fix it! http://pastebin.com/Vc8Gt9SY Hope you guys would like to help me! Best Regards Jesper Jensen from denmark jesper@dh-data.dk Hi, I am trying to make a login script that uses the user's id from the database, and tries to match it up with the user and password sent by the login form. My checklogin.php page, just jumps back to the index.php page for some reason. I don't know why. I get the following errors, any help greatly appreciated. thank you. Notice: Undefined index: myusername in /hermes/bosweb/web173/b1739/public_htmlchecklogin.php on line 19 Notice: Undefined index: mypassword in /hermes/bosweb/web173/b1739/public_html/checklogin.php on line 20 Wrong Username or Password Here is my code to check the id. I can't figure out what is wrong. Code: [Select] <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); $host = ""; $database = ""; $username = ""; $password = ""; $tbl_name = "users"; $conn = mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error()); if($conn) { mysql_select_db($database); } else { echo "failed to select database"; } // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT id FROM $tbl_name WHERE username='$myusername' and password= SHA1('$mypassword')"; $result=mysql_query($sql); $query_data = mysql_fetch_row($result); // Mysql_num_row is counting table row $count=mysql_num_rows($result) ; // If result matched id, table row must be 1 row if($count==1){ session_start(); $_SESSION['userid']=$query_data[0]; header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> |