PHP: how to use a variable from one if statement in another - php

Separately the forms are ok, but combined.... not really. The struggle is that i can't access the variable $name from the first if statement in the second.
Error : Undefined variable: name
html:
<form method="POST" enctype="multipart/form-data" id="form1">
Name: <input type="text" name="name"><br>
Pass: <input type="password" name="pass"><br>
<input type="submit" name="submit1" value="Влез">
</form>
<form method="POST" enctype="multipart/form-data" id="form2">
We need some more information about you<br>
Please enter your e-mail: <input type="text" name="email"><br>
Please enter a new Password <input type="password" name="pass1" ><br>
Plese reenter tour new password <input type="password" name="pass2"><br>
<input type="submit" name="submit2" value="Save">
</form>
php:
require('config.php');
?><script type="text/javascript">document.getElementById("form2").style.display="none"; </script><?php
if(isset($_POST['submit1']))
{
$name = mysql_escape_string($_POST['name']);
$pass = mysql_escape_string($_POST['pass']);
//chek if the username and password are correct
$check = mysql_query("SELECT * FROM test WHERE name = '$name' AND pass = '$pass'");
if(mysql_num_rows($check) >= 1)
{
?>
<script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="block";
</script>
<?php
exit();
}
else echo "<h1><font color='red'> Грешно Име или Парола</font></h1>";
}
if(isset($_POST['submit2']))
{
$email = mysql_escape_string($_POST['email']);
$pass1 = mysql_escape_string($_POST['pass1']);
$pass2 = mysql_escape_string($_POST['pass2']);
$checkpass = mysql_query("SELECT * FROM test WHERE pass = '$pass1'")or die(mysql_error());
if($pass1 != $pass2){
echo "Passwords do not Match";
}
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Wrong email format";
}
elseif (mysql_num_rows($checkpass)>=1) {
echo "Password already taken";
}
elseif (empty($pass1) || empty($pass2) || empty($email)) {
echo "Not all fields are filled";
}
else
{
//put in DB
mysql_query("UPDATE test SET pass='$pass1' WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE test SET email='$email' WHERE name='$name'") or die(mysql_error());
?><script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="none";
</script><?php
echo "<h1><font color='green'>Registration successful</font></h1>";
}
}
P.S don't mind the java script inside and no, i can't combine the forms!

The reason you cannot access the $name variable inside your second if statement is due to the form structure. You have two distinct forms and only one of them can be submitted at any time. Your if statements can therefore only handle one of the forms, either submit1or submit2. The simplest solution could be to combine the two forms and your if statements. You would then need more if statements to check what information has been provided and should be processed.
Bonus
One of your forms has names not in English. It is good practice to write code using the English language as other developers not familiar with your language are to read your code (as we do now). This also helps others if they want to research your implementations on the internet.
I would also recommend checking up on separation of concerns. As of now your code mixes presentation logic and domain logic (the action processing stuff). This may seem overwhelming, but I can assure you that it is an investment you will love in the future.
Happy coding!

As noted in the comments, you have an issue where only one function will be called, if you want the info from submit1 to be accessible in submit2, then change up your if statements.
if(isset($_POST['submit1']) || isset($_POST['submit1']))
{
//submit1 code here
if(isset($_POST['submit2']))
{
//submit2 code here
}
}
This way, submit1 data will run for both submit buttons, and submit2 will be able to make use of the data as needed.

