Update from URL - php

I have been working towards updating a password after a request has been sent and collected from email, the request part seems to work but when I try to update the password nothing seems to happen, my password length is set at 255, initially I checked if it was the correct id I was getting and it seems to be, when I manually run the query in easyphp adding what I want updated it seems to work, I have looked at my network response no errors are showing and checked my error logs nothing there either. Any advice would be great.
<?php
require_once'connection.php';
$userInput = new UserInput();
$userInput->trimInput();
$id = '';
if( isset( $_GET['reset'])) {
$id = $_GET['reset'];
}
header('Content-Type: application/json');
$errors = [];
if (empty($_SESSION['resetPassword'])) {
$_SESSION['resetPassword'] = 1;
}
else {
$_SESSION['resetPassword']++;
}
if($_SESSION['resetPassword'] > 3){
$errors[]= ["name"=>"username","error"=>"Too many attempts try again in 15 minutes"];
if(!isset($_SESSION["timeoutPassword"])){
$_SESSION['timeoutPassword'] = time();
};
$st = $_SESSION['timeoutPassword'] + 900;
if(time() > $st){
unset($_SESSION['resetPassword']);
unset($_SESSION['timeoutPassword']);
}
}
else {
if(filter_var($_GET['password'], FILTER_VALIDATE_REGEXP,["options"=> [ "regexp" => "/.{6,25}/"]]) === FALSE){
$errors[]= ["name"=>"password","error"=>"invalid password (6 to 25 characters)"];
}
if(!preg_match("/(?=[a-z]*[0-9])(?=[0-9]*[a-z])([a-z0-9-]+)/i",$_GET['password'])) {
$errors[]= ["name"=>"password","error"=>"Password must contain numbers and letters"];
}
if($_GET['password'] !== $_GET['repeatPassword']){
$errors[]= ["name"=>"repeatPassword","error"=>"passwords don't match"];
}
if (count($errors) === 0) {
try{
$sql = "UPDATE username SET activecode = 'Active', password = :password WHERE activecode = :reset";
$stmt = $db->prepare($sql);
$stmt->bindValue(':password', password_hash($_GET['password'], PASSWORD_DEFAULT));
$stmt->bindValue(':reset', $id);
$stmt->execute();
$stmt->rowCount();
if ( $stmt->rowCount() === 1){
echo json_encode(["success"=>"Your password has been reset"]);
exit(0);
}
}
catch(Exception $e ) {
$errors[]= ["name"=>"username","error"=>"Unable to update password"];
}
}
}
echo json_encode(["errors"=>$errors]);

Related

PHP redirecting before finish MySQL insert

