Code not working. PHP / HTML - php

I am trying to get a form to submit and check a login but it's not going from A to B, can anyone see any problems with the code please?
Here is to Form part:
<form action="check_login.php" name="form1" method="post">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider" role="heading" tabindex="0">Member login</li>
<li><input type="text" name="myusername" id="myusername" value="Email" /></li>
<li><input type="password" name="mypassword" id="mypassword" value="Password" /></li>
<li><button type="submit" name="login-submit" id="login-submit" data-icon="arrow-r" data-iconpos="right">LOG ON</button></li>
</ul>
</form>
And here is part 2 (checks the login ... doesn't seem to get here.
<?php
$host="localhost"; // Host name
$username="usernamehere"; // Mysql username
$password="passwordhere"; // Mysql password
$db_name="dbnamehere"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or
die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// 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 * FROM $tbl_name WHERE username='$myusername' and
password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
session_register("myusername");
session_register("mypassword");
//header("location:login_success.php");
echo 'login success';
}
else {
echo "Wrong Username or Password";
}
?>
For more information on the login part of the code, please look here:
http://devlup.com/programming/php/toa-simple-php-login-form-mysql/200/
Any questions, please ask.
Thanks.

Final Update
For future visitors, I assume this is the answer that eventually solved the problem:
Relative paths, like the one used in the form action, always start looking in the current directory.
In the original question, the form was submitting to action="check_login.php" This means that the browser will submit the data to http://www.domain.tl/wherever/theform/was/check_login.php.
If you need to submit forms to other locations, you need to either specify absolute paths (http://www.domain.tl/handler.php) or you need to understand directory traversal, and indicate the correct path (../../handler.php).
Update
What is your file structure? Is the form html in the same place as the handler php?
To be clear it should be /{parent}/form.html and /{parent}/check_login.php. Is that the case?
You said you are not getting any data in $_POST. Does this mean it is getting TO check_login.php but not working, or not getting to it at all?
Original
I'll update this with an answer to your real question after we get more info about what is happening here, but I wanted to post this so you would make sure to see it.
It seems like you have a few poor coding practices and, while I'm certainly not a pro, I feel like I can offer some improvements. See the revised code block below.
<?php
$host="localhost"; // Host name
$username="usernamehere"; // Mysql username
$password="passwordhere"; // Mysql password
$db_name="dbnamehere"; // Database name
$tbl_name="members"; // Table name
//Ideally, your database information is stored in another file, and you include it here.
//Mostly, it's just so you're not having to change it in multiple places if it changes
//but there could be a small security benefit, too
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or
die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
//What if the $_POST vars don't exist?
//$myusername=$_POST['myusername'];
//$mypassword=$_POST['mypassword'];
//Try:
$myusername = isset($_POST['myusername']) ? $_POST['myusername'] : null;
$mypassword= isset($_POST['mypassword']) ? $_POST['mypassword'] : null;
//then you should check if the variables exist
if( $myusername == null || $myusername == "" || $mypassword == null || $mypassword == "" )
{
echo "You need to fill in both fields.";
}
// To protect MySQL injection (more detail about MySQL injection)
//why are you forcing php to write to that variable twice?
//$myusername = stripslashes($myusername);
//$mypassword = stripslashes($mypassword);
//$myusername = mysql_real_escape_string($myusername);
//$mypassword = mysql_real_escape_string($mypassword);
//Try:
$myusername = mysql_real_escape_string(stripslashes($myusername));
$mypassword = mysql_real_escape_string(stripslashes($mypassword));
//As another person said, you desperately need to store hashed passwords
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
//This is a terrible idea.
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
//from #Jimmy Sawczuk
//This is deprecated, since a while ago.
//session_register("myusername");
//session_register("mypassword");
//Try:
$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
//header("location:login_success.php");
echo 'login success';
}
else {
echo "Wrong Username or Password";
}
?>
In the $_SESSION edit right at the end there, the larger question is: why are you saving those variables. If you're needing the password in the Session at a later time, you're doing your app security wrong.

Not sure if this is related but the button element causes problems in IE:
http://www.sitepoint.com/forums/html-xhtml-52/button-submit-input-submit-better-598656.html
Also, try
print_r($_POST);
before you do anything else to see if you're getting anything.

Related

php not redirecting to my login_success.php page