i tried passing the variable with session_start() like this:
if(isset($_POST['submit1']))
{
$name = mysql_escape_string($_POST['name']);
session_start();
$_SESSION["a"] = $name;
$pass = mysql_escape_string($_POST['pass']);
//chek if the username and password are correct
$check = mysql_query("SELECT * FROM test WHERE name = '$name' AND pass = '$pass'");
if(mysql_num_rows($check) >= 1)
{
?><script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="block";
</script><?php
}
else echo "<h1><font color='red'> Грешно Име или Парола</font></h1>";
}
if(isset($_POST['submit2']))
{
session_start();
$name = $_SESSION["a"];
$email = mysql_escape_string($_POST['email']);
$pass1 = mysql_escape_string($_POST['pass1']);
$pass2 = mysql_escape_string($_POST['pass2']);
$checkpass = mysql_query("SELECT * FROM test WHERE pass = '$pass1'")or die(mysql_error());
if($pass1 != $pass2){
echo "Passwords do not Match";
}
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Wrong email format";
}
elseif (mysql_num_rows($checkpass)>=1) {
echo "Password already taken";
}
elseif (empty($pass1) || empty($pass2) || empty($email)) {
echo "Not all fields are filled";
}
else
{
//put in DB
mysql_query("UPDATE test SET pass='$pass1' WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE test SET email='$email' WHERE name='$name'") or die(mysql_error());
?><script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="none";
</script><?php
echo "<h1><font color='green'>Registration successful</font></h1>";
}
}

Related

PHP login file is not working. Continues to return to the login page and not user profile

Here is the full code:
<?php
session_start();
session_regenerate_id(true);
require_once('connect.php');
require_once "lib.php";
require_once "utils.php";
$EmailAddress = mysqli_real_escape_string($link,htmlentities($_POST['EmailAddress']));
$Password = mysqli_real_escape_string($link,htmlentities($_POST['Password']));
$Fname = mysqli_real_escape_string($link,htmlentities($_POST['Fname']));
function login($result,$EmailAddress,$Password)
{
if($result)
{
if(mysqli_num_rows($result) == 1)
{
$email_exists = true;
$pass_exists = true;
if($pass_exists = true && $email_exists = true)
{
$_SESSION['active']=true;
$_SESSION['EmailAddress']=$EmailAddress;
//$_SESSION['Password']=$Password;
header("Location: myIndex.php");
exit();
}
}
else
echo "<div id='error'><h4>Error: Incorrect Password or Email</h4></div>";
}
}
function redirect_if_active()
{
header("Location: myIndex.php");
exit();
}
if(isset($_SESSION['active']) && $_SESSION['active'] ===true)
{
redirect_if_active();
}
// only processes login information if the submit button has been clicked
if (isset($_POST['submit'])) {
$sql="SELECT * FROM users WHERE EmailAddress ='$_POST[EmailAddress]' AND
Password ='$_POST[Password]'";
$result = mysqli_query($link,$sql);
login($result,$EmailAddress,$Password);
}
if(isset($_POST['signup'])){
header("Location: register.php");
exit();
}
?>
My guess is that the error is where the $sql = SELECT * FROM users WHERE but I', not entirely sure. I'll input the Email and the password, but it continues to return me to the login page. I'm not sure why it's doing that, but it needs to go to the Profile page once the user has logged in.
$link = "somethingrelatedtoyourdb";
$EmailAddress = $_POST['EmailAddress'];
$Password = $_POST['Password'];
//$Fname = $_POST['Fname']; THIS IS NEVER POSTED
echo "<pre>";
print_r($_POST);
echo "</pre>";
function login($result,$EmailAddress,$Password)
{
if($result)
{
if(($result) == true)//TRUE AGAIN
{
//THIS MAKES NO SENSE
// $email_exists = true;
// $pass_exists = true;
//if($pass_exists = true && $email_exists = true)
// {
$_SESSION['active'] == true;
$_SESSION['EmailAddress'] == $EmailAddress;
//$_SESSION['Password']=$Password;
header("Location: myIndex.php");
exit();
// }
}
else
echo "<div id='error'><h4>Error: Incorrect Password or Email</h4></div>";
}
}
function redirect_if_active()
{
header("Location: myIndex.php");
exit();
}
if(isset($_SESSION['active']) && $_SESSION['active'] ===true)
{
redirect_if_active();
}
// only processes login information if the submit button has been clicked
if (isset($_POST['submit'])) {
$sql="SELECT * FROM users WHERE EmailAddress ='$EmailAddress' AND
Password ='$Password'";
print_r($sql);
// $result = mysqli_query($link,$sql); Ill make this true for a moment
$result = true;
login($result,$EmailAddress,$Password);
}
if(isset($_POST['signup'])){
header("Location: register.php");
exit();
}
?>
<html>
<head></head>
<body>
<div id='form'>
<form action='example.php' method='POST'>
<div id='email'>Email:</div>
<div id='email2'>
<input name='EmailAddress' type='email'/>
<br>
</div> Password: <input name='Password' type='password'/>
<br>
<input class="submit" name='submit' type='submit' value='Login'/>
<input class="submit2" name='signup' type='submit' value='SignUp!'/> </form>
</body></html>
You have quite a few issues that I see right off the bat
In your sql query this $_POST[Password] should be $_POST['Password']. Same thing with the email address. This might fix your query, however please note, passing in raw post data to mysql is a big security problem. You are already setting these post params as escaped variables. You could use those, but you should look at prepared statements to keep yourself safe.
This block, has an error, and also doesn't make sense
$email_exists = true;
$pass_exists = true;
if($pass_exists = true && $email_exists = true)
It should be
if($pass_exists == true && $email_exists == true)
Or better yet
if($pass_exists && $email_exists)
However since you are explicitly setting both of these vars to true right before checking if they are true, then this will always be true.

