PHP IF body and ELSE body both executing - php

This is a very strange problem.. I've looked all around for a solution..
Here is my code. It is part of an account settings page on a website I am creating. The code has to do with the user changing his first name:
// if there are post vars, user has changed something
if($_POST) {
if(isset($_POST['firstname'])) {
$firstname = trim($_POST['firstname']);
if(strlen($firstname) < 2 || strlen($firstname) > 15) {
$msg = "<span class='errmsg'>Could not complete your request. First name must be between 2 and 15 characters.</span>";
}
else {
// connect to db
require_once('modules/config.php');
// update table
$query = sprintf("UPDATE Users SET FirstName = '%s' WHERE Email = '%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($_SESSION['email']));
mysql_query($query);
// set success message
$msg = "<span class='sucmsg'>First name successfully changed.</span>";
// reset the firstname session var
$_SESSION['firstname'] = $firstname;
}
}
}
EDIT: Added the closing brace that Dagon mentioned.

I think you're missing } at the end.
else {
is actually closing:
if(isset($_POST['firstname'])) {
instead of
if(strlen($firstname) < 2 || strlen($firstname) > 15) {

I don't know whether this will solve your problem, try it...
if(in_array(strlen($firstname), range(2, 15)))

Related

Why is my else condition being executed twice?

I went through this login system with multi-users. It's working fine since it doesn't allow my status_id users '2' to login (inactive status), but when this happens I get the echo message twice on screen.
What am I doing wrong?
I want to validate both user/password, user_type (admin/user) and user_status (1-active, 2-inactive).
<?php
include 'database/connect.php';
if (isset($_POST["submit"])) {
$email = $_POST["txtemail"];
$pass = $_POST["txtpass"];
$query = mysqli_query($con, "SELECT user_email,user_password,user_type_id, status_id FROM user");
while ($row = mysqli_fetch_array($query)) {
$db_email = $row["user_email"];
$db_pass = $row["user_password"];
$db_type = $row["user_type_id"];
$db_user_status = $row['status_id'];
if ($email == $db_email && $pass == $db_pass && $db_user_status == '1') {
session_start();
$_SESSION["email"] = $db_email;
$_SESSION["type"] = $db_type;
if ($_SESSION["type"] == '1') {
header("Location:admin/home_admin.php");
} else {
header("Location:user/home_user.php");
}
} else {
echo "Ups. Algo de errado aconteceu.";
}
}
}
Looking at your code, if the conditions specified inside the loop fails then the else will execute.
So if your user table holds 3 records and all 3 records doesn't satisfy the condition specified it will execute else statement and 3 times.
This might be the reason.
Well it looks like you are looping through every user inside your user table, so the posted email and password can only be right for one user and for the rest of them your program will go through the else statement

Login count in php

I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.php');
}
}
?>
`

How do I display the error messages in signup form?

How do I display the error messages (you did not complete all of the required fields and this username is already taken) without going to a new page to display them (like using die instead of echo), while still not continuing the process? In other words, I don't want the user to be sent to a new page to see "you did not...," I want the error to show either below or above the on this page, but I want the error message to disallow the data from being added to the database(the next command, or a couple commands down).
//if submit is clicked
if (isset($_POST['submit'])) {
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
} ?>
//if submit is clicked
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
elseif(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
else{
echo "code to submit values to database"
}
} ?>
Maybe you wanna use something like this javascript function to check for empty fields and not matching passwords (change variable names accordingly please as I took this from a little project I made):
function signup(){ //Call it on button click
var u = _("username").value;
var e = _("emailAddress").value;
var p1 = _("password").value;
var p2 = _("passwordConfirm").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Please, fill in every single field in the form...";
} else if(p1 != p2){
status.innerHTML = "The passwords do not match...";
} else if( _("terms").style.display == "none"){
status.innerHTML = "You must view our Terms & Conditions in order to proceed...";
} else { } //Redirect to a page or use Ajax to do other functions your site may need.
Notice var status = _("status");, this is where the messages will be shown on your page, you may want to add something like <span id="status"></span> to your HTML code.
Similarly to check for an available username or email on your database, you can try the following Ajax and Javascript function:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_con.php"); //database connection file
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']); //checks the texfield doesnt have any funny unusual characters
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1"; //change table name accordingly to yours
$query = mysqli_query($db_con, $sql);
$uname_check = mysqli_num_rows($query);
//This is just some extra conditions if you wish to add
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
//This if statement will check if the username is ok to use or is taken.
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
//////////// Javascript function, these can be on the same php file.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("usernamesats").innerHTML = 'Checking Availability...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("usernamesats").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Notice that for you to see the warnings your username textfield must look like this: <label>Username:</label>
<input id="username" type="Text" onBlur="checkusername()" maxlength="16">
This onBlur="checkusername()" will call the JS function.
and also add somewhere after the texfield this <span id="usernamesats"></span> to display the warnings. This should all do the trick. Oh and you may want to add the Ajax file:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
somewhere in your js folder (if you have one).
Sorry if this may be a bit long and confusing but it did the work for me, I'm sure there are other ways to do it, just thought these seemed easier to understand for me.
Check this website http://www.developphp.com/list_php_video.php for more info, there are some great tutorials there to get you started with PHP and MySQL, most of this code was done following the tutorials there :) Good Luck!

Failed to assign variable taken from database to json array

I try to get the data from database to display data via ajax but failed to worked. It's partially working because data from mysql make this thing failed to function.
Here is my funds_transfer_backend.php page. This page will assign variable to json array.
session_start();
if(!isset($_SESSION['myusername']))
{
header("Location: ../index.html");
die();
}
include("../connect.php");
$myusername = $_SESSION['myusername'];
$sql="SELECT client_id FROM `client` WHERE username='$myusername'";
$result=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_row($result)){
$id = $row['0'];
}
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
//echo "Please complete the form!";
$response = -1;
}
else {
// check account number exist
$query2 = "SELECT 1 FROM account WHERE id='$to_account_num' LIMIT 1";
if (mysqli_num_rows(mysqli_query($conn, $query2))!=1) {
//echo "Recipient account number is invalid!";
$response = -2;
}
else {
$query2 = "SELECT client.name, client.email FROM account JOIN client USING (client_id) WHERE account.id = '$to_account_num' LIMIT 1";
$result=mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$email = $row['email'];
}
$response = 1;
}
} // check account num else bracket
$display = array('response' => $response, 'name' => $name);
echo json_encode($display);
However if I remove 'name' => $name from array the #stage div will trigger like image below:
Here is my funds_transfer.php page
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
...other code goes here
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<div id="confirm" style="background-color:#FF7800; padding-left:20px; color: white;"></div>
I try to check the data from db whether it exist using manual form method="post" and I can see the name being echo. Any help is appreciated and thanks in advance.
When your response is -1, your $name variable is undefined. So php could show a warning (depending on your settings) and you are trying to add an undefined variable to your array. This will invalidate your output / json.
You can set for example:
$name = '';
at the start of your script or check whether the variable is set with isset($name) before you try to use it to avoid these problems.
There are of course other solutions, like outputting your -1 directly and exiting the script there.
I always initialize my variables.
$myusername = isset($_SESSION['myusername']) ? $_SESSION['myusername'] : false;
Then you can safely do:
if ($myusername) {} without throwing warnings.
I do this weather I get my data from a db, post/get/session or json/ajax.
It takes a little extra time upfront but removes dozens of errors in the back end so you net more time.

Returning a variable that has to be updated from a function, not returning?

There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}

Categories