Trying to make a login page using php following a tutorial, it's successfully logging in getting both the password and username from the database then showing echo "wrong password" and welcome for each scenario. However it doesnt redirect to my login_success.php page stays on check_login.php, heres my code for the check page:
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="test";
$tbl_name="members";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count > 0){
echo "Welcome";
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
any help would be great.
You cannot send anything to the client (i.e. echo "Welcome";) before setting your headers.
Reference http://www.php.net/manual/en/function.header.php
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
Nor can you send anything to the client before starting sessions.

Session User ID?

I have adpopted some code to create a login, checklogin, successful login, failed login and logout pages. The checklogin page essentially checks the username and password posted from login. If these are correct you end up at successful login page. However I want to say something like 'Welcome John' on the successful login page, but dont know how to get the username from the session so that I can base a query on this to pull back the logged in persons name. The checklogin page is:
<?php require_once('Connections/Connection1.php'); ?>
<?php
//$host="localhost"; // Host name
//$username=""; // Mysql username
//$password=""; // Mysql password
//$db_name=""; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
//mysql_connect("$host", "$username", "$password")or die("cannot connect");
//mysql_select_db("$db_name")or die("cannot select DB");
mysql_select_db($database_Connection1, $Connection1);
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=md5($_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 * FROM $tbl_name WHERE userid='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:main.php");
}
else {
header("location:login_failed.php");
//echo "Wrong Username or Password";
}
?>
Then on my successful login page, how do I echo the username? or at least refer to it in a query to then pull back the additional information like name?
Many thanks!!
When I need to do this, I usually use php's $_SESSION array and set quick look up information in there, such as a name that might be displayed on multiple pages.
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $firstname;
$_SESSION['lastname'] = $lastname;
$_SESSION['user_id'] = $id;
This gives me access to all these variables on any page that calls session_start() at the start of the php page.
On a sidenote -
using MD5 hashing passwords IS NOT SECURE! Learn how to use crypt() function with salts. It will be good practice and make your database much more secure. Unfortunately MD5 is not much more secure than plaintext at this point with people having easy access to rainbow tables and programs like ocl-hashcat.
Please look into using PDO or mysqli for your database calls. mysql_ functions are deprecated.
Changed the code a bit, this is safer..
<?php
session_start();
// Sanitize $_POST['myusername'] and $_POST['mypassword'] before loading into session variables to protect from MySQL injection
$_SESSION["myusername"]=!empty($_POST['myusername'])?mysql_real_escape_string(stripslashes($_POST['myusername'])):"";
$_SESSION["mypassword"]=!empty($_POST['mypassword'])?mysql_real_escape_string(stripslashes($_POST['mypassword'])):"";
// Load database variables, connect to server and select a database
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
mysql_connect($host, $username, $password)or die("Cannot Connect for Reason:".mysql_error());
mysql_select_db("$db_name")or die("Cannot Select DB for Reason:".mysql_error());
// Run query
$result=mysql_query("SELECT username FROM $tbl_name WHERE username='".$_SESSION["myusername"]."' AND password='".$_SESSION["mypassword"]."'");
// Check for return of single record and direct to login_success.php
if(mysql_num_rows($result)==1){header("location:login_success.php");}
else{
// On login falier, unset session variables if not needed and redirect
unset($_SESSION["myusername"]); // Optional if return value not needed or wanted
unset($_SESSION["mypassword"]); // Optional if return value not needed or wanted
header('refresh: 5; url=./login_fail.php');
die("Wrong Username or Password. Redirecting..."); // To prevent evil people manipulating the page, kill the script using die.
}
?>
To echo the user on another page: echo $_SESSION['myusername'];
You have two options...
Either you can retrieve it on main.php page as $_SESSION['myusername'];
Or, you can use pass it to main.php as header("location:main.php?username=".$myusername);
And then on main.php, you can retrieve it as $_GET['username'];

Login Form with Remember Me function AND unauthorized site access to login_success.php URL PHP

I'm having a little trouble implementing a login system that both allows users to be rememebered via cookie but at the same time not allow unauthorized access using site URL
here is my code for successful_login, the problem lies here as I get a redirect error:
<?php
session_start();
// IF USER NOT REMEMBERED OR NO SESSION THEN THROW HIM OUT TO LOGIN
if (!isset($_SESSION['valid'])|| !isset($_COOKIE['myusername']))
{
header("Location: index.php");
}
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="*****"; // Mysql password
$db_name="secure_login"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE username='$myusername'";
$result=mysql_query($sql);
?>
the session works but as soon as I close the browser and reopen it to my site I get a REDIRECT LOOP
here is the code that processes my form:
<?php
session_start();
//CHECK IF EITHER SESSION OR COOKIE EXISTS THEN REDIRECT TO LOGIN_SUCCESS ELSE CONTINUE TO FORM
function loggedin()
{
if (isset($SESSION['valid']) || isset($_COOKIE['myusername']))
{
$loggedin = TRUE;
return $loggedin;
}
}
if (loggedin())
{
header("Location: login_success.php");
}
// REST OF CODE IS PROCESSED AFTER USER CLICKS SUBMIT ON LOGIN FORM
if(isset($_POST['submit']))
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="*****"; // Mysql password
$db_name="secure_login"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$rememberme=$_POST['rememberme'];
// 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);
$encrypted_mypassword=md5($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
if(mysql_num_rows($result) == 1) //user exists
{
if ($rememberme=="on"){
setcookie("myusername", $myusername, time()+7200);
}
elseif ($rememberme==""){
$_SESSION['valid'] = 1;
}
header('Location: login_success.php');
exit();
}
if($myusername=="phillip.k#fixnode.ca" && $encrypted_mypassword=="a66d83940f5d22fa54ee51ce"){
header('Location: register.php');
}
else {
echo '<div class="alert">Incorrect Username or Password!</div>';
}
}
?>
so basically to wrap up, when a user enters a valid username and password AND clicks remember me then I like for the browser to redirect to login_success even if the user closes the browser (i.e. COOKIE from remember me button). But right now if a user closes a browser and reopens my site then the user gets a REDIRECT LOOP probably because of the cookie
ANY help is greatly appreciated
Phillip K
The problem is here:
if (!isset($_SESSION['valid'])|| !isset($_COOKIE['myusername']))
Instead of ||, you should have &&. You never have them both set in the same time, hence the redirection loop.
Another problem I found quickly is you never seem to update the cookie "myusername" when user visits the page.
As suggested, you could use an existing solution but if you really want to do it yourself I would highly suggest splitting that code into reusable functions/classes.
Md5 is not a safe way to store user passwords, you should use bcrypt or similar existing solution.
I would also confirm the IP between each page visit as a countermeasure against session hijacking (this would require storing the session data on a database which is a good idea anyway).
I would recommend a ready-to-use authentication solution.
For example http://pear.php.net/package/Auth. Have a look into the examples

PHP login problem

I have the following code. Now when I press the login button nothing happens and the username and password are cleared.
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="csduc"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select databse.
$connect=mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection).
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql,$connect);
$row=mysql_fetch_array($result);
// Mysql_num_row is counting table row.
//$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row.
if($row)
{
// Register $myusername, $mypassword and redirect to file "login_success.php".
session_register("myusername");
session_register("mypassword");
header("location: main.php");
}
else
{
echo "Wrong Username or Password";
}
?>
How can I solve this?
The correct name for the header is "Location" (with a capital 'L'). This may or may not matter. Also, technically, the Location header requires an absolute URL (eg. "http://example.com/main.php") -- some browsers will accept a relative url, but the spec requires the absolute url. Again, this may or may not be causing your problem.
So, to be more "technically correct" your redirect could be changed to something like this:
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/');
header("Location: http://$host$uri/main.php");
check out the php documentation page for the header() function for more details.
Your form tag has a problem.
It needs to be as follows:
<form method="POST" action="">
Assuming action is the same page as the code above. Otherwise point the action to the page that has the code in it. Make sure the code is at the very top of the page, otherwise session start and header won't work
For testing use
echo $myusername=$_POST['username'];
echo $mypassword=$_POST['password'];
exit;
and use sql as because password may be encoded
$sql="SELECT * FROM $tbl_name WHERE username='$myusername'";
$result=mysql_query($sql,$connect);
$row=mysql_fetch_array($result);