HTML FORM + PHP: form action to remain on same page as login

at the moment my form links to a new page with all of my php code on it. I would like for all of the code to be executed on the same page as it does in this tutorial: http://www.w3schools.com/php/php_form_url_email.asp
I'm having some difficulty understanding exactly how this tutorial manages it. I was thinking maybe it would be possible to store my add.php code in a function and then call it with form action. Is this possible? If not what would be the best way to go about this?
here is my form code:
<form action="add.php" method="post">
<p>
Username: <input type="text" name="Username"><br>
Email: <input type="text" name="Email"><br>
Password: <input type="password" name="Password"><br>
Confirm Password: <input type="password" name="ConfirmPass">
</p>
<p>
<input type="submit">
</p>
</form>
and here is my add.php page:
<?php
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
$ConfirmPass = $_POST['ConfirmPass'];
$safeUsername = SQLite3::escapeString($Username);
$safePassword = SQLite3::escapeString($Password);
$safeEmail = SQLite3::escapeString($Email);
$safeConfirmPass = SQLite3::escapeString($ConfirmPass);
$hostName = explode('#', $Email);
$database = new PDO('sqlite:maindb.db');
$sql = "SELECT * FROM users WHERE Username = ?";
$result = $database->prepare($sql);
$result->bindParam(1, $safeUsername);
$result->execute();
if($result->fetch()) {
echo "Username " . $safeUsername . " already exists";
}
else {
if (filter_var($safeEmail, FILTER_VALIDATE_EMAIL) && checkdnsrr($hostName[1]) && !empty($safeEmail)) {
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$safeEmail)) {
if (!empty($safeUsername) && (preg_match("/^[a-zA-Z ]*$/",$safeUsername)) && !empty($safeUsername)) {
if ($safePassword == $safeConfirmPass && !empty($safePassword)) {
echo $Username . " was successfully added to the database.";
$stm = "INSERT INTO users(Username, Password, Email) VALUES(?,?,?)";
$stmt = $database->prepare($stm);
$stmt->bindParam(1, $safeUsername);
$stmt->bindParam(2, $safePassword);
$stmt->bindParam(3, $safeEmail);
$stmt->execute();
$database = null;
}
else {echo "Passwords do not match"; }
}
else {echo "Invalid Username.";}
}
else {echo "Invalid e-mail address.";}
}
else {echo "Invalid e-mail address.";}
}
?>
Thanks for the help! I appreciate it.
In the tutorial you linked they use
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//your stuff here
//save your form values etc.
}
to check if there has been a post to your page (this can be any page so also the same page). Basically this will check if a POST request has been send to this page. Which will if you use a from with a post method.
As an extra test they also put stuff like
if (empty($_POST["name"])) {
//name is empty print error!
}
in it to check if a field is empty or not.
all you gotta do now is change your action to the same page.

