When i am using this script image name inserted in all user's row. how can i insert in current session user's line
auth.php
<?php
session_start();
if(!isset($_SESSION["username"]) ){
header("Location: login.php");
exit(); }
?>
home.php
<?php
include("php-includes/auth.php");
//Include database configuration file
include_once 'php-includes/dbConfig.php';
//Get current user ID from session
$userId = $_SESSION["username"];
//Get user data from database
$result = $db->query("SELECT * FROM user WHERE username = $userId");
$row = $result->fetch_assoc();
//User profile picture
$userPicture = !empty($row['picture'])?$row['picture']:'no-image.png';
$userPictureURL = 'uploads/images/'.$userPicture;
?>
Just two modifications and you are done:
1) You have to get current user's name from session
$userId = $_SESSION['username'];
2) Add single quote to the username value in query.
$update = $db->query("UPDATE user SET picture = '".$fileName."' WHERE username = '$userId'");
As a note:
If you are providing a value to database query, if it is non-numeric,
you need to add single quotes to it.
This tells that the passed string is a value and not any MySQL
reserved word/Database name/Table name/Field name.
When user logged in on that you must keep their username in session for that you can use code something like given below...
<?php
session_start();
//retrive username from database and then save in session
$_SESSION['username'] = $username;
And when you reach to this script where you need to insert the image for that user
Here can get the username from a session like given below...
session_start();
$userId = $_SESSION['username'];
And then use it in your MySQL query
$update = $db->query("UPDATE user SET picture = '$fileName' WHERE username = '$userId'");
Also, keep in mind when you are using a double quote (") for the database query then you don't need to use dots around variable name. The rather single quotation mark is enough
The complete code is given below...
if(!empty($_FILES['picture']['name'])){
//Include database configuration file
include_once 'php-includes/dbConfig.php';
//File uplaod configuration
$result = 0;
$uploadDir = "uploads/images/";
$fileName = time().'_'.basename($_FILES['picture']['name']);
$targetPath = $uploadDir. $fileName;
//Upload file to server
if(#move_uploaded_file($_FILES['picture']['tmp_name'], $targetPath)){
session_start();
//Get current user ID from session
$userId = $_SESSION['username'];
$update = $db->query("UPDATE user SET picture = '$fileName' WHERE username = '$userId'");
//Update status
if($update){
$result = 1;
}
}
//Load JavaScript function to show the upload status
echo '<script type="text/javascript">window.top.window.completeUpload(' . $result . ',\'' . $targetPath . '\');</script> ';
}
Related
I have a update page which has the update form for email and password, i tried console logging to see if the email and address are transmitted in post method,and the details are transmitted to this page but still the data is not persisted, could some one please tell me why thank you !
<?php session_start(); ?>
<?php
//extract form values and assign to regular PHP variables
$uemail=$_POST['email'];
$passW=$_POST['pass'];
$upassword= md5($_POST['passW']);
if(!isset($_SESSION['usermail'])) {
header('Location: ../homepage.php');
}
else{
include "connection.php";
$session=$_SESSION["useremail"];
$sql = "UPDATE users SET uemail = '$uemail', upassword = '$upassword' WHERE uemail = '$session'";
$_SESSION["useremail"]=$uemail; //setting new email in session
header("Location:../homepage.php");
}
?>
try to concatinate the variables.
<?php session_start(); ?>
<?php
//extract form values and assign to regular PHP variables
$uemail=$_POST['email'];
$passW=$_POST['pass'];
$upassword= md5($_POST['passW']);
if(!isset($_SESSION['usermail'])) {
header('Location: ../homepage.php');
}
else{
include "connection.php";
$session=$_SESSION["useremail"];
$sql = "UPDATE users SET uemail = '".$uemail."', upassword = '".$upassword."' WHERE uemail = '".$session."'";
$_SESSION["useremail"]=$uemail; //setting new email in session
header("Location:../homepage.php");
}
?>
and always check your variables if it is correct.. always look to your codes..
I am trying to set the session id for a user to their corresponding id from a database. The ID of a user is a simple auto increment INT in the SQL database. The user logs in with their email and password. Once the session is started, I want a session variable to store that users ID. My code for the login php file to create the session id at the moment is as follows.
$_SESSION['user_id'] = $user_id;
My code to set the session user id to a variable in another php file is then as follows:
$user_of_id = $_SESSION['user_id'];
When I try insert $user_of_id into another table of the database in the php script I've declared it in, it does not work. I have session_start(); in all necessary php files. I am hoping someone can point out my mistake.
The full code is as follows for the user login php:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['Login_Btn'])) {
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password = md5($password);// Decrypt hash of password stored in database
$mySQLQuery = "SELECT * FROM userdetails WHERE email='$email' AND password='$password'";
$resultOfQuery = mysqli_query($db, $mySQLQuery);
if (mysqli_num_rows($resultOfQuery) == 1) {
$_SESSION['user_id'] = $user_id;
header("location: User_Home_Page.html");
}else{
$_SESSION['message'] = "Login Fail";
}
}
?>
The php for uploading my document is as follows:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['upload_btn'])){
$user_id = $_SESSION['user_id'];
$taskTitle = mysql_real_escape_string($_POST['tasktitle']);
$taskDescription = mysql_real_escape_string($_POST['TaskDescription']);
$numPages = mysql_real_escape_string($_POST['number_of_pages']);
$file = rand(1000,100000)."-".$_FILES['file_document']['name'];
$file_loc = $_FILES['file_document']['tmp_name'];
$file_size = $_FILES['file_document']['size'];
$file_type = $_FILES['file_document']['type'];
$folder="uploads/";
move_uploaded_file($file_loc,$folder.$file);
$numWords = mysql_real_escape_string($_POST['number_of_words']);
$deadlineClaim = mysql_real_escape_string($_POST['deadline_claim']);
$deadlineComplete = mysql_real_escape_string($_POST['deadline_complete']);
$sql = "INSERT INTO task(user_id, title, description, file, file_type, file_size, pg_num, num_words, deadline_claim, deadline_completion) VALUES( '$user_id', '$taskTitle', '$taskDescription', '$file', '$file_type', '$file_size', '$numPages', '$numWords', '$deadlineClaim', '$deadlineComplete')";
mysqli_query($db, $sql);
header("location: User_Home_Page.html");
}
?>
EDIT: Question has been updated after my answer with a full code. Perhaps this answer needs a rework.
If you are using session_start(); correctly (at the begining of your document), your code is fine.
file1.php should be:
<?php
session_start();
$user_id = 5;
$_SESSION['user_id'] = $user_id;
file2.php should be:
<?php
session_start();
$user_of_id = $_SESSION['user_id'];
echo 'User-ID: '.$user_of_id; //User-ID: 5
If you can't output the user id, try to debug your code by checking if your session is set (print_r($_SESSION);). Perhaps you have got an if-clause which will not be executed or something like this (if(false) $_SESSION['user_id'] = $user_id; would be wrong).
If you can't output the user id anyway, you have got a problem with your server (try using this minimal code) or your client (try using antoher browser / computer).
I am creating a login for a website. I can get the code below working: It lets me log in! Yet I can't get a start session to work: People can still get to my pages via URL.
Log in PHP:
<?php
//calling connection to database
include "connection.php";
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
Start session code which says undefined variables:
<?php
include"includes/loginrequiredb.php";
if($_SESSION['username'] !=$user){
session_destroy();
header("Location: view.php");
die();
}else
{
echo "welcome to the site you have logged in" . $_SESSION['username'];
}
?>
Without starting the session you can not get the values from $_SESSION.
You just need to start session in your both files as:
session_start();
Note that you need to start_session() in both files only in just welcome file.
Side note:
I suggest to also use isset() for checking either value set or not.
Start the session with session_start and Add a session verification file in adminmain.php page.
<?php
//calling connection to database
include "connection.php";
#session_start();
//session
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
##### file verify.php #####
<?php #session_start();
if (#$_SESSION['username']!=$user) {
header ("location: index.php");
exit;
}
?>
Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.
am building a social network, i use php session to allow info to stay on the pages when the user goes to another page, however when the mysql script to update a value. it does reflect the change made unless the user log out and log back in. any ideas?
thanks . . .
<?php
session_start();
$login_email = $_SESSION['email'] ;
$login_pass = $_SESSION['pass'] ;
$target_path = "pictures/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path) and
$con = mysql_connect("localhost","root","naruto") and
mysql_select_db("users", $con) and
mysql_query (" UPDATE user_info SET profile_pic = ' $target_path ' WHERE email = '$login_email' AND password1 = '$login_pass' " ) ) {
session_destroy ();
include 'login.php';
session_start ();
if ( $login_email == $_SESSION['page_email'] && $login_pass == $_SESSION['page_pass ']){
header ('location:home.php');
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
$_SESSION['page_email']
$_SESSION['page_pass ']
It would depend on how you show the profile pic on a user's page. If it's through stored session, I would suggest you create a function to return a user information to store in $_SESSION, and call that on every user profile update
mysql_query (" UPDATE user_info SET profile_pic = ' $target_path ' WHERE email = '$login_email' AND password1 = '$login_pass' " ) ) {
session_destroy();
include 'login.php';
session_start ();
$_SESSION['user'] = get_user_info(); // your new function to return user info