deny http access to the directory, but allow internal server access

First off I want to start off saying that I don't know anything about PHP so I would appreciate all the help I can get.
So I have a website hosted on godaddy where I upload files for my clients. With the help of a friend I made a simple login system with usernames and passwords. The problem is that although the websites can't be accessed without inputting the username and password, the files suchs as .jpg can be accessed by directly inputting the full link in the browser. I want it to be so that the only way the files are accessed through the user webpage. Also I want each user to be able to access only their own files and not the others. So here is my code and if there are any additional changes that need to be made to avoid hacking I will greatly appreciate the input.
index.php file code for the form that is being used to input username and password:
<form name="form1" method="post" action="checklogin.php">
<div class="lefts">
<p>Login:</p>
<p>Password:</p>
</div>
<div>
<input name="myusername" type="text" id="myusername" />
<input name="mypassword" type="password" id="mypassword" />
</div>
<div><input type="image" name="Submit" id="submit" value="Login" src="images/submitOff.png" /></div>
</form>
checklogin.php: (if correct username and password is entered, it goes to the username webpage. if not it goes to the wrong username or password webpage
<?php
ob_start();
session_start();
$host="hostname"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbnamey"; // Database name
$tbl_name="tablename"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$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 username FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
//returns false if no results returned
$row = mysql_fetch_row($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($row){
// Register $myusername, $mypassword and redirect to file
$_SESSION["myusername"] = $myusername;
$_SESSION["mypassword"] = $mypassword;
$myPage = $myusername.".php";
$_SESSION["myPage"] = $myPage;
header("location:".$myPage);
}
else {
header("location:index2.php");
}
ob_end_flush();
?>
username1.php: (webapge for user that contains files)
<?
session_start();
if(
//!session_is_registered(myusername)
!isset($_SESSION["myusername"]) ||
$_SESSION["myPage"] != basename($_SERVER['REQUEST_URI'])
){
header("location:index.php");
}
?>
<html>
//content that consist of links to the files
Png 1
</html>
The security of this script is very bad. You aren't hashing passwords. The header() allows you to add an element to the HTTP response header. THE SCRIPT STILL EXECUTES., you are not preventing access to anything. Furhter more, mysql_real_escape_string() does everything that addslashes() does and more. Doing both just tells people that you don't know what either of them does. You must start using parametrized quires with ADODB or the PDO libraries.
Use an .htaccess file to prevent accesss
Order deny, allow
Deny from all
Allow from localhost

Categories