PHP Login Script - The password is incorrect but the user exists?

My username & password is correct but when i run this script and when i test my login i keep getting = "The password is incorrect but the user exists". Can anyone help?
Here is my Script;
<?php
include ("db.php");
if (isset($_SESSION['loggedin']) == "1") {
echo "You are already logged in. Go home";
} else {
if (isset($_POST['login'])) {
$username = strip_tags(mysql_real_escape_string($_POST['username']));
$password = md5(strip_tags(mysql_real_escape_string($_POST['password'])));
if (empty($username) || empty($password)) {
echo "Enter both fields.";
} else {
$userQ = mysql_query("SELECT * FROM users WHERE `username` = '{$username}'");
if (mysql_num_rows($userQ) == 0) {
echo "This user does not exist.";
} else {
$userA = mysql_fetch_array($userQ);
if ($password !== $userA["password"]) {
echo "The password is incorrect but the user exists.";
} else {
$_SESSION['loggedin'] = "1";
header("Location: index.php");
exit;
}
}
}
}
?>
<form method="post">
Username: <input type="text" name="username" maxlength="25" /><br />
Password: <input type="password" name="password" maxlength="20" /><br />
<input type="submit" name="login" value="Login" />
</form>
<?php
}
?>
Any Help would be great, i have just started to learn php and not sure if this code is correct.
$userA = mysql_fetch_array( $userQ ); this will return array. You need to iterate it and return associative array to check each record like;
.....
while ($row = mysql_fetch_assoc( $userQ)) {
$userA = $row["password"];
}
if ( $password !== $userA["password"] ) {
echo "The password is incorrect but the user exists.";
}
.....
There is iteration in above code, but it will always have one result, because username is unique(I think)
I think you may have multiple users with the same username. Check your database for this. If not, then try to remove mysql_real_escape_string() before using md5 on it.
On a side note, if you are starting to leran PHP then don't use mysql functions anymore. Try to use mysqli or PDO extensions. Mysql functions are deprecated as of PHP 5.5.

Admin and normal user login system PHP MYSQL

I have some code which attempts to check whether a user is an admin or normal user, and then compares it against an SQL table to determine which page opens up (admin page vs normal user page).
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$admin = $_POST['admin'];
if( $user == "" || $pass == "")
{
echo '<div id ="errormsg">Please fill in all fields</div>';
}
else
{
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user'
and password = '$pass' and admin = '$admin' ") or die ("Can't query the database");
$count = mysqli_num_rows($query);
if($count == 1)
{
if ($admin == 1)
{
$_SESSION['username'] = $user;
header("location: admin.php");
}
else if ($admin == 0)
{
$_SESSION['username'] = $user;
header("location: users.php");
}
else
{
echo '<div id="errormsg">No matches, try again</div>';
}
}
}
}
There are no errors, however the admin value doesn't seem to make a difference and by default opens 'users.php' everytime. The $admin is a checkbox with value '1' when checked, the logic being to check this value against the database. Can anyone help solve this issue?
This is the html form:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<label class="login">Username:</label><input type="text" name="user" /><br />
<label class="login">Password:</label><input type="password" name="pass" /><br />
<label class="login">Admin?:</label><input type="checkbox" value="1" name="admin" /><br/>
<input type="submit" name="submit" value="Login" />
</fieldset>
</form
The error is how you check if user is admin:
if ($admin == 1)
Replace this with:
if (isset($admin))
Also, you need to exit or die after using header():
if (isset($admin))
{
$_SESSION['username'] = $user;
header("location: admin.php");
exit;
} else {
$_SESSION['username'] = $user;
header("location: users.php");
exit;
}
Firstly, you need to have a read up on mysql escaping / best practices. Your script here is vulnerable to SQL injection.
There are plenty of good resources online, or search SQL injection PHP on here, to help explain this to you if unsure.
How is the $_POST['admin'] value set, can you post an example of your form here?
I'm guessing that the value being sent in isn't matching your conditions above so this is likely to be the cause.
It could be as simple as changing your if statement to be === rather than ==, but to be sure I'd need to see your form's source core.
Try this one with some correction in database query-
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '".$user."'' and password = '".$pass."''") or die ("Can't query the database");
Hope it will help.

