PHP - broken image displaying from database - php

Every time a user submits a picture for their "profile pic" it will display as a "broken image" and I noticed that when I physically insert an image into the mysql data base and display it, it works perfectly and the size of the file changes to "BLOB - KiB" instead of MB. But when I insert that same image into the database using my "upload file", that image turns to "BLOB MB" and doesn't display on the website. I saw some post about this and they said to remove the "addslashes" from the variable and i did that but it still didn't work. So what i wan't to do is display the image from the database that was submitted by the user. It works when you physically insert it into the database without a file but if you do it with one, it doesn't work. Here is a screen shot of the database structure, upload file, and retrieving file.
PHP Upload file
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') { //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['username'])) {
if($_SESSION['came_from_upload'] != true) {
setcookie("username", "", time() - 60 * 60);
$_COOKIE['username'] = "";
header("Location: developerLogin.php");
exit;
}
error_reporting(E_ALL & ~E_NOTICE);
if($_SERVER['REQUEST_METHOD'] == "POST") {
$token = $_SESSION['token'];
$userid = $_SESSION['id'];
$fullname = addslashes(trim($_POST['fullname']));
$username = addslashes(trim($_POST['username']));
$email = addslashes(trim($_POST['email']));
$password = addslashes(trim($_POST['password']));
$storePassword = password_hash($password, PASSWORD_BCRYPT, array(
'cost' => 10
));
$file_tmp = addslashes(trim($_FILES['file']['tmp_name']));
$file_name = addslashes(trim($_FILES['file']['name']));
try {
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
die("There was an error connecting to the database");
}
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = ?");
$stmtChecker->execute(array(
$userid
));
if($result = !$stmtChecker->fetch()) {
setcookie("username", "", time() - 60 * 60);
$_COOKIE['username'] = "";
header("Location: developerLogin.php");
exit;
}
if(!empty($fullname)) {
$stmtFullname = $handler->prepare("UPDATE generalusersdata SET fullname = ? WHERE user_id = ?");
$stmtFullname->execute(array(
$fullname,
$userid
));
}
if(!empty($username)) {
$stmtCheckerUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = ?");
$stmtCheckerUsername->execute($username);
if($resultCheckerUsername = $stmtCheckerUsername->fetch()) {
die("Username Already in use! Please try again");
}
$stmtUsername = $handler->prepare("UPDATE generalusersdata SET username = ? WHERE user_id = ?");
$stmtUsername->execute(array(
$username,
$userid
));
}
if(!empty($email)) {
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
die("Email is Not Valid!");
}
$stmtCheckerEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = ?");
$stmtCheckerEmail->execute($email);
if($resultCheckerEmail = $stmtCheckerEmail->fetch()) {
die("Email Already in use! Please try again");
}
$stmtEmail = $handler->prepare("UPDATE generalusersdata SET email = ? WHERE user_id = ?");
$stmtEmail->execute(array(
$email,
$userid
));
}
if(!empty($password)) {
if(strlen($password) < 6) {
die("Password has to be GREATER than 6 characters!");
}
//Check if password has atleast ONE Uppercase, One Lowercase and a number
if(!preg_match("(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$)", $password)) {
echo 'Password needs to be at least ONE uppercase, ONE lowercase, and a number!';
exit;
}
$stmtPassword = $handler->prepare("UPDATE generalusersdata SET password = ? WHERE user_id = ?");
$stmtPassword->execute(array(
$storePassword,
$userid
));
}
if($_FILES['file']['error'] == UPLOAD_ERR_OK) {
$mime = mime_content_type($_FILES['file']['tmp_name']);
if(strstr($mime, "video/")) {
die("Please note that this file is NOT an image... Please select an image for your Profile Picture");
} else if(strstr($mime, "image/")) {
$allowedTypes = array(
IMAGETYPE_PNG,
IMAGETYPE_JPEG
);
$detectedType = exif_imagetype($_FILES['file']['tmp_name']);
if($extensionCheck = !in_array($detectedType, $allowedTypes)) {
die("Failed to upload image; the format is not supported");
}
$dir = "devFiles/";
$uploadedFile = $dir . basename($_FILES['file']['name']);
if(is_dir($dir) == false) {
mkdir($dir, 0700);
}
if(!move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)) {
die("There was an error moving the file... Please try again later!");
}
$stmtFile = $handler->prepare("UPDATE generalusersdata SET profile_image = ?, file_tmp = ? WHERE user_id = ?");
$stmtFile->execute(array(
$file_name,
$file_tmp,
$userid
));
}
}
$_SESSION['token'] = $token;
header("Location: developerUpload.php");
exit;
}
} else {
header("Location: developerLogin.php");
exit;
}
HTML
<form method="post" enctype="multipart/form-data" autocomplete="off">
Information Changer<br>
Fullname: <input type="text" name="fullname" placeholder="Full Name.....">
<br/>
<br/>
Username: <input type="text" name="username" placeholder="User Name.....">
<br/>
<br/>
Email: <input type="text" name="email" placeholder="Email.....">
<br/>
<br/>
Password: <label><input type="password" name="password" placeholder="Password....." ></label>
<br></br>
Profile Picture: <input type="file" name="file">
<br/>
<input type="submit" name="submit">
</form>
Retrieving file
try {
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
die("There was an error connecting to the database");
}
$stmt = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = :userid");
$stmt->bindValue(':userid', '61', PDO::PARAM_INT);
$stmt->execute();
while($result = $stmt->fetch()) {
echo '<img src="data:image/jpeg;base64,' . base64_encode($result['file_tmp']) . '"/>';
}

