PHP Button limit - php

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?

Related

How to change a variable according to the user, administrator

I have a user table with a column called id_role. All new users are assigned a id_role value of 3 by default.
Any users that need higher level privileges, I manually update them to 2 for administrator and 1 for super_admin.
The problem is that id_role is still worth the value of the last registered and I do not understand why.
If I do not add a new user id_role, it will always be 1 and everyone will log in superadmin, if I am adding a new user, id_role will be 3 and everyone (even the admin) will log in as a basic user.
Here is my basic code :
<?php
session_start();
$Nom = $_POST["Nom"];
$mdp = $_POST["mdp"];
//$id_role = $_POST["id_role"];
try{
$bdd = new PDO('mysql:host=localhost;dbname=azer', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(Exception $e) {
die("acces imlpossible");
}
$st = $bdd->query("SELECT * FROM membre WHERE Nom='".$Nom."'")->fetch();
$mangetesmorts = $bdd->query("SELECT * FROM membre WHERE id_role");
if (password_verify($mdp, $st['mdp'])) {
$_SESSION['Nom'] = $Nom;
$_SESSION['activite'] = $st['activite']; //$_SESSION['id_role'] = $mangetesmorts['id_role'];
//var_dump($_SESSION['id_role']);
//print_r($id_role);
while ($donne = $mangetesmorts->fetch()) {
if ($_SESSION['activite'] =='cricket') {
header("Location: cricket.php");
} elseif ($_SESSION['activite'] == 'foot') {
header("Location: foot.php");
} elseif (($donne['id_role'] == 2)) {
header("Location: admin.php");
} elseif ($donne['id_role'] == 1) {
header("Location: admin_super.php");
} else {
header("Location: index2.php");}
}
}
and that's what I tried after:
<?php
session_start();
$Nom = $_POST["Nom"];
$mdp = $_POST["mdp"];
//$id_role = $_POST["id_role"];
try{
$bdd = new PDO('mysql:host=localhost;dbname=azer', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (Exception $e) {
die("acces imlpossible");
}
$st = $bdd->query("SELECT * FROM membre WHERE Nom='".$Nom."'")->fetch();
$mangetesmorts = $bdd->query("SELECT * FROM membre WHERE id_role");
if (password_verify($mdp, $st['mdp'])) {
$_SESSION['Nom'] = $Nom;
$_SESSION['activite'] = $st['activite'];
//$_SESSION['id_role'] = $mangetesmorts['id_role'];
//var_dump($_SESSION['id_role']);
//print_r($id_role);
while ($donne = $mangetesmorts->fetch()) {
$_SESSION['id_role']=$donne['id_role'];
if ($_SESSION['activite'] =='cricket') {
header("Location: cricket.php");
} elseif ($_SESSION['activite'] == 'foot') {
header("Location: foot.php");
} elseif ($_SESSION['id_role'] == 2) {
header("Location: admin.php");
} elseif ($_SESSION['id_role'] == 1) {
header("Location: admin_super.php");
} else {
header("Location: index2.php");
}
}
}
Your block of conditional redirects is based on the second query which does not reference the user that has successfully logged in. (if that query works at all).
In other words, while ($donne = $mangetesmorts->fetch()) { is going to pull all rows from your table, then iterate the only the first row because the redirect will end the script.
Because your first SELECT query is returning the full row of data for the user as the array $st just use that to determine the redirect.
if (in_array($st['activite'], ['cricket', 'foot'])) {
header("Location: {$st['activite']}.php");
} elseif ($st['id_role'] == 2) {
header("Location: admin.php");
} elseif ($st['id_role'] == 1) {
header("Location: admin_super.php");
} else {
header("Location: index2.php");
}
You can declare whatever $_SESSION elements you like, I've left them out of this condition block for clarity/consistency.

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.

Update from URL

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]);

php PDO mysql - behavioural query

Happy New Year to all. I need to point out I am trying to use PDO exclusively and I'm a relative noob to using PDO, so please excuse the question if it appears plainly obvious.
I'm having a bit of a stupid moment because I cannot seem to understand a few things as to why a relatively simple email validation system I have (tried) to write is not quite working correctly. Everything is ok until the php at the end of the validation link is setting the email address as being validated. Here is my code, followed by questions:
Firstly I have an include file that holds the DB login. It looks like this:
<?php
// DATABASE SETTINGS
$hostname = "127.0.0.1";
$username = "devProduction";
$password = "ienx3rybcisuc";
$database = "devProduction";
try {
$conn = new PDO("mysql:host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// close the database connection (removed as I do this at the end of each call)
//$conn = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
And then in the page that actually received the user after they click on the link sent out to their email:
<?php
// Grab our includes
include '../conf/Funcs.php';
include '../conf/DBconfig.php'; // (This is the file displayed above)
require_once '../conf/Mobile_Detect.php';
// Check out what device is looking at us
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
$scriptVersion = $detect->getScriptVersion();
// Check to see if we are already logged in under an already validated account
if(isset($_COOKIE['AGMARDTuid']) || isset($_COOKIE['AGMARDTtoken'])) {
logout();
header("Location: ../");
exit;
} else {
$val = base64url_decode($_GET['val']);
$val = explode(":-:", $val);
$uid = $val[0];
$add = $val[1];
$key = $val[2];
// These are the three items that are pulled out of the URL $val value. This works fine
// It's only here to check it's working ok for the moment
echo "uid: ".$uid."<br>add: ".$add."<br>key: ".$key."<br><br>";
// Kill the process if either of the three values - $uid, $add, $key - are empty
if(($uid == "") || ($uid == NULL) || ($add == "") || ($add == NULL) || ($key == "") || ($key == NULL)) {
logout();
header("Location: ../");
exit;
} else {
// Seems everything is in order for email validation, so lets validate
$yes = "yes";
$NULL = NULL;
try {
$stmt = $conn->prepare("UPDATE $database.users SET `emailValidated` = :validate, `emailValidationKey` = :newkey WHERE `uid` = :uid AND `email` = :add AND `emailValidationKey` = :key");
$stmt->bindParam(':uid', $uid);
$stmt->bindparam(':add', $add);
$stmt->bindParam(':key', $key);
$stmt->bindParam(':validate', $yes);
$stmt->bindParam(':newkey', $NULL);
$stmt->execute();
$result = "success";
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); $result = "fail"; }
$conn = null;
echo "result: ".$result." (post sql)<br><br>";
if($result == "fail") {
echo "Email did not successfully validate, there was a problem<br><br>";
echo $conn . "<br>" . $e->getMessage();
} else if($result == "success"){
echo "Email successfully validated<br><br>";
echo $conn . "<br>" . $e->getMessage();
}
echo "<br><br>We got to the end!";
}
}
?>
The code works, kinda. The problem is, if there is NOT an account within the database that matches all three values passed to the script from the URL, it still displays as having updated (validated) an account, even though it has not. Why is this?
Also, for the section that I am binding some parameters, specifically these two:
$stmt->bindParam(':validate', $yes);
$stmt->bindParam(':newkey', $NULL);
Why do I seem to have to assign $yes = "yes"; and "$NULL = NULL; as variables beforehand? I did try:
$stmt->bindParam(':validate', 'yes');
$stmt->bindParam(':newkey', NULL);
and
$stmt->bindParam(':validate', yes);
$stmt->bindParam(':newkey', NULL);
and
$stmt->bindParam(':validate', 'yes');
$stmt->bindParam(':newkey', 'NULL');
all without success.
Answers and info and suggestions always welcome and appreciated. Thank you!
C
You should use bindValue instead bindParam when you want to pass a value (or the result of a function) in the prepared statement.
$id = 100;
$datas = array('a', 'b', 'c');
$stmt = $db->prepare("SELECT * FROM user WHERE id = :id AND status > :status AND justForExample = :other");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindValue(':status', 1, PDO::PARAM_INT);
$stmt->bindValue(':other', implode("", $datas), PDO::PARAM_STR);
$stmt->execute();
The documentation to BindValue
The documentation to BindParam
More informations about the difference

Categories