How to preserve my session in PHP? - php

I'm making video-portal, so I've authentication system and if I post some comment, or image sessions disapper.
And i Get "Undefined index: email in C:\xampp\htdocs\social_site\assets\login.php on line 2"
AND "Notice: Undefined index: password in C:\xampp\htdocs\social_site\assets\login.php on line 3
".
login.php
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM members WHERE email='$email'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
$hash_password = $row['password'];
$hash = password_verify( $password, $hash_password);
$y = $_session['username'] = $row['username'];
$x = $_session['id'] = $row['id'];
if (isset($_POST['submit'])) {
if ($hash == 0) {
header('location: index.php?fillpassword');
exit();
}
else{
$sql = "SELECT * FROM members WHERE email='$email' AND password='$hash_password'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
echo "<script>alert('You have no access here. You must login.')</script>";
header ("Location: ../index.php?erorr=noaccess");
}
}
}
?>
main.php
<?php
if ($_SESSION['id'] = $row['id']) {
echo "<form method='POST' action='".setComments($conn)."' enctype='multipart/form-data'>
<input type='hidden' name='size' value='1000000'>
<input type='file' name='image' value='Upload photo'>
<textarea name='text' rows='8' cols='80'></textarea>
<br/>
<input type='submit' name='upload' value='Submit'>
</form>";
}
?>

You have to add a session_start at the begin of your script.
If you don't want to have php's warning when the session is destroyed add also a check to see if the session is still there:
if(isset($_SESSION['password')){ [..] }

Maybe you used dreamweaver , the dreamweaver add hidden some charackters, you can check or remove it by HXD software . Download it from here .

Related

How to correctly create a form to delete MySQL record by using PHP

I would like to create a form to delete the MySQL record. After checking lots of post here and other website, I am still confused about how to achieve it. Could someone guide me what wrong is with my code?
<?php
$server_name = 'xxxxxx';
$user_name = 'xxxxxx';
$password = 'xxxxxx';
$db_name = 'xxxxxx';
$conn = new mysqli($server_name, $user_name, $password, $db_name);
if(!$conn) {
die("Fail to connect to the database $conn->connect_error");
}
$conn->query('SET NAMES UTF8');
require_once('conn.php');
$id = $_POST['value'];
$sql = sprintf("DELETE FROM users WHERE id=%d", $id);
$result = $conn->query($sql);
if(!$result) {
die($conn->error);
}
if ($conn->affected_rows >= 1) {
echo 'Delete successfully';
} else {
echo 'Fail to delete the data';
}
$result = $conn->query("SELECT * from users");
if(!$result) {
die($conn->error);
}
while($row = $result->fetch_assoc()) {
echo "id: $row[id]";
echo "<form action='delete.php' method='POST'>
<input type='hidden' name='id_to_delete' value='$row[id]'>
<input type='submit' name='delete' value='Delete'>
</form>";
echo "username: $row[username]<br>";
}
?>
<form method="POST" action="delete.php">
<label for="test">Username: </label>
<input type="text" id="test" name="name">
<label for="test">Password: </label>
<input type="text" id="test" name="password">
<input type="submit">
</form>
I can see a couple of potential problems with the code:
First, you use $_POST['value'] in the PHP to get the $id to delete but you want to be using $_POST['id_to_delete'] because that is the name you have given to the html hidden input in the row's form (<input type='hidden' name='id_to_delete' value='$row[id]'>).
Second, the delete attempt will happen regardless of whether the form was submitted or not so you want to check whether there is actually an id to delete making sure it is a number.
For example:
...
$id = filter_input(INPUT_POST, 'id_to_delete', FILTER_VALIDATE_INT);
if($id!==null && $id!==false) {
$sql = sprintf("DELETE FROM users WHERE id=%d", $id);
$result = $conn->query($sql);
if(!$result) {
die($conn->error);
}
if($conn->affected_rows >= 1) {
echo 'Delete successfully';
}
else {
echo 'Fail to delete the data';
}
}
...
PLEASE NOTE: This is not production ready code! Do not use in a public facing environment! You will need to do a lot more work on validating who can post data to this php otherwise anyone could send a post request to the page and delete all your users regardless of whether they loaded the form or not.

Bypass the check if the Username is unchanged in the form

FORM
<!DOCTYPE HTML>
<html>
<head>
<title>
</title>
</head>
<body>
<form id='updateholder' action='updateacc.php' method='post'>
<fieldset >
<legend>Update Account</legend>
Username:
<input type='text' name='username' id='username' value = "<?php echo $row['user_Username']?>"/>
Current Password:
<input type='text' name='curpassword' id='curpassword' value = "" maxlength="50" />
New Password:
<input type='text' name='confirm' id='newpassword' value = "" maxlength="50" />
Confirm New Password:
<input type='text' name='confirm' id='confirmpassword' value = "" maxlength="50" />
Middle Name:
<input type='text' name='middlename' id='middlename' value = "<?php echo $row['user_Mname']?>"/>
Last Name:
<input type='text' name='lastname' id='lastname' value = "<?php echo $row['user_Lname']?>"/>
<input type='Submit' name='Submit' value='Submit' />
</fieldset>
</form>
LOGOUT
</body>
</html>
Update.php
<?php
session_start();
include('dbconn.php');
$user_ID = $_SESSION['user_ID'] ;
$sql = "SELECT * FROM tbl_user WHERE user_ID = '$user_ID'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (isset($_POST['Submit'])) {
$username = $_POST["username"];
$curpassword = $_POST["curpassword"];
$middlename = $_POST["middlename"];
$lastname = $_POST["lastname"];
$username = trim(mysqli_escape_string($con, $username));
$curpassword = trim(mysqli_escape_string($con, $curpassword));
$middlename = trim(mysqli_escape_string($con, $middlename));
$lastname = trim(mysqli_escape_string($con, $lastname));
$sql2= "SELECT user_Username FROM tbl_user WHERE user_Username='$username'";
$sql3= "SELECT user_Password FROM tbl_user WHERE user_ID='$accholder_ID'";
$result2 = mysqli_query($con, $sql2);
$result3 = mysqli_query($con, $sql3);
$row2 = mysqli_fetch_array($result, MYSQLI_ASSOC);
$row3 = mysqli_fetch_array($result2, MYSQLI_ASSOC);
if (mysqli_num_rows($result) == 1) {
echo "Sorry...This Username already exist..";
} else {
$query = mysqli_query($con, "Update tbl_user SET user_Mname = "$middlename", user_Lname = "$lastname", user_Username = "$username", user_Password = "$curpassword"");
if ($query) {
echo "Account Updated";
}
}
}
?>
I have a Code here that shows the data of the tbl_user in html form
but when it checks if the username existed
it will always echo "Sorry...This Username already exist.."
Since it will also include his own existing username in the check if it is submitted
Is there a way to bypass the check if the Username is unchanged
If you want to bypass check for unchanged username just add one check like:
Example:
if(trim($_POST["username"]) == $row['user_Username']){
//return unchanged username stuff
}
else{
// your stuff for changed username
}
If form value and database values are same it means username is unchanged else changed.
You can check directly by
if($_POST["username"] == $row['user_Username'])
{
echo "User Name Matched";
}
else
{
echo "Unique User Name";
}

