I am trying to use a php script to only show a link, when a "user" in a MySQL table is "logged in". What is wrong with the php code which I have tried? Mine is here below:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<head>
require_once(checklogin.php)
</head>
<body>
<?php
if($myusername == "admin");
echo " Click Me! ";
?>
</body>
</html>
The $myusername variable comes from the file below which checks the username from a form (on another page) against the mysql table and opens a session.
<?php
ob_start();
$host="-----";// Mysql username
$password="-----"; // Mysql password
$db_name="-------"; // Database name
$tbl_name="-------"; // 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 * FROM $tbl_name WHERE username='$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:login_success.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
So to repeat my question: What exactly is wrong with this block of code
if($myusername == "admin");
echo " Click Me! ";
?>
which should recognize the user and display the link
The cause of the syntax error is a stray ; after the if statement. It should be removed.
if($myusername == "admin");
//-----------------------^^
// Error here -- remove that semicolon!
There are some other issues here, like the unquoted value in session_register(), which should be surrounded in quotes:
session_start();
if(!session_is_registered(myusername)){
//-----------------------^^^^^^^^^^^^^
header("location:main_login.php");
}
However, the use of session_register() is not recommended. The proper modern way to set session variables is by using the $_SESSION superglobal array. (see the deprecation notices in the PHP docs)
// Set a variable
session_start();
$myusername = "admin";
$_SESSION['myusername'] = $myusername;
// Get a variable
// Always call session_start() at the beginning of the script
echo $_SESSION['myusername'];
// admin
try like this
<?php
if($myusername == "admin")
echo "<a href='test.html'> Click Me! </a>";
?>
when you start the string with double inverted coma(") you must have to use single inverted coma(') in that statement if parser found another double inverted coma (") it will consider as a end of string
may be this issue
Try this
<?php
if($myusername == "admin") // semicolon removed
{
// use single quotes for href or escape double quotes
echo "<a href='test.html'> Click Me! </a>";
}
?
place test.html in single quotes like this ('test.html') not like this ("test.html")
There are two problems.
if($myusername == "admin"); // remove this semicolon after if.
And echo " Click Me! "; // remove the double quotes around test.html
Related
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.
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 have a checklogin.php script that works fine to redirect a user to a specific page on successful login. I now want to set it to redirect to the original index.php page that redirected the user to the login form. At the top of index.php I include:
<?php
session_start();
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
I have checked that $_SESSION['url'] is getting correctly set on this page.
main_login.php just contains the login form which is processed by checklogin.php:
<form name="form1" method="post" action="checklogin.php">
and $_SESSION['url'] is getting correctly set on this page too.
checklogin.php looks like this:
<?php
session_start();
print_r($_SESSION['url']);
ob_start();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // 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);
$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
$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:$_SESSION['url']");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
As you can see I am trying to print $_SESSION['url'] at the top of this script but nothing is getting returned.
Could someone help with this?
Thanks,
Nick
You cannot insert a "complex" variable like $_SESSION['url'] inside a litteral string, like the following statement:
header("location:$_SESSION['url']");
In my version of PHP (5.3.10), it produces the following error:
PHP Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE,
expecting T_STRING or T_VARIABLE or T_NUM_STRING in
/home/.../test.php on line ...
Indeed, if you want to output a field in an array, you should use concatenation:
header("Location: " . $_SESSION['url']);
This may be the source of your problem. Depending on PHP configuration, it may not display the error and just output a blank page, check the php logs to be sure.
The best practice is to use this whenever you want to output the value of a variable in a string.
For example, do not use echo "Foo: $foo";, use instead echo "Foo : ". $foo;
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 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');
}