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
Related
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'];
I'm trying to create simple login/registration page.
I'm using index.php which includes login.php in it.
I want to report the login errors in a specific position, using an answer to a preious question.
The problem is that if I encounter an error, the url changes to the login.php file and on next login I get error of "Cannot find page".
I want to eventually be able somehow display errors and be able to get another input and handle it.
login.php:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="kupon"; // 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
$email=$_POST['email'];
$password=$_POST['password'];
// To protect MySQL injection
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE email='$email' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $email and $password, table row must be 1 row
if($count==1){
// Register $email, $password
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header("location: members.php");
}
else {
$error = '<p class="error">User does not exist</p>'
include('../index.php');
exit;
}
?>
index.php form:
<form action="php/login.php" method="post" class="form">
<p class="email">
<input type="text" name="email" /> :דואר אלקטרוני</br>
</p>
<p class="password">
<input type="password" name="password" /> :סיסמא</br>
</p>
<p class="submit">
<input type="submit" value="היכנס" />
</p>
</form>
<?php
if(isset($error)) echo $error;
?>
You shouldn't put passwords or other Personal Identification Information into the session. Better to have your login code assign a session ID with an identification that links it to the user in your database. (Like a column filled with unique values called userid)
You need to make sure you are initializing the session in the login.php and any page that you want to have require they be authenticated. This allows you to have the page check the session to confirm that the user is actually logged in.
To resolve the 404 error (Page Not Found), you need to fix this: header("location: members.php");. That needs to be the full path of the file. Since your login.php file is under the directory of php and members.php is not, when you get directed to login.php, this location forward tries to load members.php in the php directory and since it is not there, it gives a 404 error.
You are including the login.php, but the actual page is index.php - so you should post your form to index.php instead.
It looks like you have a problem using relative urls.
You start on index.php, which redirects on form submission to php/login.php.
Next time, you submit to php/php/login.php instead.
If you're in the document root, try using /index.php and /php/login.php instead. I can't be more specific without knowing more about your project's layout however.
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.
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);
I am trying to create a simple login system. When I run the login form (with the correct username and password) it doesn't seem to run the php. Any suggestions?
<?php
$host="linuxserver"; // Host name
$username="jparry2"; // Mysql username
$password=""; // Mysql password
$db_name="jparry2"; // Database name
$tbl_name="customer"; // Table name
// Connect to server and select databse.
mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_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
$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=mysqli_query($sql);
// Mysql_num_row is counting table row
$count=mysqli_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:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
<html>
<body>
</body>
</html>
edit added login form code
<html>
<head><title>Login</title></head>
<body>
<form action='checklogin.php'
method='POST' style='margin: .5in'>
<p><label for='user_name' style='font-weight: bold;
padding-bottom: 1em'>USER ID: </label>
<input type='text' name='myusername' id='myusername'
value='' /></p>
<p><label for='password' style= 'font-weight: bold'>Password: </label>
<input type='password' name='mypassword' id='mypassword'
value='' /></p>
<p><input type='submit' value='Login'> </p>
<input type='hidden' name='sent' value='yes'/>
Register
</form>
</body>
</html>
If your browser asks you to download the php file it means the php interpreter is not being invoked. i.e. you don't have it installed or configured correctly.
Are you getting any error message? Seems ok to me. Have you tried echoing something in the if-block for example? That might help you understand what's wrong.
Some things you could check or try:
Have you got error reporting on?
Put `var_dump($_POST); die(); on the top of the page to see if the $_POST variables are submitted correctly.
Make sure you are not outputting anything to the browser before the header() function. If you have error_reporting off and you outputted something to the browser, using header() will result in a fatal error which could cause a blank white page.
A few other notes from your code:
You don't need to put variables inside double quotes, they work on their own: mysqli_select_db("$db_name") becomes mysqli_select_db($db_name)
You don't need to stripslashes() if you're doing mysql_real_escape_string. The latter will handle the job on its own.
In some browsers, the Location header is case-sensitive, and thus your header("location:login_success.php"); call might not be working (a comment on the header documentation page suggests that this occurs in IE7). Try capitalizing the l in Location.
You don't do any "session_start()", so your session can't be used.
Maybe you need it to started in your "login_success.php" script.
I agree with Daniel, by revising header("Location: login_success.php");
Also, as a side note since at the time of writing this, it wasn't clearly explained what didn't work, but you when adding session variables you need to have session_start().
Also try to use $_SESSION['variable'] since session_register() is deprecated as of PHP 5.30 taken from PHP: session_register try something like this
if($count==1){
session_start();
// Register $myusername, $mypassword and redirect to file “login_success.php”
$_SESSION['username'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
session_write_close(); // makes sure nothing was lost during redirect
header('Location: nextpage.php');
}