You are storing the temporay filename - not its contents.
$file_tmp = addslashes(trim($_FILES['file']['tmp_name']));
Should be
$file_tmp = file_get_contents($_FILES['file']['tmp_name']);

Related

MYSQL is automatically decrypting my password upon record entry

I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>

PHP - Keep session up when database information is changed

When a user logs into my website a session is created with their "user id". When they want to go change their account information they can click the button and they will be redirected to the "developer_infoupdater.php" file. But every time they change their information, the session ends and they are logged out. I want them to stay logged in after they change their information. I believe the problem is on the "developerUpload.php" file because i am checking if their information is current and if not redirect them to the logout page. And when i changed the destination from logout to a different file, it went to the file that i changed it to. So what I want is for the user to stay logged in after they update their account information. Here is my code
Developer Upload file
<?php
session_start();
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
//Check if TOKEN used to log in, is actually there
$token = $_SESSION['token'];
$stmtToken = $handler->prepare("SELECT * FROM token_table WHERE token = :token");
$stmtToken->execute(array(':token'=>$token));
if($rowToken = !$stmtToken->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerSignup.php");
exit;
}
//Check if information is still in there has changed
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$fullname = $_SESSION['fullname'];
$email = $_SESSION['email'];
$password = $_SESSION['password'];
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id= :userid AND fullname = :fullname AND username = :username AND email = :email");
$stmtChecker->execute(array(':userid'=>$userid, ':fullname'=>$fullname, ':username'=>$username, ':email'=>$email));
if(!$resultChecker = $stmtChecker->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
if(!password_verify($password, $resultChecker['password'])){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
if(isset($_COOKIE['id'])){
if(isset($_POST['changeSettings'])){
$_SESSION['token'] = $token;
$_SESSION['id'] = $userid;
$_SESSION['came_from_upload'] = true;
header("Location: developer_infoupdater.php");
exit;
}
}
info update file
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
error_reporting(E_ALL & ~E_NOTICE);
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
$userid = $_SESSION['id'];
$fullname = addslashes(trim($_POST['fullname']));
$username = addslashes(trim($_POST['username']));
$email = addslashes(trim($_POST['email']));
$password = addslashes(trim($_POST['password']));
$storePassword = password_hash($password, PASSWORD_BCRYPT, array('cost' => 10));
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = :userid");
$stmtChecker->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtChecker->execute();
if($result = !$stmtChecker->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
if(!empty($fullname)){
$stmtFullname = $handler->prepare("UPDATE generalusersdata SET fullname = :fullname WHERE user_id = :userid");
$stmtFullname->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$stmtFullname->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtFullname->execute();
}
if(!empty($username)){
$stmtCheckerUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = :username");
$stmtCheckerUsername->bindParam(':username', $username, PDO::PARAM_STR);
$stmtCheckerUsername->execute();
if($resultCheckerUsername = $stmtCheckerUsername->fetch()){
die("Username Already in use! Please try again");
}
$stmtUsername = $handler->prepare("UPDATE generalusersdata SET username = :username WHERE user_id = :userid");
$stmtUsername->bindParam(':username', $username, PDO::PARAM_STR);
$stmtUsername->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtUsername->execute();
}
if(!empty($email)){
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){
die ("Email is Not Valid!");
}
$stmtCheckerEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = :email");
$stmtCheckerEmail->bindParam(':email', $email, PDO::PARAM_STR);
$stmtCheckerEmail->execute();
if($resultCheckerEmail = $stmtCheckerEmail->fetch()){
die("Email Already in use! Please try again");
}
$stmtEmail = $handler->prepare("UPDATE generalusersdata SET email = :email WHERE user_id = :userid");
$stmtEmail->bindParam(':email', $email, PDO::PARAM_STR);
$stmtEmail->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtEmail->execute();
}
if(!empty($password)){
if(strlen($password) < 6){
die ("Password has to be GREATER than 6 characters!");
}
//Check if password has atleast ONE Uppercase, One Lowercase and a number
if(!preg_match("(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$)",$password)){
echo 'Password needs to be at least ONE uppercase, ONE lowercase, and a number!';
exit;
}
$stmtPassword = $handler->prepare("UPDATE generalusersdata SET password = :password WHERE user_id = :userid");
$stmtPassword->bindParam(':password', $password, PDO::PARAM_STR);
$stmtPassword->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtPassword->execute();
}
if($_FILES['file']['error'] == UPLOAD_ERR_OK){
$file_tmp = file_get_contents($_FILES['file']['tmp_name']);
//keep only A-Z and 0-9 and everything else KILL
$file_name = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['file']['name']));
$file_name = strtotime("now")."_".$file_name;
$mime = mime_content_type($_FILES['file']['tmp_name']);
if(strstr($mime, "video/")){
die("Please note that this file is NOT an image... Please select an image for your Profile Picture");
}else if(strstr($mime, "image/")){
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG);
$detectedType = exif_imagetype($_FILES['file']['tmp_name']);
if($extensionCheck = !in_array($detectedType, $allowedTypes)){
die("Failed to upload image; the format is not supported");
}
$dir = "devFiles/";
$uploadedFile = $dir . basename($_FILES['file']['name']);
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(!move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)){
die("There was an error moving the file... Please try again later!");
}
$stmtFile = $handler->prepare("UPDATE generalusersdata SET profile_image = :file_name, file_tmp = :file_tmp WHERE user_id = :userid");
$stmtFile->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmtFile->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$stmtFile->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtFile->execute();
}
}
$_SESSION['id'] = $userid;
$_SESSION['token'] = $token;
header("Location: developerUpload.php");
exit;
}
}else{
header("Location: developerLogin.php");
exit;
}
?>
Indeed when changing your user information it doesn't match what was previously cached in the session ( this is logical ). Seems to me you have 2 choices.
Update session data when making edits ( hard to maintain )
Check only the primary key of the user (this is what i would do)
$userid = $_SESSION['id'];
/* Nuke this stuff
$username = $_SESSION['username'];
$fullname = $_SESSION['fullname'];
$email = $_SESSION['email'];
$password = $_SESSION['password']; // I wouldn't persist the password, what do we need it for after login,
*/
//Look up the user by ID only
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id= :userid");
$stmtChecker->execute(array(':userid'=>$userid));
if(!$resultChecker = $stmtChecker->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}else{
//if a user with this ID exists update session data.
$_SESSION['username'] = $resultChecker['username'];
$_SESSION['fullname'] = $resultChecker['fullname'];
$_SESSION['email'] = $resultChecker['email'];
}