I have this code on "insert.php":
if ($stmt = $GLOBALS['mysqli']->prepare("INSERT INTO table1(iduser, title, msg, anonim, ip, iduniversity) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param("issisi", $_SESSION['iduser'], $_POST['title'], $_POST['msg'], $anonim, getIP(), $_SESSION['iduniversity']);
if ($stmt->execute()) {
$idmsg = $GLOBALS['mysqli']->insert_id;
$i = 0;
$stmt2 = $GLOBALS['mysqli']->prepare("INSERT INTO tag(idmsg, tag) VALUES(?,?)");
foreach ($tags as $tag) {
if ($tag != '') {
$stmt2->bind_param("is", $idmsg, $tag);
if ($stmt2->execute()) {
$i++;
}
}
}
$stmt2->close();
$stmt->close();
mysqli_close($GLOBALS['mysqli']);
sendFile($idmsg);
header("Location: /public/watch_msg.php?idmsg=" . $idmsg);
exit();
} else {
exit("Ops! Ocorreu algum erro. COD1370");
}
} else {
exit("Ops! Ocorreu algum erro. COD1371");
}
So, everything is working fine, except that sometimes when it redirects to "watch_msg.php" the message seems not to be on the database yet. When this happens, as soon as I refresh the page, everything is there!
First thing I thought is that there could be a race-condition somewhere, but I read in another question that PHP is sequential, and as I close both statements and connection before the redirect (so that used tables should be unlocked), why i'm getting this result somethimes? What i'm doing wrong?
Also, no functions outputs anything, but "sendFile" saves an image if the user sends one, so headers should be fine (it also gives me the error when I comment the function).
Code on watch_msg:
$msg = NULL;
$tags = NULL;
$coments = NULL;
$data_high = date("Y-m-d H:i:s");
$iduser;
if ($loggedin) { //If logged in
$idmsg = filter_input(INPUT_GET, 'idmsg', FILTER_SANITIZE_STRING);
$iduser = $_SESSION['iduser'];
$query = "SELECT * FROM table1 WHERE iduser = ? AND idmsg = ? AND datemsg < ?";
$stmt = $GLOBALS['mysqli']->prepare($query);
$stmt->bind_param("iis", $iduser, $idmsg, $data_high);
if ($stmt->execute()) {
$msg = mysqli_fetch_assoc($stmt->get_result());
if ($msg === NULL) {
exit('This message doesn\'t exists');
}
...
} else {
echo "Error.";
}
}

Php login via email in mysql

Hi guys i have loging via email , and i want to add login via email.
When i add (login=:login OR) in sql query, i got bug you can login by any password.
Here some code :
public function login($login,$upass)
{
try {
$stmt = $this->conn->prepare("SELECT * FROM Klient WHERE login=:login OR email=:login LIMIT 1");
$stmt->execute(array(':login' => $login));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() == 1) {
if ($userRow['userStatus'] == "Y") {
if ($userRow['haslo'] = $upass) {
$_SESSION['userSession'] = $userRow['idKlient'];
return true;
} else {
header("Location: index.php?error");
exit;
}
} else {
header("Location: index.php?inactive");
exit;
}
} else {
header("Location: index.php?error");
exit;
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
EDIT:
i'm trying to add password_hash(), but when i login in my website is going down.
i tried to add password hash but my website is going down when i login in.
public function login($login, $upass)
{
try {
$stmt = $this->conn->prepare("SELECT * FROM Klient WHERE login=:user_login OR email=:user_login");
$stmt->execute(array(":user_login" => $login));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() == 1) {
if ($userRow['userStatus'] == "Y") {
if ( password_verify($upass, $userRow['haslo'])) {
$_SESSION['userSession'] = $userRow['idKlient'];
return true;
} else {
header("Location: index.php?error");
exit;
}
} else {
header("Location: index.php?inactive");
exit;
}
} else {
header("Location: index.php?error");
exit;
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
You need to change here add param for email also
$stmt->execute(array(':login' => $login,':email' => $login));
if ($userRow['haslo'] = $upass) {
You're giving $userRow['haslo'] the password, you need to check it with ===
And please, use hashing not plain-text, check password_hash
You could try something like:
$stmt = $this->conn->prepare("SELECT * FROM Klient WHERE login = :login: OR email = :email: LIMIT 1")
$stmt->execute(array('login' => $login, 'email' => $upass));
And my suggestion is that you check variables before exec, something like:
if(isset($login) && isset($upass)) {
...
}
Hope this helps, cheers!
Do not try to use the same named parameter twice in a single SQL statement, for example
<?php
$sql = 'SELECT * FROM some_table WHERE some_value > :value OR some_value < :value';
$stmt = $dbh->prepare($sql);
$stmt->execute( array( ':value' => 3 ) );
?>
...this will return no rows and no error -- you must use each parameter once and only once. Apparently this is expected behavior (according to this bug report: http://bugs.php.net/bug.php?id=33886) because of portability issues.

PHP API returning wrong response for android app

I am creating a API for android developer in PHP in which he want to delete some values from database and want to show a message after that.
Now the problem is this data is deleting successfully but this API always shows else part message after complete the process. If I remove the else part its return the null which crash the android app. So I just want to give a proper json message to the android developer
Here is the code which I am trying
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1)
{
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_count as $table_count)
{
$user_count = mysql_query("select * from $table_count where user_name = '$user_name'");
$total_user_count = mysql_num_rows($user_count);
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
}
}
I know there is something wrong with this logic. But I need expert advise where my logic is wrong and what I have to do make it success
Problem with your original code, is that you are setting success/failure inside the loop. One of the four table may/may not contain the username. And if the last table don't have that, then as per your logic you are getting "record not found" even if previous iteration of the loop deleted data from the tables where username exists.
<?php
$conn = mysqli_connect(.....);
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1) {
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
$userHistoryDeleted = 0;
foreach($tables_count as $table_count) {
//if history is found, then it will be deleted otherwise not
mysql_query("delete from $table_count where user_name = '$user_name'");
if(mysqli_affected_rows($conn)) {
$userHistoryDeleted = 1;
}
}
$msg = 'Record Not Found!';
if($userHistoryDeleted) {
$msg = 'Clear Successfully All History!';
}
$response['success'] = $userHistoryDeleted;
$response['user']['error_msg'] = $msg;
}
Change your code :
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
to this one
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
}
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}

PHP Button limit

Okay I have a problem here. Whether users column "checked" is 1 or 0 it ignores the IF statement and still adding 10000 points. Can somebody explain me why ?
foreach ($users as $u) {
if (isset($username) . $u['checked'] == 0) {
foreach ($points as $p) {
$username = $_SESSION['username'];
$p = $p['points'] + 10000;
try {
$q = $pdo->prepare("UPDATE users SET points = ?, checked = ? WHERE username = ?");
$q->execute(array($p, $ten, $username));
} catch (Exception $e) {
echo $e->getMessage();
die();
}
header("Location: index.php");
}
} else {
echo "Nothing";
}
}
Try using a more explicit if statement like
if(isset($username) && $u['checked'] == 0)
Also as Bery said in the comments, isn't $username supposed to be $u?

Passing variables out of a function

So, every page looks for 4 things, $e,$w,$n and $success.
$e is an array where errors are set. In every function errors are set with $e[] = 'error message';
Same for $w that is for warnings, $n for notices and the obvious for $success.
Now if the function has errors it shouldn't go ahead with the operations it's set to do, where as notices and warning are just for informing purposes.
The pages check for all of those and display each one in closeable coloured divs.
so here is my question...
I don't think this will work as expected.
Will this return the variable itself, or does this just show the contents of the variables when the function is run?
function add_member()
{
global $dbh;
if (!isset($_POST['username'],$_POST['password'],$_POST['email'])) {
$e[] = 'We need the minimum of a username and password to add a new user';
}
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (!preg_match($regex, $_POST['email'])) {
$e[] 'The email address is wrong';
}
$stmt = $dbh->prepare("SELECT `username` FROM `1_members` WHERE `username`=? LIMIT 1");
$username = strtolower($_POST['username']);
$username = trim($username);
$stmt->bindValue(1, $username, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount()) {
$e[] = 'That username is already in use';
}
if (($_POST['password']) !== ($_POST['vpassword'])) {
$e[] = 'The passwords did not match.';
}
if (strlen($_POST['username']) <= '3') {
$e[] = 'Username too short - needs to be 4 or more chars.';
}
if (strlen($_POST['password']) <='5'){
$e[] = 'password not long enough, please make it 6 chars.';
}
if (!isset($_POST['vpassword'])) {
$w[] = 'Warning: You didn\'t verify the password. Incase of typo the password was ['..']';
}
if (!isset($_POST['email'])) {
$w[] = 'Warning: You didn\'t enter an email address the password. This member will not get email alerts without an email address.';
}
if ($e) {
return $e;
}
else {
$password = trim($_POST['password']);
$options = ['cost' => 12,];
$password = password_hash($password, PASSWORD_BCRYPT, $options);
$email = trim($_POST['email']);
$stmt = $dbh->prepare("INSERT INTO `1_members` (`username`, `password`, `email`) VALUES(?,?,?)");
$stmt->bindValue(1,$username,PDO::PARAM_STR);
$stmt->bindValue(2,$password,PDO::PARAM_STR);
$stmt->bindValue(3,$email,PDO::PARAM_STR);
$stmt->execute()
$success = 'added member '.$username.'';
if (isset($w)) {
return $w;
}
if (isset($n)) {
return $n
}
return $success;
}
}
This function will return possibly 4 different things, and unless there is a massive error somewhere in the database setup, it shouldn't display anything. Instead, it'll return variables:
$e (array) if account can't be created due to a validation error or duplication
$w (array) if there is a warning after account creation
$n (array) if there is a notice after creation -- except that never happens. $n is not declared.
$success (string) otherwise
This function is all over the place - unpredictable. Whatever calls it will have to do a bunch of logic to deal with its return. Possibly a better way to do this is to return a richer construct. For example:
function add_member() {
$return_info = array(
"errors" => array(),
"warnings" => array(),
"notices" => array(),
"created" => false # sometimes a simple true / false is good enough
);
// do validation as before
// ...
if( $_POST['password'] !== $_POST['vpassword'] ) {
$return_info["errors"][] = "Passwords didn't match.";
}
// if account IS created, just flip the created switch
// ...
$try_inserting = $stmt->execute();
if( $try_inserting ) { # replace this with an actual error check
$return_info["created"] = true;
}
// now everything comes back: creation status, warnings, errors, etc...
return( $return_info );
}
This function refactoring standardizes all of its returns, so that it's predictable in dealing with it. You can do simple statements like:
$attempt = add_member();
if( $attempt["created"] === true ) {
echo "added member!";
}
Whatever is calling this can also do very simple checks for errors, warnings, notices:
if( !empty($attempt["errors"]) ) {
// display the errors
}

Categories