i am making my own php game. So far i have made almost everything. Now to finish it, i need to get id from user who is logged in. I'm not so familiar with the functions and sessions. Please help.
This is what i made so far:
In my index page people login. then they are redirected to this.
So $_POST['username'] is where user type his user name in index.
<?php
$username = $_POST['username'];
include("Files/config.php");
$connect = #mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if($connect) {
if(mysql_select_db(DB_NAME)) {
$sql = mysql_query("SELECT * FROM users WHERE `username`='$username'") or die(mysql_error());
$gatherinfo = mysql_fetch_array($sql);
global $getid;
$getid = $gatherinfo['id'];
echo $getid;
function getuid() {
$_SESSION['getuid'] = $getid;
echo $getid;
}
}
}
else{ echo "Can not connect";}
?>
I searched other scripts for this, i found on one it says just $session->uid and it shows his id from mysql.
In mysql database i have table users with info about them
Id, username, password (password is hashed), email,...
Please help me if you can :D
At the beginning of index file (where your user logging in) start named session (be careful to avoid echo or print any values before session_start:
<?php //index.php
session_name('SAMPLESESSION');
session_start();
then when you will get the logged User ID, write this value to the session variable, like this:
.....
$_SESSION['uid'] = $getid;
.....
in the script you was redirected by your index file start session with the same name and get your user ID:
<?php //redirectedfromindex.php
session_name('SAMPLESESSION');
session_start();
echo $_SESSION['uid'];
....
If I right understand you, these that you need.
Related
I have made a web application. I have completed the registration and login. There are two user types that can register, student or professor.
I have a session running from the login time until logout. If you login as a user there are certain things you can do. One of them is close an appointment. This can be done from a radiobuton in a loginstudent.php (for example) page and submit button. This leads you to another .php page. On that page I have to use the username of the user that is logged in (in my case that would be the student) for a mysql query. I don't know how to access this.
$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id=(SELECT user_id FROM user WHERE username=$username);";
I think this is wrong.
edit
this is the complete login
<?php
session_start();
if (($_POST['submit'])) {
include_once 'dbh.php';
$username = $_POST['username'];
$password = $_POST['password'];
//check if empty
if (empty($username) || empty($password)) {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=empty");
die;
exit();
} else {
$sql = "SELECT * FROM user WHERE username='$username';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result); // tsekarei posa vrethikan
if ($resultCheck < 1) {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
die;
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
$hash_password_check = password_verify($password, $row['password']);
if ($hash_password_check == false) {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
die;
exit();
} elseif ($hash_password_check == true) {
//login
if ($user_type=="student") {
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['user_type'] = $row['user_type'];
header("Location: http://localhost/TexnologiaLogismikou/student.php?login=success");
die;
exit();
} else {
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['user_type'] = $row['user_type'];
header("Location: http://localhost/TexnologiaLogismikou/professor.php?login=success");
die;
exit();
}
}
}
}
}
} else {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
die;
exit();
}
then goes
<?php
include_once 'header.php';
?>
<script>
$(document).ready(function () {
$('#5').hide();
$("form input:radio").change(function () {
if ($(this).val() === "appointment") {
$("#5").show();
} else {
$("#5").hide();
}
});
});
</script>
<section class="main-container">
<div class="main-wrapper">
<form class="student-form" action="studentphp.php" method="POST">
<link href="style.css" rel="stylesheet" type="text/css"/>
<h4 id="9">Select your action:</h4><br>
<input type="radio" name="action" value="appointment">
<p id="8">Show your Appointments</p><br>
<input id="5" type="text" name="prof_last" placeholder="Professor Lastname">
<input id="6" type="radio" name="action" value="upload">
<p id="7">Upload a File</p><br>
<input type="submit" name="submit">
</form>
</div>
</section>
<?php
include_once 'footer.php';
?>
and this is the page i need the username
<?php
include_once 'header.php';
if (($_POST['submit'])) {
include_once 'dbh.php';
$prof_last = $_POST['prof_last'];
if (empty($prof_last)) {
header("Location: http://localhost/TexnologiaLogismikou/student.php?professorlastname=empty");
die;
exit();
} else {
$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id=(SELECT user_id FROM user WHERE username=$username);";
mysqli_query($conn, $sql);
}
} else {
header("Location: http://localhost/TexnologiaLogismikou/student.php"); //se ksanapaei sto sign up
die;
exit();
}
?>
<?php
include_once 'footer.php';
The approach i think you should use is:
Firstly, i suppose that you have created some sort of 'user-roles' table to manage the different user access levels (for professor and for student).
After a user has logged in with their username and password, you can access their account details (their real name or username, whichever), and save this value in the session variable. It will look like:
$_SESSION["username"] = "some-user-name";
You can store other info here as well, such as the user's real name, like:
$_SESSION["display-name"] = "the user's name";
When the logged-in user navigates to the any other page, you can get their information from the session variable like this:
$username = $_SESSION['username'];
$displayName = $_SESSION['display-name'];
You can then do whatever you like with them.
After reading through the posted code, i think your goal is to help a student set up an appointment with a professor. And you would like to access the professor record in the database by matching it with the professor's last name. Correct me if i am wrong. If this is the case, then i advise you to change your approach slightly. Look at it like this. If a user logs in successfully (prof or student), store their user_id as well. It will help you later, like this:
$_SESSION["user-id"] = $row['id'] //or
$_SESSION["prof-id"] = $row['id'] //or
Secondly, when a student would want to set/close an appointment, i suggest that you:
Read all the professors' full names and database ids from the the student's department (or from the database table) into an html select tag, something like [select value=""][/select]
This will save you from using the 'last-name' as a matching field in the database. Someone might write 'johns' or 'Johns', or even 'Johns '. These are all the same to a human reader but are different to the database.
You can assign the value field in the select tag to the database id of the professor, with the corresponding professor name.
Something like [select value="1"] Prof. Jonathan Andrews[/select] , etc
That way, there is no need for a student to type (or even know) the last name of the professor. They would select the professor's name.
Lastly, when reading the appointments from the database, you can use the professor id from the select tag and the student id from the session variable. If your select tag is named 'prof-id', you can get the POSTed value with:
$profId = $_POST['prof-id'];
#get the student id from the session var
$studentId = $_SESSION['user-id']
$newQuery = "SELECT * FROM appointment WHERE prof_id = $profId AND student_id = $studentId";
Let me know if understand this and can continue from there. If you need the code, let me know.
well, if you store the username in the $_SESSION already, you can access it anywhere. Just make sure to call session_start() at the top of the PHP script every time you want to use it.
You state that you have login pages working, and sessions working.
A session is serverside storage tied to a connection. So the typical way to handle this (in simplest terms)
if (you accept that user logged in) {
// From the database row you used to check username/password
$_SESSION['userId'] = $row['user_id'];
} else {
//Login failed
}
Depending on how you wrote your login check sql statement you might have to adjust it to include the user_id for this to work.
Once this is working, anytime you need the user_id of the currently logged in user, you have it available in the session. For a secured site, this might be on nearly every request.
Now your sql statement is simpler:
$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id={$_SESSION['userId']}";
Here's where I will admonish you that all your SQL statements should be using bound parameters rather than variables embedded in strings, but that is not the crux of your question.
Also you might be able to save yourself some time and code by storing an array to $_SESSION so that you don't need to set every user table variable individually.
You can do this:
$_SESSION['user'] = $row;
Then later you can reference:
echo $_SESSION['user']['username'];
I downloaded a php login source and now it works and it even logs in. when it logs in it shows your name with
<?php echo $_SESSION['username']; ?>
but i also want to display there balance by putting
<?php echo $_SESSION['balance']; ?>
But it doesnt display the balance?
https://gyazo.com/7cd0a7888ac976590391888925d0c18f
I added the balance table to the existing tables.
I really dont know what to do! :(
Please Insert;
<?php session_start(); ?>
In every page where you want to access $_SESSION global array.
in your case;
<?php session_start(); ?>
$_SESSION['balance'] = 1000;
echo $_SESSION['balance']; // will output 1000.
suppose this page was set-session-value.php and you want to get this $_SESSION['balance'] value in get-session-value.php do as follow in get-session-value.php file;
<?php session_start(); ?>
echo $_SESSION['balance'];
In your login.php add this line after setting session for username
$_SESSION["balance"]=$balance;
And in your home, it is always advised to check if session exists and then print it. So,
if(isset($_SESSION["balance"])){echo $_SESSION["balance"]; }
start session before use
<?php
session_start();//start session
$_SESSION['username']='abc';//Set value session
$_SESSION['balance']=10;
echo $_SESSION['username']; //Use value of session
echo $_SESSION['balance'];
?>
please use this process for session use
When you logged into your application.After that you should want to add following code into top of the page.
session_start();
$_SESSION['username'] = $userNameValue;//set user name
echo $_SESSION['username'];
And then you should want to fetch data related to who logged user from your user table by using query.
Example
$query = "SELECT * YOURTABLENAME WHERE username='$_SESSION['username']'";
mysql_query($query, $connection) or die(mysql_error());
$data = mysql_fetch_array($query);
Then you can assign to $_SESSION['balance'] for value like this;
$_SESSION['balance'] = $data['balance'];
echo $_SESSION['balance'];
I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>
First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.
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