change password in mysql table?

Hi im having a problem with my change password script. im trying to allow a user to change their password in the mysql table 'ptb_users.password' it's suppose to store this as md5.
When i hit submit in my form, i'm assuming it goes to changepassword.php but the page is just blank, nothing is echoed and im not getting any errors.
Can someone please show me where im going wrong with this, thanks
Here's my form:
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php");
require('includes/checks.php');
?>
<?php
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form method="post" action="includes/changepassword.php" name="form1" id="form1">
<input type="password" name="oldpassword" id="password" class="subject" placeholder="Old Password">
<input type="password" name="oldpassword" id="password" class="message" placeholder="Old Password">
<input type="password" name="newpassword" id="newpassword" class="message" placeholder="New Password">
<input type="image" src="assets/img/icons/loginarrow1.png" name="submit" id="submit" class="submit">
</form>
And here's my mysql function:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
?>
<?php
session_start();
include '_config/connection.php';
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']."");
if(!$result)
{
echo "The username you entered does not exist";
}
else
if($password!= mysql_result($result, 0))
{
echo "";
}
if($newpassword=$confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm new password fields must be the same";
}
?>
if(isset($_POST['submit']))
{
$email = $_POST['email'];
echo $newpassword = ($_POST['password1']);
echo $confirmpasssword = ($_POST['password2']);
if($newpassword=$confirmpassword)
{
echo $newpassword = md5($newpassword);
echo $result = mysql_query("UPDATE users SET password='$newpassword' WHERE email='$email' ");
}
if($result)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm password fields must be the same";
}
}
can anyone tell me is this correct coding, to change password and store in mysqldb.
first you do not check the old password properly (md5 stored, plaintext compare... won't work)
second you do not have any confirmpassword set, so this wont work too
what would work is:
$password = md5($_POST['password']);
$newpassword = md5($_POST['newpassword']);
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']." AND password = '".$password."'");
if(!$result)
{
echo "The username you entered does not exist or old password didn't match";
}
else
{
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
There are many things wrong with this.
Let's get the basics out of the way first:
Don't use mysql_ functions. switch to PDO or mysqli while you can.
md5 is in its dying days. See this answer - understandably, you may be so entrenched in md5 you can't get out without pestering every user to update their pw.
Your problem then is this:
if($password!= mysql_result($result, 0))
You're not comparing against a md5 stored hash. It should be something like this:
if(md5($password) != mysql_result($result, 0))
and this:
if($newpassword=$confirmnewpassword)
is just reassigning a variable. I think you wanted
if($newpassword == $confirmnewpassword)
As for output, you may want to consider the if/else structures you're using here. This could be cleaned up significantly and all together looks out of date. Maybe just an opinion.
If you have a specific thing to hone in on, let me know and I may update.
EDIT
This whole block should be cleaned. Something like this may help:
if(!$result)
{
echo "The username you entered does not exist";
}
else
{
if(md5($password) != mysql_result($result, 0))
{
echo "Current PW does not match what we have";
}
else
{
if($newpassword == $confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."") or die(mysql_error());
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
}
else
{
echo "The new password and confirm new password fields must be the same";
}
}
}

Categories