updated values are displaying only after refreshing the page

i am trying to update name ,email , image informations in form.
name, email was updating fine, but image was not saving in folder, so i removed ; in below line :
if ($user_home->update($uname,$email, $phone, $uid)); ,
now once we click on "save" button, images are saving in folders,
but name & emails are displaying old values, & after refreshing page displaying updated values. but i want to display updated values once we click on save button.
form
<form action="profile.php" method="POST" enctype="multipart/form-data">
Name :
<?php echo $row['userName'] ?> <br/>
Email :
<?php echo $row['userEmail'] ?> <br>
<h3>photo</h3>
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
code for name ,email
<?php
include 'home.php';
// session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);
// query
if ($user_home->update($uname,$email, $phone, $uid)); // This is the line
{
header("Location: profile.php");
die();
}
}
?>
code for image
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "Error: Invalid parameters - please contact your server administrator.";
}
?>
You need to do the select query after the update query, otherwise you are getting the old info and then update the record in the database.
<?php
include 'home.php';
// session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
// query
if ($uid > 0 && $user_home->update($uname,$email, $phone, $uid)) // This is the line
{
header("Location: profile.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Or you can use this custom update:
// query
if ($uid > 0)
{
$stmt = $user_home->runQuery("UPDATE tbl_users SET userName=:uname,
userEmail=:email, phone=:phone WHERE userID=:uid");
$stmt->execute(array(
":uid"=>$_SESSION['userSession'],
":email" => $email,
":phone" => $phone,
":uname" => $uname
));
header("Location: profile.php");
die();
}

authentification doesn't work

I'm trying to make an authentication form with PHP and MySQL but it doesn't work and I'm wondering why.
Is there anybody who can help me ? I did a password hash in a precedent file, but they are not linked. This one is independant .
Thank you !
<?php
session_start();
function connect_db($host, $port, $db, $username, $password)
{
$pdo = new PDO("mysql:host=$host; port=$port; dbname=$db", $username, $password);
return $pdo;
}
if (isset($_POST["email"]) && isset($_POST["password"]) && !empty($_POST["email"]) && !empty($_POST["password"]))
{
$error_pass= "";
$email = $_POST["email"];
$password = $_POST["password"];
try
{
$pdo = connect_db("localhost", 3306, "*******", "******", "*******");
$sql = $pdo-> prepare("SELECT * FROM users WHERE email = :email AND password = :password");
$sql->bindParam(':email', $email);
$sql->bindParam(':password', $password);
$sql->execute();
$req = $sql->fetch();
echo $req["password"] . "SALUT \n";
var_dump($req["password"]);
if (password_verify($password, $req['password']) == 0) {
session_unset();
$error_pass = "Incorrect email/password";
}
else {
$_SESSION["name"] = $req["name"];
header("Location: index.php", true, 302);
}
}
catch (PDOException $e)
{
echo $e->getMessage();
}
if ($error_pass) {
echo $error_pass;
}
}
else {
echo "Some fields are missing";
}
?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action ="login.php">
<input type="text" name="email">
<input type="text" name="password">
<input type="submit" name="submit" value ="submit">
</form>
</body>
</html>
Remove password from your query. You need to find user only by email and then verify that password is correct.
$sql = $pdo-> prepare("SELECT * FROM users WHERE email = :email");
$sql->bindParam(':email', $email);
$sql->execute();
$req = $sql->fetch();
// #todo :: check did you got any users
if (password_verify($_POST["password"], $req['password'])) {
// password is valid
}

check if profile data exists on profile update

I have a profile page, function for the edit and a check function for the edit.
profile page:
if (isset($_POST['edit']) && $_POST['edit'] === 'Edit') {
$errorMsgs = $user->validateUpdate($_POST);
if (empty($errorMsgs)) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
$user->updateProfile($username,$email,$id);
echo 'edited';
exit;
}
foreach ($errorMsgs as $msg) {
echo '<li>'. $msg. '</li>';
}
}
while ($row = mysqli_fetch_assoc($result)) {
?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
Username<br>
<input type="text" name="username" value="<?php echo $row['username']; ?>" /><br>
Email<br>
<input type="text" name="email" value="<?php echo $row['email']; ?>" /><br>
<input name="edit" type="submit" value="Edit"/>
</form>
<?php }
?>
Update function:
function updateProfile($username,$email,$id){
$con = new Core();
$con->connect();
$username = trim(strtolower($username));
$username = str_replace(' ', '', $username);
$sql = 'UPDATE users SET username = ?, email = ? where id = ?';
if ($stmt = $con->myconn->prepare($sql))
{
$stmt->bind_param('ssi', $username, $email, $id);
$stmt->execute();
$stmt->close();
}
else{
die("errormessage: " . $con->myconn->error);
}
}
Check function:
function validateUpdate(array $userDetails)
{
$con = new Core();
$con->connect();
$errmsg_arr = array();
foreach($userDetails as $key => $value) {
if (empty($value)) {
$errmsg_arr[] = ucwords($key) . " field is required";
}
}
if (!empty($userDetails['edit'])) {
if (!empty($userDetails['email']) && !filter_var($userDetails['email'], FILTER_VALIDATE_EMAIL)) {
$errmsg_arr[] = "the provided email is not a valid email address";
}
$sqlu = "SELECT username FROM users WHERE username = ?";
if($stmt = $con->myconn->prepare($sqlu)){
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
}
if($stmt->fetch() > 0){
$errmsg_arr[] = "Username already exists!";
$stmt->close();
}
$sqle = "SELECT email FROM users WHERE email = ?";
if($stmt = $con->myconn->prepare($sqle)){
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
}
if($stmt->fetch() > 0){
$errmsg_arr[] = "Email already exists!";
$stmt->close();
}
}
return $errmsg_arr;
}
Everything works perfect. But there's a flaw in this check.
Someone goes to their profile.
The person tries to edit details, edits it all: code echo's "succesfully edited".
But if the person tries to edit Email only instead of all details, gets the error message that the "Username value" already exists.
Now my question: How would I let it not check on the username value if it isn't edited? Or email value?
Thanks in advance!
you would exclude the user that's logged in from the query. While doing the login you would save the users id in a session variable. You can use this variable for preventing the queries from checking against the user itself
$sqlu = "SELECT username FROM users WHERE username = ? AND id != '".$_SESSION['user_id']."'";
$sqle = "SELECT email FROM users WHERE email = ? AND id != '".$_SESSION['user_id']."'";
That should fix your issue! More info on session variables

Categories