I was hoping someone could help me with a small script I am writing, my main goal is to just make a registration page as secure as possible and thought the best place to start would be using mysql_real_escape_string however it wont keep I just keep getting error at line 1 so here's my code:
<?php
if(isset($_POST['submit'])){
if($_POST['username'] == "" || $_POST['password'] == ""){
header("Location: tryagain.php");
exit;
}else{
mysql_connect("localhost", "root", "Root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$username = $_POST['username'];
$password = $_POST['password'];
$sql = sprintf("INSERT into login(id,username,password) values('','%s','%s'", mysql_real_escape_string($username), mysql_real_escape_string($password));
$result = mysql_query($sql) or die(mysql_error()) ;
echo "Congratulations it worked woooo";
}
}
?>
and heres the html
<form method="post" action="sql.php">
<table>
<tr>
<td>
<input type="text" name="username"/>
</td>
<td>
<input type="text" name="password"/>
</td>
<td>
<input type="submit" name="submit" value="submit">
</td>
</tr>
</table>
</form>
If i change the $sql statment to this the code works fine
$sql = "INSERT into login(id,username,password) values('','$username','$password')";
Can anyone see what I've done wrong :S it works perfectly fine when I adjust it to log in using real escape.
Also what other methods can I use to validate data? I plan on making the if statements check for only number and letters, and just prevent any special characters all together. Thanks.
On a side note, yes I know mysqli and pdo should be used not mysql sadly were I'm at they don't use them.
Your SQL statement is broken:
INSERT into login(id,username,password) values('','%s','%s'
Should be
INSERT into login(id,username,password) values('','%s','%s')
Not sure what is your issue, I'm thinking sprintf. Maybe try this :
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = sprintf("INSERT into login(id,username,password) values('','%s','%s', $username, $password)");
Related
<?php
session_start();
$db =mysqli_connect("localhost", "root", "","registration" );
if (isset($_POST['login_btn'])){
$username = mysql_real_escape_string($_POST ['username']);
$password = mysql_real_escape_string($_POST ['password']);
$password= md5($password);
$sql = "SELECT * FROM users WHERE username= '$username' AND password= '$password'";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result) == 1 ){
$_SESSION['message']= "You are now logged in";
$_SESSION['username'] = $username;
header("Location: home.php");
}else{
$_SESSION['message'] = "Username and password combination is incorrect";
}
}
?>
<html>
<head>
</head>
<body>
<div class="header"> <h1>login</h1></div>
<?php
if (isset($_SESSION['message'])){
echo "<div id = 'error_msg>".$_SESSION['message']."</div>";
unset($_SESSION['message']);
}
?>
<form method="post" name="loginform" action="login.php">
<table>
<tr>
<td> Username:</td>
<td><input type = "text" name="username" placeholder="Username" class="textInput" required></td>
</tr>
<tr>
<td> Password:</td>
<td><input type = "password" placeholder="Password" name="password" class="textInput" required></td>
</tr>
<tr>
<td></td>
<td><input type = "submit" name="login_btn" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
Hi guys, this is my login page with PHP. Apart from logging in it allows passwords which are not the same. According to the code its set to check if the two passwords are matching and if they aren't, it displays an error.
This one doesn't display an error even if the two passwords don't match. Why does it allows a user to log in with wrong passwords??
I want it to display an error when passwords don't match and in return doesn't allow logging in because of wrong credentials.
You are not using mysql_real_escape_string properly. You should use either mysqli_real_escape_string or use mysql_connect to connect to MySQL.
mysql_real_escape_string's second parameter is assumed automatically if mysql_connect is used, but you are using mysqli_connect instead, that's why it's not finding any connection.
From pph website it states:
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Reference: http://php.net/manual/en/function.mysql-real-escape-string.php
Try changing
$username = mysql_real_escape_string($_POST ['username']);
$password = mysql_real_escape_string($_POST ['password']);
to
$username = mysqli_real_escape_string($db, $_POST ['username']);
$password = mysqli_real_escape_string($db, $_POST ['password']);
I'm new to php and sql and all that stuff, and I was watching a tutorial on youtube about forums in php and wonder why this code doesn't echo "Success" when submitting the form. I also wonder why it echo out Failure before I have submitted the form. I have connected successfully to the database.
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="register.php" method="POST">
Username: <input type="text" name="username">
<br/>
Password: <input type="password" name="password">
<br/>
Confirm Password: <input type="password" name="confirmPassword">
<br/>
Email: <input type="text" name="email">
<br/>
<input type="submit" name="submit" value="Register"> or Log in
</form>
</body>
</html>
<?php
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysql_query("INSERT INTO users ('id', 'username', 'password', 'email') VALUES('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysql_error();
}
}
?>
Connect.php
<?php
$connect = mysqli_connect("localhost", "root", "") or die("Could not connect to server!");
mysqli_select_db($connect, "php_forum") or die("Could not connect to database!");
?>
There are a few things wrong here.
You're using the wrong identifiers for your columns in (and being quotes):
('id', 'username', 'password', 'email')
remove them
(id, username, password, email)
or use backticks
(`id`, `username`, `password`, `email`)
mysql_error() should have thrown you an error, but it didn't because of:
You're mixing MySQL APIs with mysqli_ to connect with, then mysql_ in your query.
Those two different APIs do not intermix with each other.
Use mysqli_ exclusively and change your present query to:
if($query = mysqli_query($connect, "INSERT...
and change mysql_error() to mysqli_error($connect)
as a rewrite for that block:
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users ('id', 'username', 'password', 'email') VALUES('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
Just to test the error, make the changes as I outlined just above, while keeping the quotes around your columns the way you have it now. You will then see the error that MySQL will throw. You can then do as I've already outlined above and remove the quotes around the column names, or replace them with backticks.
The tutorial you saw may very well used backticks, but were probably not distinguishable enough for you to tell that they were indeed backticks and not single quotes.
However, your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
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.
Also, instead of doing:
$connect = mysqli_connect("localhost", "root", "") or die("Could not connect to server!");
mysqli_select_db($connect, "php_forum") or die("Could not connect to database!");
You should be checking for errors instead, just as the manual states
$link = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($link));
http://php.net/manual/en/function.mysqli-connect.php
So in your case:
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
Edit: and I changed action="register.php" to action="" since you're using the entire code inside the same page.
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Username: <input type="text" name="username">
<br/>
Password: <input type="password" name="password">
<br/>
Confirm Password: <input type="password" name="confirmPassword">
<br/>
Email: <input type="text" name="email">
<br/>
<input type="submit" name="submit" value="Register"> or Log in
</form>
</body>
</html>
<?php
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users (`id`, `username`, `password`, `email`) VALUES ('', '".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
:It will echo ;Failure' so executing this bit of code
else{
echo "Failure" . mysql_error();
}
whenever $_POST["submit"]) is not set and it will be not set anytime you open you page (even if you navigate to it from your bookmark of from google search results) or when you submit you FORM in GET mode
I am trying to build a login system with registration etc.
now for the registration i use a form and the method "post". Now it fails in what i think is sending the input trough the post. can you help me fix it? here is the code involved in it:
above !doctype
<?php
include('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST["username"]) && isset($_POST["password"])){
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$query = "INSERT INTO `user` (username, password, email) VALUES ($username, $password, $email)";
$result = mysqli_query($query);
if($result){
$msg = "User Created Successfully.";
}
else
{echo "fail";}
}
?>
the form:
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Registreer</h1>
<form action="" method="POST">
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email" required placeholder="name#email.com" /></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Registreer" />
</form>
</div>
The connect.php
<?php
$servername = "localhost";
$username = "sqluser";
$password = "Welkom01!";
$dbname = "users";
$connection = mysqli_connect($servername, $username, $password);
if (!$connection){
die("Database Connection Failed". mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, $dbname);
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
Thanks in advance.
As per your originally posted question and without marking it as an edit under your newly edited question, should anyone wonder why the answer.
Since we're more than likely dealing with strings
VALUES ($username, $password, $email)
needs to be wrapped inside quotes:
VALUES ('$username', '$password', '$email')
you also need to pass DB connection to your query $result = mysqli_query($query);
Edit: (you added your DB connection code after) from your original post
Since you've not shown what your DB connection is, this would be something like
$result = mysqli_query($connection,$query);
plus, adding or die(mysqli_error($connection)) to mysqli_query()
You also have a missing & in if(isset($msg) & !empty($msg)){ which should read as if(isset($msg) && !empty($msg)){
However, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
So actualy the problem is i need a login/register system and thast what i wrote and it works all fine login and register is working except when i try to create account i write in all the things its needed and create it and it says You've succsessfully registered! but when i go check the database there isnt the new data with id username pass and so on but i get no error connecting to database or anything and when i try to login i cant cuz there are no data from registering in database. I also checked the database name twice and its not wrong in the code i think or it is i m kinda new in php.
if anyone wants i can add him on skype or you can check over teamviewer if u prefer i rly need this fixed please!!
picture of the database: http://shrani.si/f/1f/pO/3sIbCuUk/brez-naslova.png cant post pictures directly yet
Database server
Server: 127.0.0.1 via TCP/IP
Server type: MySQL
Server version: 5.6.14 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
Web server
Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6
Database client version: libmysql - mysqlnd 5.0.11-dev - 20120503
PHP extension: mysqli Documentation
this is my register.php file
echo "<h1>Sign Up</h1>";
$submit = #$_POST['submit'];
//form data
$fullname = strip_tags(#$_POST['fullname']);
$username = strip_tags(#$_POST['username']);
$password = strip_tags(#$_POST['password']);
$confirmpassword = strip_tags(#$_POST['confirmpassword']);
$date = date("Y-m-d");
if($submit)
{
//check for existance
if($fullname&&$username&&$password&&$confirmpassword)
{
if($password==$confirmpassword)
{
if (strlen($username)>25||strlen($fullname)>25)
{
echo "Lenght of username or full name is too long!";
}
else
{
if(strlen($password)>25||strlen($password)<6)
{
echo "Your password must be between 6 and 25 characters long!";
}
else
{
//register the user
//encrypt password
$password = md5($password);
$confirmpassword = md5($confirmpassword);
//connect to databases
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("login");
$queryreg = mysql_query("INSERT INTO users VALUES ('','$fullname','$username','$password','$date'");
die("You've succsessfully registered! <a href='index2.php'>Click here to return to the login page!</a>");
}
}
}
else
{
echo "Your passwords do not match!";
}
}
else
{
echo "Please enter all fields!";
}
}
?>
<p>
<form action="register.php" method="POST">
<table>
<tr>
<td>
Full Name:
</td>
<td>
<input type="text" name="fullname" value="<?php echo $fullname?>">
</td>
</tr>
<tr>
<td>
Username:
</td>
<td>
<input type="text" name="username" value="<?php echo $username ?>">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>
Confirm Password:
</td>
<td>
<input type="password" name="confirmpassword">
</td>
</tr>
</table>
<p>
<input type="submit" name="submit" value="Create Account">
</p>
</form>
thats my index2.php i named it index2.php cuz i arleady have 1 index.php
<head>
<title>Login Session</title>
</head>
<body>
<form method="POST" action="login.php">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" name="submit" value="Log in">
Create An Account
Domov
</form>
</body>
and here is login.php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username&&$password)
{
$connect = mysql_connect("localhost", "root", "") or die("Couldn't connect to host!");
mysql_select_db("login") or die("Couldn't find database!");
$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&&md5($password)==$dbpassword)
{
$_SESSION['username']=$username;
header("Location: member.php");
}
else
{
echo "Wrong password!";
}
}
else
{
die("That user hasn't been created!");
}
}
else
{
echo "Username and password must be entered!";
}
and member.php
session_start();
if ($_SESSION['username'])
echo "Hello, ".$_SESSION['username']."!<br/><a href='logout.php'>Sign Out";
else
{
header("Location: index2.php");
}
I think you are trying to insert a record without a valid primary key. Use null instead of '' for the primary key
$queryreg = mysql_query("INSERT INTO users VALUES (null,'$fullname','$username','$password','$date'");
You can also see if there is any error in the query using die(mysql_error()); after the query.
Very Important
You should NOT use md5 to hash a password, it is very vulnerable and insecure. Use bcrypt instead. Also you shouldn't use the mysql_* functions, as they are deprecated, use mysqli instead
Well, there are a few things that i would recommend.
There is no use for the # symbol in the post fields: http://us3.php.net/manual/en/language.operators.errorcontrol.php
There is no point of using strip_tags for $password and $confirmpassword.
You are hashing them in md5. I recommend you to use mcrypt: http://php.net/mcrypt
$password = md5($password);
$confirmpassword = md5($confirmpassword);
In:
$queryreg = mysql_query("INSERT INTO users VALUES ('','$fullname','$username','$password','$date'");
Provide the columns name in the query, like:
$queryreg = mysql_query("INSERT INTO users (fullname, username, password, date) VALUES ('$fullname','$username','$password','$date'");
You don't need to provide blank space as id in order to let MYSQL use AUTOINCREMENT.
Check your column value type for date, you are passing it as string.
Try to resolve first your inserts to the database.
your errors
1.the connection
the connection line should be:
$db = mysql_connect("localhost", "root", "" ,"login") or trigger_error(mysql_error());
instead of:
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("login");
---summary-----keep it in one line and always declare an error where ever possible
2.the insertion into the database
first of all you should specify in which columns it should insert what
for eg.
$new_user= mysqli_query("INSERT INTO userinfo (id,firstname,lastname) VALUES ('','firstname','$lastname')");
explaination:the above code states that insert the values stored in the variable firstname & lastname into the column firstname & column lastname.The value of id is left blank because we want it to auto_increment
secondly
you should use a if....else condition to kill the script if it does not insert the data in the database
ok since you clearly know that your php extenson is mysqli the simply change mysql to mysqli note:if your connection line is in the same file and not in a different one you should include the connection variable before the sql line
for eg:
$search=mysqli_query($db,"select * from userinfo where ......
where $db is the variable that holds the connection script
I'm pretty new to PHP, but I decided to try and make a simple login page on my test website, just to see how things work. I know it's not very secure, but I'm not worrying too much about that yet. The problem I am having is when I try to login, be the username correct or not, I am redirected to the login page instantly. I don't think it is even going to the PHP script that checks the username and password or anything, since I get the same results when I use an incorrect username or password. I'm not entirely sure if this is a PHP problem or not, since the form is in HTML, so sorry if it's not.
Login Page:
<?
include"includes/head.inc";
?>
<div class="login" align="center";>
<h1>Log In</h1>
<form action="/cp/login.php" method="post">
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td>
Email
</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="password" name="password">
</td>
</tr>
</table>
<input type="submit">
</form>
</div>
<?
include"includes/footer.inc";
?>
Login.php:
<?
$username = $_POST['username'];
$password = $_POST['password'];
session_start();
include"../includes/connect.inc";
$q = "SELECT * from users where email='$username' and password='MD5($password)'";
$result = mysql_query($q, $connection) or die
("Could not execute query : $q." . mysql_error());
if (!$result) {
echo "<h1>Incorrect username or password.</h1>";
}
else {
$r = mysql_fetch_array($result);
$login_username = $r["email"];
session_register("login_username");
Header("Location: protected.php");
}
?>
Protected.php:
<?
session_start();
if ($login_username == "") {
Header("Location: ../login.php");
}
else {
include"../includes/head.inc";
include"../cp.inc";
include"../includes/footer.inc";
}
?>
I included all the files just in case they are needed, but it seems to just be looping the login page, not cycling through the others. The username and password I am entering are correct, and worked in my previous login system before I rewrote it to make it work better. I hope I'm not missing anything silly or obvious. Thanks for reading.
Something that might cause this:
session_start();
if($login_username=="") {
You're referring to something inside the session; this is how you should do that:
session_start();
if (!isset($_SESSION['login_username']) || $_SESSION['login_username']=="") {
Another small issue:
<?
$username=$_POST['username'];
$password=$_POST['password'];
session_start();
You should test the $_POST keys first before attempting to access them.
if (!isset($_POST['username'], $_POST['password'])) {
die("Invalid page request");
}
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
Last but not least, learn PDO; see also the page here that warns about continued use of mysql_ functions: http://uk.php.net/manual/en/function.mysql-connect.php