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
Related
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> ';
}
I've made a web page where you can register and log in, and once you log in you can edit your profile and also upload an avatar. I'm working on the avatar part right now and I can't figure out why it doesn't work. I will show you some parts of my code so hopefully you can help me.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$avatar_path = $mysqli->escape_string('images/'.$_FILES['avatar']['name']);
if (preg_match("!image!",$_FILES['avatar']['type'])) {
if (copy($_FILES['avatar']['tmp_name'], $avatar_path)) {
//It copies the image to the specified path so i know it works till here.
$_SESSION['avatar'] = $avatar_path;
And here is the problem, because it basically does nothing, it doesn't even return an error message so I don't know what's wrong with my SQL.
($_SESSION[msg1] is equal to your username (I know it because I printed it here), so basically what I'm trying to do is insert the avatar path into the users table where username is equal to your username, but it does nothing.
$sql = "UPDATE users SET avatar = $avatar_path WHERE username = $_SESSION[msg1]";
if ($mysqli->query($sql) === true){
header("Location: index.php");
}
}
}
}
Formate your query like so:
$sql = "UPDATE users SET avatar = '" . $avatar_path . "' WHERE username = '" . $_SESSION['msg1'] . "'";
if ($mysqli->query($sql) === true){
header("Location: index.php");
}
else
{
die("Database Query Failed: " . mysqli_error());
}
I have a login form in php which I have connected to a sql database in phpmyadmin. The script I have written should get the email and password variables from the user. It should then check the database to make sure the user is registered. Then either redirect the user to their account or notify the user that their details didnt match up and ask them to try again. However no matter what way I change the code it will always redirect to the account page even if the data I submit through the form is random info.
Any help or advice would be great. Thanks.
Here is my code
<?php
//require_once 'includes/db_connect.php';//
//require_once 'includes/functions.php';//
$con=mysqli_connect("x","m","z","m");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start(); //starting a PHP session.
if (isset($_SESSION['logged'])){
header("Location:account.html");
exit();
}
$email = $_POST['email'];
$password =($_POST['password']);
$sql = mysqli_query($con,"SELECT * FROM `websiteusers` WHERE email ='" . $email . "' and password ='" . $password . "'") or die (mysqli_error($sql));
$count = mysqli_num_rows($sql);
//$row=mysqli_fetch_array($query);//
if ($count==1){
$_SESSION[logged] = 1;
$_SESSION['email'] = $email;
$_SESSION['password'] =$password;
header("location:account.html"); /* Redirect the browser */
}
else {
echo "Sorry those details are not in the database. Click here <a href=\"memberlogin.html\"</a> to try again.";
}
exit();
?>
It's because of the Session Index which you used $_SESSION[logged] and should be $_SESSION['logged']
if ($count==1){
$_SESSION['logged'] = 1;
$_SESSION['email'] = $email;
$_SESSION['password'] =$password;
header("location:account.html"); /* Redirect the browser */
}
You forgot '' in the $_SESSION[logged] variable, it should be $_SESSION['logged']
I have a comics site which I'd like to easy my uploading of image paths to the database.
I have a login screen which checks as such for correct credentials:
<?php
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['pw']) ? $_POST['pw'] : "";
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(verify($username, $password) == 1) {
header("Location: ?action=admin");
}
else {
echo "<center>Incorrect credentials</center>";
}
}
function verify($user, $pw) {
include './scripts/dbconnect.php';
$result = $mysqli->query("SELECT username, password FROM users WHERE username='" . $user . "' AND password='" . $pw . "'");
return $result->num_rows;
}
include 'include/footer.php';
?>
Which will then log them in to the upload screen.
Unfortunately, all the user has to do is guess what my url might be for the upload page and they can skip my login screen...
/HTwS/?action=login (just replace 'login' with 'admin' and you're there...) So, my first line of defense will be to not make my upload page name so obvious... but what happens if a user still guesses it... can I verify in another way which won't let them just change the url up?
Thanks!
Well this is pretty insecure. What you're going to want to do is set some session variables when you login ($_SESSION[user_id], $_SESSION[permission_type], etc...). You can then have a function such as verifyAdmin() at the top of each admin page that would check if the logged in user is in fact an admin by checking the $_SESSION variables you just set. If they're not, they get redirected to the login page.
When the admin logs in, set some session variables as such:
$_SESSION[user_id] = id_of_admin;
$_SESSION[permission_type] = 'admin';
verifyAdmin would look something like this:
function verifyAdmin() {
if(!isset($_SESSION[username]) || !isset($_SESSION[permission_type]) || $_SESSION[permission_type] != 'admin'){
header("Location: login.php");
}
}
Then on the top of each admin page you can simply do this:
verifyAdmin();
Your verify function should look like this:
function verify($user, $pw) {
include './scripts/dbconnect.php';
$result = $mysqli -> query("SELECT username, password FROM users WHERE username='" . $user . "' AND password='" . $pw . "'");
if ($result -> num_rows == 1) {
$_SESSION[username] = $user;
$_SESSION[permission_type] = 'admin';
}
return $result -> num_rows;
}
This chunk of code is also vulnerable to SQL injection. You need to sanitize those $_POST variables.
Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.