major php issues - php

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');
}

Related

Php Session and post problems in login page

Ok, so we got some basic HTML here
<form action="main_login.php" method="post" style="text-align:right;">
Username:
<input type="text" name="username" value="" size=20 style="display:inline-block;margin-left:10px"required>
<br>
Password:
<input type="password" name="password" value="" size=20 style="margin-left:12px"required>
<br>
<input type="submit" value="Log In" style="margin-left:75px"=>
</form>
And 2 php files the main login.php
<?php
session_start();
$con = mysqli_connect("localhost", "root", "", "complaints");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$myusername=$_POST["username"];
$mypassword=$_POST["password"];
echo $myusername . "<br>";
echo $mypassword . "<br>";
// MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM register WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($con,$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['username']=$myusername;
$_SESSION['password']=$mypassword;
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
mysqli_close($con);
?>
If login succeeds its redirecting here login.php
<?php
session_start();
if ( isset( $_SESSION['username'] ) ){
header("location:main_login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
Ok, so, im new in php and dont know much about sessions. First i used session_register and session_is_registered but as i found out these functions are not used anymore. so i converted to sessions but my problem keeps appearing here
$myusername=$_POST["username"];
$mypassword=$_POST["password"];
I cant use the $_POST to get the data from the form. Also i dont know if i have placed correctly the session functions.
Edit: Username and password names in html are the same which are used in php, i just misstyped here.
Edit: Username and password names in html are the same which are used in php, i just misstyped here.
Edit: Ok, so you've made a typo in the form fields. You're still mixing MySQL APIs, see further down below about the mixing function using mysql_real_escape_string().
Look at name="myusername" and your POST assignment, along with the one for your password.
They don't match.
Change name="myusername" to name="username"
and name="mypassword" to name="password"
as per
$myusername=$_POST["username"];
$mypassword=$_POST["password"];
Having used error reporting, would have signaled an undefined index and an headers already sent warning; see below.
You also have spaces before <?php which would cause an output before header. Remove them.
Plus, you're mixing MySQL APIs with mysql_error(). mysql_error() should read as mysqli_error($con) and this below:
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
which should read as
$myusername = mysqli_real_escape_string($con,$myusername);
$mypassword = mysqli_real_escape_string($con,$mypassword);
or
$myusername = mysqli_real_escape_string($con,$_POST['username']);
$mypassword = mysqli_real_escape_string($con,$_POST['password']);
mysqli_ and mysql_ functions do not intermix together.
Regarding security
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Plus, in regards to SQL injection, use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Footnotes
It is best to add exit; after each header.
header("location:login_success.php");
exit;
and for all headers.
Edit:
Remove
$myusername=$_POST["username"];
$mypassword=$_POST["password"];
echo $myusername . "<br>";
echo $mypassword . "<br>";
then replace it with:
$myusername = stripslashes($_POST["username"]);
$mypassword = stripslashes($_POST["password"]);
$myusername = mysqli_real_escape_string($con,$_POST['username']);
$mypassword = mysqli_real_escape_string($con,$_POST['password']);
Edit #2:
This is what I tested your code with, and got success, therefore I don't know what is wrong with your present code.
HTML FORM
<form action="main_login.php" method="post" style="text-align:right;">
Username:
<input type="text" name="username" value="" size=20 style="display:inline-block;margin-left:10px"required>
<br>
Password:
<input type="text" name="password" value="" size=20 style="margin-left:12px"required>
<br>
<input type="submit" value="Log In" style="margin-left:75px"=>
</form>
MySQL
<?php
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
$myusername = stripslashes($_POST["username"]);
$mypassword = stripslashes($_POST["password"]);
$myusername = mysqli_real_escape_string($conn,$_POST['username']);
$mypassword = mysqli_real_escape_string($conn,$_POST['password']);
echo $myusername; // echos
echo "<br>";
echo $mypassword; // echos
$sql="SELECT * FROM register WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($conn,$sql);
$count=mysqli_num_rows($result);
if($count==1){
echo "Yep";
}
else{
echo "nope";
}
N.B.: You should also clear out your sessions (destroy sessions), there could be something on the server caching old usernames and passwords.
Also make sure there are no spaces in your columns, that the types are correct and the lengths are long enough to hold the data. Usually VARCHAR(255) is more than enough, but is suggested when using hashed passwords generated by password_hash(), a function which you should be using when storing passwords.
See also:
What is the difference between session_unset() and session_destroy() in PHP?
on Stack.
<?php
session_start();
First of all there is a space at the beginning.
It should be
<?php session_start();
the session problems for login page might occur because the url you are opening in the browser are not unique. for example If say you are creating a login page for your website, and you have created sessions successfully. Now, if you are logging in from url say http://geekzgarage.com then your session is limited to this url only. If you again open the above url like http://www.geekzgarage.com (note www. in both urls), then you will see that you are not logged in.
So make sure that your webpage is opening always in single type of url. either with www. or without www.

PHP and MySQL echo string only in certain conditions

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

Code not working. PHP / HTML

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.

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