PHP script not showing that you're logged in

I am learning PHP, and I'm busy with this tutorial over here:
https://www.youtube.com/watch?v=kebwxI1Bw88
I did everything according to the video and went over it 3 times, but my script isn't working... and I was wondering if anyone can help me figure out why? My code seems to be exactly like the guy's code on the video.
The video is about creating the login functionality for a forum. What happens with my script is.... It does what it's supposed to when I type in the WRONG user/pass combination (showing the message that it's supposed to show). But, when I type in the RIGHT user/pass combination... The file redirects to the index like it's supposed to... but it's still displaying the login form and not showing the "You are logged in as _ " message.
My Login Form on the index page:
if (!isset($_SESSION['uid'])) {
echo "<form action='login_parse.php' method='post'>
Username: <input type='text' name='username' />
Password: <input type='password' name='password' />
<input type='submit' name='submit' value='Log In'>
";
} else {
echo "<p>You are logged in as ".$_SESSION['username']." $bull; <a href='logout_parse.php'>Logout</a>";
}
My login_parse.php file:
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: index.php");
exit ();
} else {
echo "Invalid login information. Please return to the previous page. ";
exit ();
}
}
Check if $_SESSION['uid'] has a value.
print_r($_SESSION);
to see all the values

PHP/MySql Update Will Not Work

