$_SESSION display not reflecting changes after hitting submit once - php

I'm creating a profile page where the name of the user can be edited. I can't seem to figure out how to update the name of the user that is displayed at the top page (i.e. Hi Kana!) after a successful edit.
The name is generated using a session variable at the top of my page, $_SESSION['username']
<?php
session_start();
if(isset($_POST['submit']) && isset($_SESSION['newusername'])){
unset($_SESSION['username']); //clear existing username session
$_SESSION['username'] = $_SESSION['newusername']; //replace with the new username
echo $_SESSION['username'];
} else {
echo $_SESSION['username'];
}
?>
After hitting the submit button with a different name set on the text input it should change but it does not. These are the lines of codes after the code I mentioned above.
<?php
$textinput = $_POST['textinput'];
if(isset($_POST['submit']))
{
if(strlen($_POST['textinput']) < 2)) {
$errormessage = 'too short';
}
else
{
$_SESSION['newusername'] = $textinput; //setup a new session for the new username to be used above.
}
}
?>
Note that the two quoted set of codes are in the same page.
What happens is that the name still shows the previous name, which is supposedly overwritten. I tried refreshing the page but it still does not change, I need to submit again (2nd time) to show the new name.

You can and should drastically simplify your code. Currently there are a variety of unnecessary operations here. Consider semantically what you want to accomplish:
If the user submits their name, update the session with the new value. Then output the value.
That's it. Let the semantics of what you want to accomplish guide how you accomplish it. Start the session, check for the form post, conditionally update the value, output the current state of the value. For example:
<?php
session_start();
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>
Maybe you'll want to add a sensible default in the absence of a username. That would just be something like:
<?php
session_start();
// set a default value
if (!isset($_SESSION['username'])) {
$_SESSION['username'] = "Default User";
}
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>

Related

PHP wont redirect from log-in form

I am making an html login page which will submit a form to a php page to check to see if user details lie in an established username access database.
If the username and password correspond to a row in the database, the php redirects to an mainpage (mainpage.html), otherwise it redirects back to the login page (LOGINPAGE.html).
The if function I have used to achieve this in my php script is as follows:
if(odbc_fetch_row($DetailCheckExec)) //If username corresponds with password
header('Location: mainpage.html');
else
header('Location: LOGINPAGE.html');
The problem is, the php doesn't seem to redirect. Even if I simplify my code to simply redirect, nothing changes. i.e.
<?php
header("Location: LOGINPAGE.html");
exit;
?>
won't work either.
Any help is appreciated thank you.
well i dont know the function "(odbc_fetch_row($DetailCheckExec)" but there's a step by step login that I made i hope it works
if ((isset($_POST['user'])) and (isset($_POST['password'])))
{//checks if the inputs in the form are empty
//sets two variables with the value of the imputs
$usuario = $_POST['user'];
$clave = $_POST['password'];
//then selects the row where the values are equal in the database
$consulta = "SELECT usuario, contrasena FROM `usuarios`
WHERE usuario = '$usuario' and contrasena = '$clave'";
$resultados=mysqli_query($con,$consulta);
while(($fila=mysqli_fetch_array($resultados))){
$vpeso = $fila['peso'];
$vestatura = $fila['estatura'];
$vusuario = $fila['usuario'];
}
if(($resultados) AND ((isset($vusuario)) and ($vusuario <> '') )){
//starts session
session_start();
//stablishes the user in the session
$_SESSION['usuario'] = $usuario;
//if the user doesn't exist it will bring to signup.php for example
}else{
header("Location: signup.php");
}
}
well I hope it works, sorry for not changing the variable names haha

How to use a variable in 2 different Php files?

I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.

php "else" code redirecting instead of echo-ing

Just trying to make a login page in php.. Here the if code is working but else code is not working.. it is also working if code.. instead of printing message..
here is the code:
session_start(); //session starts
$con=mysql_connect('localhost','root','');// connecting to ..........
mysql_select_db('news_db'); //connectin to db
if(isset($_POST['login'])) //if button login is pressed
{
$name=$_REQUEST['username'];//getting name
$password=$_REQUEST['password']; //getting password
$qyer=mysql_query("select * from news_tb where username='$name' and password='$password'"); //selecting fields
$row=mysql_fetch_array($qyer); //fetching values in row
if($row['username']==$name && $row['password']==$password)// condition to match the fields with database
{
header("location:news1.php"); // on else also this page is opening
}
else
{
echo "pls enter valid information"; //redirects to if condition and doesnt print the msg
}
}
Its because by pressing send or whatever, you post the code to the script. All you are doing is checking if it has been posted, not if the variables themselves are empty. Then if you have an empty row in mySQL, you will never use the else.

Pass the login details to another page using session PHP

I need the login details in another page for retrieving the data from the database. Basically, I need to display the editable form with the details of the user logged in. I tried session_register() for storing the username in login.php page. But for some reason I am not able to display the username using $_SESSION[] in my edit.php page. I am doing this after the function session_start() as well.
I am new to php, so don't know whether I misunderstood session! Or is there any other way to pass the login details?
Thanks in advance
My code:
**Login.php**
<?php
$userName = $_POST['username'];
$password = $_POST['password'];
//Connect to the database
//query the database
if($rows==1)
{
session_start();
$_SESSION['user']=$userName;
header("location:edit_user.php");
}
else
{
echo 'Data Does Not Match <br /> Re-Enter UserName and Password';
}
?>
**In edit.php**
<?php
session_start();
if(!isset($_SESSION['user']))
{
header("location:login_form.php");
}
else
{
echo $_SESSION['user'];
}
?>
First of all make sure that you place session_start() at the very beginning of any script you use it in. There can be no output to the browser before you call session_start() and that includes spaces or new-lines before the opening <?php tag.
So:
<?php
session_start();
...
Second, make sure you terminate your script after a redirect, for example:
header("location:edit_user.php");
exit();
That makes sure that no code after the redirect gets executed, so sessions won't get unset or session variables changed by accident.
session_register() is a deprecated function. Just use $_SESSION["bar"] = "foo" to store something.
for future references, please post parts of your code when you are asking questions. It helps everyone to give you an answer in more specific cases.
<?php
session_start();
if(!isset($_SESSION['Foo']))
{
$_SESSION['Foo'] = "Bar";
}
?>
Source : http://php.net/manual/en/features.sessions.php
you can retrive data from the database like this
//start connection
$connect = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);
if(!$connect){
die("Database connection Error".mysql_error());
}
//select database
$db = mysql_select_db(DB_NAME);
if(!$db){
die("Database selection Error".mysql_error());
}
//get data
$login = mysql_query("SELECT * FROM TABLENAME where user_id={$_SESSION['user_id']}");
$login_data = mysql_fetch_array($login);
now $login_data array has the user details which you can point to form text field values..
the $_session['user_id']=$login_data['user_id'] value has to be assigned earlier which stays in the $_SESSION global variable through out the session

PHP Session Management - Basics

i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? ยป Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.

Categories