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.";
}
}
Related
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]);
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
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?
I'm currently building a system for a football league. And are currently working on the script file for adding results. Most of the script works and the result is always successfully added to the database. However the authentication part seems to fail. The if statement on line 12 does not seem to fire and I can't understand why.
My code can be found in the pastebin link here: http://pastebin.com/ty4pdGgn
<?PHP
include 'functions.php';
dbConnect();
//$userEmail = mysql_real_escape_string($_POST["userEmailText"]);
$userCode = mysql_real_escape_string($_POST["userPasscodeText"]);
$authenticated = false;
$userEmail = "info#example.com";
if ($userEmail == "info#example.com") {
header('Location: ../results.php?error=authentication');
}
$allUsers = mysql_query("SELECT * FROM accounts WHERE email = '$userEmail'");
while ($thisUser = mysql_fetch_assoc($allUsers)){
if ($userCode != $thisUser['passCode']) {
header('Location: ../results.php?error=authentication2');
}
echo $thisUser['passCode'];
$authenticated = true;
$userID = $thisUser['userID'];
}
if (!$authenticated) {
header('Location: ../results.php?error=authentication3');
}
$dateSubmitted = $_POST['submissionDate'];
$homeTeam = $_POST['homeTeam'];
$awayTeam = $_POST['awayTeam'];
$homeGoals = $_POST['homeGoals'];
$awayGoals = $_POST['awayGoals'];
if ($homeTeam == $awayTeam) {
header("Location: ../results.php?error=team");
}
if (getTeamLeague($homeTeam) != getTeamLeague($awayTeam)) {
header("Location: ../results.php?error=league");
} else {
$leagueID = getTeamLeague($homeTeam);
}
if ($homeGoals > $awayGoals) {
$winnerID = $homeTeam;
} else if ($homeGoals < $awayGoals) {
$winnerID = $awayTeam;
} else if ($homeGoals == $awayGoals) {
$winnerID = -1;
}
$cQuery = mysql_query("INSERT INTO results VALUES ('', $userID, '$dateSubmitted', $leagueID, $homeTeam, $homeGoals, $awayTeam, $awayGoals, $winnerID, 0)");
if ($cQuery){
header('Location: ../results.php');
} else {
echo mysql_error();
}
?>
Any help with this matter will be much appreciated. The functions.php contains no errors as this is all to do with database entry and not the authentication.
Put a die(); after the header("Location:...");
As your comparison code (the "if" part on line 12) that you pasted has to work, i have two advice:
Put a die(); or exit(); after the header() part.
Try looking here, as I am not sure if header() will work, while the location path you set is relative. Basic advice is to always use base paths for redirects, like "http://your.site.com/script.php").
Hello i have a weird scope problem
require 'connect.php';
$name = $_GET['R'];
echo $name;
if(isset($_POST['prev_password']) && isset($_POST['new_password']) && isset($_POST['rep_password'])) {
echo $name;
if(!empty($_POST['prev_password']) && !empty($_POST['new_password']) && !empty($_POST['rep_password'])) {
$user_password = $_POST['prev_password'];
$user_new_password = $_POST['new_password'];
$user_rep_password = $_POST['rep_password'];
if($user_new_password == $user_rep_password) {
$mysql_query = sprintf("SELECT username, password FROM users WHERE username='$name'", $name);
$query_run = mysql_query($mysql_query, $mysql_link) or die('COULD NOT PERFORM QUERY');
while($row = mysql_fetch_array($query_run)) {
$qUser_name = $row['username'];
$qUser_pass = $row['password'];
}
if($qUser_name == $name) {
echo 'Match';
if($qUser_pass == $user_password) {
$mysql_query = sprintf("UPDATE users SET password='$user_new_password' WHERE username='$name'", $name);
$query_run = mysql_query($mysql_query, $mysql_link) or die('COULD NOT PERFORM QUERY');
echo header('Location: main.php?C=1');
}else {
header('Location: main.php?C=4');
}
}
}else {
header('Location: main.php?C=3');
}
}else {
header('Location: main.php?C=2');
}
}
anyway, the problem is with the first variable $name, when i 'echo' $name its ok, displays the content correctly, but inside the (if sss) ITS EMPTY, idk why, i've tried using global, the GLOBALS array, and its still empty, ... so .. the query its executed with an empty parameter.
please help, if someone can see what could be possible wrong.
PD: this is a Changepassword.php the $_GET['R'] is getting from the user Main.php site, AND I KNOW, im not Hashing password,, that is not really the problem here