i have created 2 pages
update.php
edit.php
we start on edit.php so here is edit.php's script
<?php
$id = $_SESSION["id"];
$username = $_POST["username"];
$fname = $_POST["fname"];
$password = $_POST["password"];
$email = $_POST["email"];
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("a2670376_Pass") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE members SET username = '$username', fname = '$fname',
password = '$password' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
<form action="update.php" method="post">
<input type="hidden" name="id" value="<?=$id;?>">
ScreenName:<br> <input type='text' name='username' id='username' maxlength='25' style='width:247px' name="username" value="<?=$username;?>"/><br>
FullName:<br> <input type='text' name='fname' id='fname' maxlength='20' style='width:248px' name="ud_img" value="<?=$fname;?>"/><br>
Email:<br> <input type='text' name='email' id='email' maxlength='50' style='width:250px' name="ud_img" value="<?=$email;?>"/><br>
Password:<br> <input type='text' name='password' id='password' maxlength='25' style='width:251px' value="<?=$password;?>"/><br>
<input type="Submit">
</form>
now here is the update.php page where i am having the MAJOR problem
<?php
session_start();
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
mysql_select_db("a2670376_Pass") or die(mysql_error());
$id = (int)$_SESSION["id"];
$username = mysql_real_escape_string($_POST["username"]);
$fname = mysql_real_escape_string($_POST["fname"]);
$email = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
$query="UPDATE members
SET username = '$username', fname = '$fname', email = '$email', password = '$password'
WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
now on edit.php i fill out the form to edit the account "test" while i am logged into it now once the form if filled out i click on |Submit!| button
and it takes me to update.php and it returns this
(0) Not Updated
(0) <= id of user logged in
Not Updated <= MySql Error from
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
i want it to update the user logged in and if i am not mistaken in this script it says
$id = (int)$_SESSION["id"];
witch updates the user with the id of the person who is logged in
but it isnt updating its saying that no tables were effected
if it helps heres my MySql Database picture
just click here http://i50.tinypic.com/21juqfq.png
even with
session_start();
it wont work returns the same thinf as before
it appears that you have not started your session, therefore $_SESSION['id'] is not set.
session_start();
And, as always don't use mysql_* functions, that time has gone. Use mysqli or PDO
it seems your session might have times out or you did not even initialize it at all.
from your output it shows the id is 0 so there is your problem

sql Showing rows 0 - 0 (1 total) causing error with mysql_num_rows

right i have confirmed the query SELECT * FROM mbgeust WHERE user_name = '{$name}' AND user_pass = SHA1('{$pass}') returns a result but it returns saying 'Showing rows 0 - 0 ( 1 total, Query took 0.0005 sec)' sould that not be rows 0 - 1 as mysql_num_rows($mysql) is returning 0 despite the fact that the query returns one row here is my whole code
<?php
session_start();
include './inc/sql.php';
if(!isset($_SESSION['loggedin'])){
if(isset($_POST['submit'])){
$name = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);
sql_start();
$mysql = mysql_query("SELECT * FROM mbgeust WHERE user_name = '{$name}' AND user_pass = SHA1('{$pass}')")
or die ("Error: ". mysql_error(). " with query ". $mysql);
if(mysql_num_rows($mysql) == 1){
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $name;
header('refresh:3; URL = /');
die('You are now logged in!');
}
else{
header('refresh:3; URL = /');
die ('Password was probably incorrect!');
}
sql_stop();
}
echo "<form action='./' method='POST'>
Username: <br/>
<input type='text' name='username' /><br/>
Password: <br/>
<input type='password' name='password' /><br/>
<input type='submit' name='submit' value='Login'/>
</form>";
}
else {
include 'main.php';
}
?>
and sql.php
<?php
function sql_start(){
global $con;
$con = mysql_connect("mackinnonsbakery.co.uk.mysql","mackinnonsbaker","UE9ux3cZ")
or die('Could not connect: ' . mysql_error());
mysql_select_db("mackinnonsbaker", $con)
or die('Could not connect: ' . mysql_error());
}
function sql_stop(){
global $con;
mysql_close($con);
}
?>
You're calling mysql_real_escape_string prior to sql_start(), so you have no active database connection - so $name and $pass are probably set to false. Check your error logs you should see warnings.
I have switched to mysqli and changed the sql_start/sql_stop in to separate included files at the start and end of the page this seams to have sorted it if anyone knows how to fix this without moving to mysqli provide an answer as it will help others here is my code at present:
<?php
session_start();
include './inc/sql_start.php';
if(!isset($_SESSION['loggedin'])){
if(isset($_POST['submit'])){
$name = $mysqli->real_escape_string($_POST['username']);
$pass = $mysqli->real_escape_string($_POST['password']);
$query = "SELECT * FROM mbgeust WHERE user_name = '{$name}' AND user_pass = SHA1('{$pass}')";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 1){
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $name;
header('refresh:3; URL = /');
die('You are now logged in!');
}
else{
header('refresh:3; URL = /');
die ('Password was probably incorrect!');
}
$stmt->close();
}
}
echo "<form action='./' method='POST'>
Username: <br/>
<input type='text' name='username' /><br/>
Password: <br/>
<input type='password' name='password' /><br/>
<input type='submit' name='submit' value='Login'/>
</form>";
}
else {
include 'main.php';
}
include './inc/sql_stop.php';
?>
sql_start.php
<?php
$mysqli = new mysqli("mackinnonsbakery.co.uk.mysql", "mackinnonsbaker", "UE9ux3cZ", "mackinnonsbaker");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
sql_stop.php
<?php
$mysqli->close();
?>
again if anyone has the real solution please post it

Categories