Php not accessing the Database - php

i have a form file with name form1.php
<?PHP
//form.php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>form</title>
</head>
<body>
<?PHP if (isset ($_SESSION["notfound"])) { ?>
<h2 style="text-align:center">Wrong user name or password</h2>
<?PHP unset($_SESSION["notfound"]);}
if (isset ($_SESSION["empty"])) {?>
<h2 style="text-align:center">Empty</h2>
<?PHP unset($_SESSION["empty"]); }?>
<form name="signin" action="http://localhost/M1.php" method="post">
<table>
<tr>
<td>
<label>
Username<input type="text" name="name" size="32"/>
</label>
</td>
<td>
<label>
Password <input type="password" name="pass" size="32"/>
</label>
</td>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>
</form>
and controll file M1.php
<?php
$name=$_POST["name"];
$pass=$_POST["pass"];
if((!empty($name)) && (!empty($pass)))
{
session_start();
if($conection=mysql_connect("localhost","","")===false)
die("not connect to data base");
if(mysql_select_db('login',$conection) ===false)
die("data base not found");
$sql =sprintf("SELECT `password` FROM `signin` WHERE `username`= '%s' ",mysql_real_escape_string($name));
$dbpass=mysql_query($sql);
if ($dbpass==$pass)
{
$_SESSION["authenticated"]=true;
header("Location: http://localhost/home.php");
exit;
}
else //if ($dbpass===false)
{
$_SESSION["notfound"]=true;
header("Location: http://localhost/form1.php");
exit;
}
}
else
{
$_SESSION["empty"]=true;
header("Location: http://localhost/form1.php");
exit;
}
?>
*i am useing xampp for runing them
i have data base loging which contain a table signin
when i fill the form with same user name and password which i save in signin table and click submit it return me on form1.php with session 'notfoun'
and when i submit empty form it return me without seting empty session *

