I have the following login script, where i do use sessions.
<?php
session_start();
if(isset($_SESSION['logged_in'])){
$id = $_SESSION['id'];
header("Location: start.php?id=$id");
exit();
}
if(isset($_POST['submit'])){
$x1 = $_POST['x1'];
$x2 = $_POST['x2'];
...
$query = $db->query("SELECT * FROM table WHERE x1='".$x1."' AND x2='".$x2."'");
if($query->num_rows === 1){
$row = $query->fetch_object();
$id = $row->id;
$_SESSION['logged_in'] = true;
$_SESSION['id'] = $id;
header("Location: start.php?id=$id");
3more queries
exit();
start.php will be just:
<?php
echo $_GET['id'];
?>
I thought $_GET['id'] would be stored on the server so that $_GET should be displayed. The fetch_object is working. I know that, because it will be displayed the right way at "id=$id" at the browser. So would someone be that friendly and could help me out. Thanks!
The $_GET superglobal is defined as part of the URL string:
http://example.org/index.php?foo=bar&baz=1
In index.php:
echo $_GET['foo']; // bar
echo $_GET['baz']; // 1
So $_GET is not stored on the server, but is passed with each HTTP request, as is $_POST, but that is passed in the HTTP headers rather than simply appened to the end of the URL.
$_GET variables are those passed via the URL, i.e. index.php?foo=bar&baz=qux (foo equals bar, baz equals qux).
These variables are not stored on the server as a part of the session, but rather only exist with that request. If you want to store information on the server as a part of the session, you should use $_SESSION instead, which will exist within the current session, regardless of the request.
Related
At the moment I am writing a little media library in PHP and i want to set sessions, so the user stays logged in and get's echoed his name at the front page.
[index.php]
if(isset($_SESSION['loggedin']))
{
//ECHO $USERNAME
}else{
echo '<p>To start, please login or register.</p>';
}
?>
I want, if theres an session id set, that PHP echoes out the $username.
[signup.php]
<?php
session_start();
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
$uid = ($_POST['uid']);
$pw = ($_POST['pw1']);
$pw2 = ($_POST['pw2']);
if ($pw == $pw2) {
$sql = "INSERT INTO user (uid, pw) VALUES ('$uid', '$pw')";
$result = mysqli_query($conn, $sql);
echo "Registration succeeded.";
}else{
echo "Please check your information.";
}
header ("Refresh: 3; ../index.php");
So, after PHP successfully compares my $pw1 and $pw2 i want to start a session, then it should put the $username in the $_SESSION array.
Of course next to the secure session id.
I repeat, after this i want to echo the $username out at front page.
What is the best way to do it?
Thanks.
$sql="SELECT username FROM users WHERE userid=$uid";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($result);
$_SESSION['username']=$row['username'];
You can do something like this.
Usage of $_SESSION super global array (compact version)
session_start(); //To init
$_SESSION['username'] = 'Bob'; // Store value
echo $_SESSION['username']; // Treat like normal array
Detailed example
To use a session, you have to init it first.
session_start();
After that you access the session vars via the super global
$_SESSION
A good way is always to store a value in your variables you want to use:
// init session
session_start();
// check if session var is set, if not init the field with value in the super global array
if(!isset($_SESSION['auth'])) $_SESSION['auth'] = false;
if(!$_SESSION['auth']) {
//do auth here like eg.
header('Location: signup.php'); // if auth is okay -> $_SESSION['auth] = true + redirect to this (main) script
die(); // This is really necessary because a header redirect can be ignored.
}
// if auth okay, do fancy stuff here
For security read the following
Remember to escape your user input, always!
How can I prevent SQL injection in PHP?
The session_id is stored in cookies normally.
Or - the old way via URL parameter.
You do not have to secure the session_id.
Read also advices about XSS/CSRF.
Plus tokens are also good.
May be this is what you mean with secure session_id.
Stackoverflow: preventing csrf in php
OWASP: https://www.owasp.org/index.php/PHP_CSRF_Guard
OWASP: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
How to post values to loginchk_coustomer.php given in below code, not through Url by any other way.
Is there any other way to post these value to loginchk_coustomer.php becoz it is not secure.
<?php
include "include/connect.php";
$user_name = $_REQUEST['user_name'];
$password = $_REQUEST['password'];
//echo "select * from school_info where school_id='$user_name' and school_password='$password'";
$sql_query = mysql_fetch_assoc(mysql_query("select * from school_info where school_id='$user_name' and school_password='$password'"));
$db_username = $sql_query['db_username'];
$db_password = $sql_query['db_password'];
$db_databasename = $sql_query['db_databasename'];
echo "<script>";
echo "self.location='member/loginchk_customer.php?db_username=$db_username&db_password=$db_password&db_databasename=$db_databasename&user_name=$user_name&password=$password'"; // Comment this line if you don't want to redirect
echo "</script>";
?>
You need to create a session to store all that information.
Here's what they are - from http://php.net/manual/en/features.sessions.php:
Session support in PHP consists of a way to preserve certain data across subsequent accesses.
To start a session write at the beginning of your code:
session_start(); // needed in all pages that will use the variables below
and then after your assign the information this way:
$_SESSION['username'] = $sql_query['db_username'];
$_SESSION['password'] = $sql_query['db_password'];
$_SESSION['databasename'] = $sql_query['db_databasename'];
All the information will persist on those variables along the site until you do:
session_destroy();
I also recommend you not to redirect with javascript, but this way in PHP:
header('Location: member/loginchk_customer.php');
Possibly after checking this answer you will think about to change the way you check the login information. But that's okay. It's the way of learning.
More information about sessions: http://php.net/manual/en/book.session.php
I hope this helps.
Let's say I have the following URL:
http://test/order?id=263&name=John
A php file handles the URL and I use $_GET to take the data from the URL and bind it to a variable:
<?php
$id = $_GET['id'];
$name = $_GET['name'];
?>
As it stands now, the user is able to change the URL and subsequently the values of the variables. I want the variables to be bound once and not to be subjected to change after. Is there any way to do that with PHP?
you could actually store them in session....
1)at the very top of the page initialize the session
2) check if the value in session exists and if not create it.
at this point every further change will not be taken in consideration,
<?php
session_start();
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = [
'id' => (int) $_GET['id'], //Cast the id to int
'name' =>urldecode($_GET['name']) //url decode the name
];
}
Now you have your data stored in session and you can call it using:
$_SESSION['user']['id']
$_SESSION['user']['name']
and they will never be overwritten, if you want to be updated on every call or change it if some parameter has been passed you can add some option in the condition
if (!isset($_SESSION['user']) && $_GET['updateData') == 1) {
$_SESSION['user'] = [
'id' => (int) $_GET['id'], //Cast the id to int
'name' =>urldecode($_GET['name']) //url decode the name
];
}
<?php
start_session();
if(isset($_SESSION['name'])){
$name = $_SESSION['name'];
$id = $_SESSION['id'];
} else {
$_SESSION['id'] = $_GET['id'];
$id = $_GET['id'];
$_SESSION['name'] = $_GET['name'];
$id = $_GET['name'];
}
?>
You could try something like this.
Just save those variables in session or in some file until session is closed, if you have long session (login/logout). You can create array in session and keep there all these ids along with session ids. Hope that helps
I am passing the following variables from a query through a link:
<a href="middle.php?name=<?php echo $name; ?>&id=<?php echo $id1; ?>&rowid=<?php echo $rowid; ?>&record=<?php echo $record; ?>">
The variables are being passed to this page:
session_start();
//$id = ($_GET['id']);
if (isset($_GET["record"])) {
$_SESSION["record"] = $_GET["record"];
}
if (isset($_GET["id"])) {
$_SESSION["id"] = $_GET["id"];
}
if (isset($_GET["rowid"])) {
$_SESSION["rowid"] = $_GET["rowid"];
}
if (isset($_GET["name"])) {
$_SESSION["name"] = $_GET["name"];
}
if (isset($_GET["store"])) {
$_SESSION["store"] = $_GET["store"];
}
and then users are redirected to this page where Im trying to use the assign the session variables to variables in the page like this:
session_start();
$id = $_SESSION[id];
$rowid = $_SESSION[rowid];
$name = $_SESSION[name];
$record = $_SESSION[record];
The variables arent accessible as I need them to be on this page. Am I missing quotes? What is the best way to use the session variables again?
FYI they're mainly being used in other queries like this:
"SELECT * FROM mgap_orders WHERE mgap_ska_id = '" . $_SESSION['id'] . "' AND mgap_status = 0 GROUP BY mgap_ska_report_category LIMIT 5";
Am I missing quotes?
Yes. You say you're accessing them like this:
$id = $_SESSION[id];
That should be this:
$id = $_SESSION['id'];
But even more to the point, why do you need to use session here at all? The way you describe the situation is:
User makes a request with query string values in the link.
In the response you forward the user to another page (presumably using the location header?).
On the last page the values need to be present.
If they're query string values, keep them as query string values in the redirect. So where you may have something like this:
header('Location: somePage.php');
you can include the values:
header('Location: somePage.php?name=' . $name');
and so on for the remainder of the values, just like you do when building the original link for the page which performs the redirect.
Also, while you don't show your data access, you do show your query which appears to be vulnerable to SQL Injection attacks. Ultimately the values you're using are coming from user input (query string) so you shouldn't directly concatenate them into SQL queries.
I have this problem. Session does not work when I use with $_POST. If I add 63 manualy it will works across pages. I can see the output 63.
$_SESSION['name'] = 63;
echo $_SESSION['name'] ;
but this below won't work when I switch between pages. The $row['id'] output is also 63.
$cari = "SELECT id FROM dns_soa WHERE `origin` = '".$_POST['origin']."'";
$keputusan = mysql_query($cari);
$row = mysql_fetch_array($keputusan);
$_SESSION['name'] = $row['id'];
echo $_SESSION['name'] ;
When I go to 2nd pages I can see the output but when I went back to 1st pages the output is gone. Any idea?
Because when you are coming back it will again set the session variable, as this time you don't have the $_POST[origin] variable that leads to $row['id']="" and the session variable also NULL...
What you should do is..
$cari = "SELECT id FROM dns_soa WHERE `origin` = '".$_POST['origin']."'";
$keputusan = mysql_query($cari);
$row = mysql_fetch_array($keputusan);
if(!isset($_SESSION['name']))
$_SESSION['name'] = $row['id'];
echo $_SESSION['name'] ;
When you go back to the page where you have used $_POST, $_POST becomes empty, unless your browser posts it again. So the SQL query returns no result. Hence, $_SESSION['name'] becomes empty.
Also make sure you have invoked session_start on every page before using $_SESSION