You are not fetching data from database and you make a condition based on execute query = $pass which will be always false, so change to
$dbpass=mysql_query($sql);
$result = mysql_fetch_array($dbpass);
$passw = $result['password'];
if ($passw==$pass)
{
//logged
As side note i would say a couple of thing. First I notice you sanitized your input which is a good pratice, but you really should switch to prepared statments with either PDO or mysqli so you will avoid any risk of mysql injection, also because mysql_* functions are deprecated. Second saving a password in plain text in database is a very bad pratice, you should really encrypt it and save an hash of the password in database, there is anice post about that here. Further more I think that session_start(); should be placed at the top of your file to work correctly.

It's firstly good time to make use of PDO or mysqli rather then using mysql which is deprecated in latest PHP version.
While passing db connection values, I feel you missed out the username & password, which should help you connect the database.
Later, mysql_query("SELECT_QUERY"); returns result object, whose values should be read by mysql_fetch_assoc() which returns the db row into associative array form.
Finally your code should look like,
$sql =sprintf("SELECT `password` FROM `signin` WHERE `username`= '%s' ",mysql_real_escape_string($name));
$result = mysql_query($sql);
$dbpass = mysql_fetch_assoc($result);
$dbpass = $dbpass['password'];
if ($dbpass==$pass)
{
$_SESSION["authenticated"]=true;
header("Location: http://localhost/home.php");
exit;
}
else //if ($dbpass===false)
{
$_SESSION["notfound"]=true;
header("Location: http://localhost/form1.php");
exit;
}

What's the error you're getting?
Anyway, how do you connect through your database? I see you have put the username and password as an empty string. You should try to put in a user/pass of an existing user:
mysql_connect syntax:
mysql_connect(host,username,password,newlink,clientflag)
example:
mysql_connect("localhost","root","")
or
mysql_connect("localhost","root","password")

Related

Retrieving an SQL statement from an HTML form with the POST method doesn't query the database

I'm currently building a simple CRUD application and decided it would be a nice feature to directly query the database from the browser (i.e from an HTML table) and display ('Read') the results from that particular query.
However, I've been doing some reading and it seems this would essentially be an SQL injection and is something to be avoided. Apparently, it is NOT normal practice to ask a user to input an SQL statement.
Despite this, I've been trying to add this feature to experiment with my code but the SQL statement provided by the HTML form is not being executed.
To recap:
My form in index.php asks the user for an SQL statement.
This is then processed by read.php, which retrieves the SQL statement with the superglobal $_POST['submitsql'] ('submitsql' is just the name of the form's submit button) and queries the database with the query() method. It also displays a message with _$_SESSION[''] superglobal.
From index.php: (form where the user inputs SQL statement)
<form action ="read.php" method ="post">
SQL statement: <input type="text" name="sql_stat">
<button type= 'submit' name = 'submitsql'>Query</button>
</form><br>
read.php (retrieves SQL statement and queries the database)
<?php
include ('server.php');
if(!isset($_SESSION)){
session_start();
}
if(isset($_POST['submitsql'])){
$sql = $_POST['sql_stat'];
$results = $conn->query($sql);
$conn->close();
$_SESSION['message'] = "Query successfully sent: ".$sql;
header('location: index.php');
}else{
$sql = "SELECT * FROM `Students` ORDER BY `degree`";
$results = $conn->query($sql);
$conn->close();
}
?>
For some reason, the message containing the SQL statement is correctly displayed but the database is not queried and all the records are shown (in a table in index.php).
I hope I'm making sense here. My code was working fine when read.php was querying the database directly as opposed to retrieving the SQL statement from the HTML form in index.php. Apologies if I'm not expressing myself correctly.
If it makes any difference, here is the entire index.php:
<?php
include('server.php');
include('create.php');
include('read.php');
include('delete.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>CRUD PROJECT</title>
<meta charset="utf-8"/>
</head>
<body>
<h1>CRUD project</h1>
<h4>Query the database:</h4>
<form action ="read.php" method ="post">
SQL statement: <input type="text" name="sql_stat">
<button type= 'submit' name = 'submitsql'>Query</button>
</form><br>
<?php
if(isset($_SESSION['message'])){
echo $_SESSION['message'];
session_unset();
session_destroy();
}
?>
<table border = '1' cellpadding = '10' >
<tr>
<th>Student ID</th><th>Degree</th><th>Grade</th><th>Graduation Year</th>
</tr>
<tr>
</tr>
<?php
if($results->num_rows>0){
while($row = $results->fetch_assoc()){
echo "<tr><td>".$row['student_id']."</td>";
echo "<td>".$row['degree']."</td>";
echo "<td>".$row['grade']."</td>";
echo "<td>".$row['graduation_year']."</td>";
echo "<td><a href = 'update.php?student_id=".$row['student_id']."'>Edit</a></td>";
echo "<td><a href = 'delete.php?student_id=".$row['student_id']."'>Delete</a></td>";
}
}else {
echo "NO RESULTS TO DISPLAY";
}
?>
</table>
<br>
<h2> Add new records </h2>
<form action ="create.php" method ="post">
Degree: <input type="text" name="degree"><br>
Grade: <input type="text" name="grade"><br>
Graduation year: <input type="text" name="graduation_year"><br>
<button type= 'submit' name = 'submit'>Submit</button>
</form>
</body>
</html>
And server.php where I connect to the database and initialise my variables:
<?php
//Define connection parameters
$db_server = 'localhost';
$db_user = 'root';
$db_password = 'therasmus1';
$db_name = 'University_records';
$conn = new mysqli($db_server,$db_user,$db_password,$db_name);
// Toggle error display
mysqli_report(MYSQLI_REPORT_ERROR);
// Check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
// Initialise your variables (optional - good practice)
$Degree = "";
$Grade = "";
$Graduation_year = "";
$sql = "SELECT * FROM `Students`";
$results = $conn->query($sql);
?>
All feedback is welcome. Thanks in advance.
I can see that there is an issue with your logic. You are submitting your form to read.php then preparing the $results in that file and then immediately redirecting to index.php so you never use the $results when you submit the form.
But you are also including the read.php in your index.php file. So what happens is that, you submit your form to read.php, create the $results(but never use it), redirect to index.php, in the index.php you have included read.php so now it checks if(isset($_POST['submitsql'])){ and since the request method now is not post it goes to else block:
$sql = "SELECT * FROM `Students` ORDER BY `degree`";
$results = $conn->query($sql);
$conn->close();
So the $results contains all the records of the Students table.
With this logic, no matter what you type in <input type="text" name="sql_stat">, you will always get the $sql = "SELECT * FROM Students ORDER BY degree";
The easiest way to fix this problem, is:
Submit your form to index.php. In index.php Change <form action="read.php" method="post"> to <form action="index.php" method="post">
Remove the header('location: index.php'); from read.php
This fix will solve your current problem.

error using inert php plugin wordpress

I want to create login page for admin and worker, and each of them will have different content table in their page once they logged in.
I've installed insert php plugin to write code in page directly.
I am using session for login and I want to use record set to create custom table in each page.
I created a code in dreamweaver then post it in page text.
I have created this code but it didn't work as php and didn't logged in and shows code in the page.
[insert_php]
error_reporting(E_ALL);
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "lujcarwa", "lcarwash2015");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = mysqli_real_escape_string($password);
// Selecting Database
$db = mysqli_select_db("login", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login']=$username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
error_reporting(E_ALL ^ E_DEPRECATED);
include('login.php'); // Includes Login Script
if(isset($_SESSION['login'])){
header("location: profile.php");
}
error_reporting(E_ALL ^ E_DEPRECATED);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "lujcarwa_washer", "dj0P7]w4S]");
// Selecting Database
$db = mysqli_select_db("lujcarwa_washer", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysqli_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
[insert_php/]
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1> Login </h1>
<div id="login">
<form action="" method="post">
<p>
<label>UserName :</label>
</p>
<p>
<br />
<input id="name" name="username" placeholder="username" type="text">
<br />
<label>
<br>Password</label>
<br />
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
</p>
</form>
</div>
</div>
</body>
I'm not known with the [insert_php] plugin but it looks like it's a issue with not closing you [insert_php] tag like this [/insert_php] at the end of your php.
Edit:
You are closing it like:
[insert_php/] //While it should be: [/insert_php]
Hope this helps you out.
Edit:
I just took a look at the plugin description and saw this in the FAQ:
Why can't I set cookies or do a browser redirect?
With PHP, cookies are set in the web page header lines, before any page content is processed. Redirects, too, are done in the header lines. When PHP code is within a post or a page, all the header lines have already been sent, along with part of the content. At that point, it is too late to set cookies or redirect with PHP
So it looks like you can't use this plugin to redirect the user at login.
I would suggest just to write the php in your template folder in a custom page template or header file.
Hope this helped!

Can't redirect from login page to home page [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I am learning pHp. I have made a login page.
The problem i am facing here is that, when user clicks on signin button & if record is found then he is taken to other page which displays redirect link, the user has to click on that to go to the next page.
Now what i want that when a user click on signin button, then the details should be cross checked in the database, if the record is found then user should be directly redirected to next page else error should be displayed.
This is my html page:
<!DOCTYPE html>
<html>
<head>
<title>OpenMoz</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="index.css"/>
</head>
<body style="height:650px;">
<h1 align="center" ><b><i>City Login</i></b></h1>
<div class="login">
<form action="login.php" method="post">
<input type="text" placeholder="Username" name="username" autocorrect=off autocapitalize=words required> <br>
<input type="password" placeholder="password" name="password" autocorrect=off autocapitalize=words required> <br>
<input type="submit" name="submit" value="Sign In">
</form>
<input type="submit" name="submit" value="Sign Up">
<div>
</body>
</html>
This is the login.php script to verify details :
<?php
$username = $_POST["username"];
$password = $_POST["password"];
if($username && $password)
{
$connect = mysql_connect("localhost","root","password") or die("Couldn't connect");
mysql_select_db("phplogin")or die("Couldn't connect");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword)
{
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
}
else
{
echo ("Incorrect Password !");
}
}
else
die("The user doesn't exist");
}
else
echo ("Please enter username & password");
?>
I would be really thankful if my problem gets solved.
As long as you have not outputted anything to the browser, you can do a header redirect. This will achieve your aim.
Change this:
echo ("<center><a href='home.php'>Redirect</a></center>");
$_SESSION['username'] = $username;
To this:
$_SESSION['username'] = $username;
header("Location: /some-new-page.php");
exit;
Always exit; after a location redirect.
Oh yeah, and CLEAN your inputs.. ..you are wide open to SQL Injection.
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Oh yeah .. and mysql_* is deprecated. Use mysqli_*
use header("Location:home.php"); its best way to redirect page in php
header("Location:whaeverpage.php");
exit();
Do it before sending any data to the browser or you will get a header allready sen error
or by javascript :
If($connected ==='yes'){//your connection statement
?>
<script>window.location.replace("whatever_page");</script>
<?
}
WOWOW NONONO HALT! DO NOT LEARN mysql_ API FOR NEW DEVELOPMENT. It's deprecated/unsupported, ancient, error-prone. learn to use mysqli_ or better yet, PDO , and here is a great tutorial http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
also here: $query = mysql_query("SELECT * FROM users WHERE username='$username'");
code is vulnerable to SQL injection attack by hackers. must use mysql_real_escape_string.
also, you should not use * , for most cases, be specific. Also, you should not store passwords in plaintext (as your login system is doing), you should hash it..
other than that, check Chris Magg's already said what i would'ev https://stackoverflow.com/a/31355969/1067003

Issue with directing php form [duplicate]

This question already has answers here:
PHP Form not directing to correct pages
(4 answers)
Closed 9 years ago.
<?php
if ($_POST['submit'] == "submit")
{
$userName = $_POST['username'];
$passWord = $_POST['password'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$checkUserNameQuery = "SELECT username FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWordQuery = "SELECT password FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkPassWord = mysql_query($checkPassWordQuery);
$AdminChanges = "";
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
$AdminChanges = "AdminChanges.php";
}
else
{
$AdminChanges = "InvalidLogin.html";
}
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action = <?php echo PrepSQL($AdminChanges); ?> method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
I'm having a problem where the form, when submitted, is being directed to the wrong places. It's a user verification page. If the username and password don't match the ones stored in the database, it should go to the Invalid Login page. If they do, they should go to the next part of the user verification website.
The form tag, before entering values, looks like this in the page source:
However, when the username & password are correct, it goes to the InvalidLogin.html page. When it's incorrect, the form reloads again and when I check the page source, it's the exact same code except now the form tag shows:
Any suggestions?
I think u got it wrong, the action tag is where the form sends the request, not where to go after it sends it.
Try using header('location: '.$AdminChanges); right after the user verification in order to redirect the page.
EDIT: Also remove the action tag of the form. By removing it the request will be sent to the same file you are working on.
<?php
if($_POST['username'] && $_POST['password']){
$username = $_POST['username']; // Escape this
$password = $_POST['password']; // Escape this
$searchQuery = mysql_query("SELECT id FROM onlineformdata WHERE username = '$userName' AND password = '$password' ORDER BY id DESC LIMIT 1");
if(mysql_num_rows($searchQuery)){
header('location:/adminPage.php'); // Go to this page if row exists in DB
}
else{
header('location:/invalidLoginPage.html'); //Go to this page if row doesn't exist in DB
}
exit; // So that it quite this page and goes to the desired one set in the "headers"
}
else{
//Not strictly needed... But you could be useful in some circumstances
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action='' method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" value="submit" />
</form>
</body>
</html>
This should get you started in the right direction. Don't forget to escape the username/password fields as you see fit.
The action part of the form is where the form is submitted to and so - in your case - that should be the same page. As Hristo said, you can leave it out/blank and it will default to submitting itself.
As for Marc B (he did ask a question after all); if you read the code you would see that the PrepSQL function actually adds single quotes around the string... As there are no quotes in the html this isn't wrong in anyway... So I don't see what the problem is there (aside from it not doing what he wanted it to).
With regards to multiple user accounts, so long as you don't allow the same username to be used by multiple users then there is only one record returned by the database... So again, there's no problem there.

Creating a login page with php - Can't see where the error lies

EDIT: ASSIGNMENT WORK. Please don't mention External Libraries or complicated procedures that deal with security issues.
I want to implement a very basic login page that compares the users username and password with ones stored in a database (using MySql) and then redirect to another webpage that is only available to logged in users. I have looked at these two tutorials:
http://frozenade.wordpress.com/2007/11/24/how-to-create-login-page-in-php-and-mysql-with-session/
http://www.phpro.org/tutorials/Basic-Login-Authentication-with-PHP-and-MySQL.html
and I've attempted to use both techniques. The second one kept giving me server errors, and the first one gives me the login page, and doesn't return any errors, but then when pressing the submit button, it just doesn't do anything. I've followed it practically word for word, only changing the file names and some database column names to fit with my pre-existing stuff, but to no avail. This login page has given me an almighty headache and I would really like to get this out of the way and done with now.
LOGIN PAGE
<?php
// Inialize session
session_start();
// Check, if user is already login, then jump to secured page
if (isset($_SESSION['username'])) {
header('Location: RecordEvents.php');
}
?>
... skip all the unnecessary parts
<h1>Login</h1>
<?php
if(!empty($errorMessage))
{
echo("<p>There was a problem with your login:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="loginscript.php" method="post">
Username:
<input type="text" name="username" /> </br>
Password:
<input type="password" name="password" /> </br>
<p>
<!--the submit button with an altered value. once selected the validation script will run-->
<input type="submit" name="login" value="Allons-y!" />
</p>
</form>
CONFIG.INC (I tried at first naming the file .php but that made no difference.)
<?php
$hostname = 'localhost';
$dbname = 'clubresults';
$username = 'newuser';
$password = 'password';
// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
// Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
?>
LOGINSCRIPT.PHP
<?php
// Inialize session
session_start();
// Include database connection settings
include('Inlcude\config.inc');
// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT * FROM admin_passwords WHERE (Username = '" . mysql_real_escape_string($_POST['username']) . "') and (Password = '" . mysql_real_escape_string(md5($_POST['password'])) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['username'];
// Jump to secured page
header('Location: RecordEvents.php');
}
else {
// Jump to login page
header('Location: Login.php');
}
?>
RECORDEVENTS.PHP
<?php
// Inialize session
session_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['username'])) {
header('Location: Login.php');
}
Include ('Include\eventscript.php');
?>
... blah blah
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="RecordEvents.php" method="post">
Name: <input type="text" name="EventName" value="<?php print $varEventname;?>" /> </br>
Date: <input type="text" name="EventDate" placeholder="yyyy-mm-dd hh:mm:ss" value="<?php print $varEventdate;?>" /> </br>
Location: <input type="text" name="Location" value="<?php print $varLocation;?>" /> </br>
<p>
<!--the submit button with an altered value. once selected the validation script will run-->
<input type="submit" name="formSubmit" value="Allons-y!" />
<!--the reset button to empty the form and start again-->
<input type="reset" name="formReset" value="Try Again" />
</p>
</form>
the db is called clubresults, the table i'm using is admin_passwords and the column names are: Username, Password.
Can anyone spot the error I am obviously making?
Check your spelling.
include('Inlcude\config.inc');
Please see this.
$login = mysql_query("SELECT * FROM admin_passwords WHERE username = '" .mysql_real_escape_string($_POST['username']) . "' and password = '" .mysql_real_escape_string($_POST['password']) . "'");
I removed the md5() function.
http://php.net/manual/en/function.md5.php
This is what really happens when there is an md5 in your query.
Lets say that you input the ff.
username = username
password = password
Your query will be like this, with md5() in your $_POST['password'].
SELECT * FROM admin_passwords WHERE username = 'username' and password = '5f4dcc3b5aa765d61d8327deb882cf99'
Please see the link above for more info!
First thing I see is
include('Inlcude\config.inc');
Obviously, the path is wrong. Further, sanitize your code. E.g. include doesn't require parentheses and should be written in lower case always, like
include 'Include\config.inc';
Next, are you sure, there is only one entry in your database? As it is defined to only load the recordevents script on
mysql_num_rows($login) == 1
Sometimes while developing, you may have two equal rows.

Categories