View and change sessions variables in a browser - php

Debugging a PHP program, is there any add-on/plug-in for browser which I can view sessions variables (those PHP $_SESSION["foobar"] )?
Best if I can change the value in the variables.

There is no way to manipulate the values stored in sessions from the client side.
That's one of the main reasons you'd use a session over a cookie - YOU control the data.
With cookies, the user can manipulate the data.
The only way to access/manipulate session data from the client side would be with an Ajax call or other JavaScript mechanism to call another php script, which would be doing the retrieval/manipulation of the session data via the session_ functions.

$_SESSION is a server-side array of variables. If we could read or change the values, there are many things that we could do to hack or cause other bad things to happen.
However, using phpinfo(); we can view session variables - but we cannot change the value.
Even better, we can debug all session variables with
print_r($_SESSION);
//if you echo "<pre>" before, and a closing "</pre>" after, it prints very cleanly.
some other useful commands:
session_start(); // start session -- returns Session ID
session_destroy(); // unset all session variable
Session is an array so if you set $_SESSION['key']='value'; it is same like $array['key']=value; - only, what is special about $_SESSION - is that it persists until the window is closed, or session_destroy() is called.

You can use this code below:
<?php
error_reporting(E_ALL);
session_start();
if (isset($_POST['session'])) {
$session = eval("return {$_POST['session']};");
if (is_array($session)) {
$_SESSION = $session;
header("Location: {$_SERVER['PHP_SELF']}?saved");
}
else {
header("Location: {$_SERVER['PHP_SELF']}?error");
}
}
$session = htmlentities(var_export($_SESSION, true));
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Session Variable Management</title>
<style>
textarea { font: 12px Consolas, Monaco, monospace; padding: 2px; border: 1px solid #444444; width: 99%; }
.saved, .error { border: 1px solid #509151; background: #DDF0DD; padding: 2px; }
.error { border-color: #915050; background: #F0DDDD; }
</style>
</head>
<body>
<h1>Session Variable Management</h1>
<?php if (isset($_GET['saved'])) { ?>
<p class="saved">The session was saved successfully.</p>
<?php } else if (isset($_GET['error'])) { ?>
<p class="error">The session variable did not parse correctly.</p>
<?php } ?>
<form method="post">
<textarea name="session" rows="<?php echo count(preg_split("/\n|\r/", $session)); ?>"><?php echo $session; ?></textarea>
<input type="submit" value="Update Session">
</form>
</body>
</html>

Be aware however that while the session 'variables' are stored server-side, the Session ID is either in the GET/POST URL (a VERY BAD idea) or stored in a browser cookie, (better security), but still susceptible to manipulation/attack/etc if you don't hand Cookie based session IDs carefully.
http://en.wikipedia.org/wiki/Session_fixation
http://en.wikibooks.org/wiki/PHP_Programming/sessions#Avoiding_Session_Fixation

Related

How can I give an html element an ID taken from a php variable?

I am creating a website which uses php to get data from a phpmyadmin database and use the info from this database in my html.
I have this php query which finds the value from the 'ID' field and then creates a variable called '$studentID' with this value (which will be the number 2 in this case):
$result = $conn->query("select * from logins where usertype =
'student'");
$row = $result->fetch_array();
$studentid = $row['id'];
Then I have attempted to use this variable as the ID for an html element called 'rowcontainer':
<div class = 'rowcontainer' id = "<?php echo $studentid; ?> "></div>
Then I have set the background colour of this element using the id "2" to blue (using css):
#2 {
background-color: blue;
}
.rowcontainer {
width: 100%;
height: 30px;
}
When I use the inspect tool, the element 'rowcontainer' does appear to have an id of "2" like I want but the colour is still the default white and not blue.
inspect element html
inspect element css
Is there something I have missed, or a better way to achieve this?
While HTML5 is happy with an id starting with a digit it appears that CSS3 is not.
If you do stick with having and id that starts with a digit you can get CSS to pick it up by using an attribute selector - this says 'choose the element that has an id attribute with that string'.
[id='2']{
background-color: blue;
}
.rowcontainer {
width: 100%;
height: 30px;
}
<div id="2">id is 2</div>
Or you can prepend (not append) the id with an a-z character or string in your php like this:
<div class = 'rowcontainer' id = "id<?php echo $studentid; ?>"></div>
and then select this div by
#id2 {
background-color: blue;
}
Incidentally, beware of adding spurious space characters to strings. Your PHP puts a space after the 2. In some cases spaces matter (string matching on the whole) in some they don't.
First you need to know that you are using class & ID for for styling the same div. The answer of your question is dont pass numerical PHP values to html ID. In your case you are passing 2. Append this variable with some text then it will work.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.rowcontainer {
width: 100%;
height: 30px;
}
#2yes{
background-color: blue;
color: red;
}
</style>
</head>
<body>
<h1 class='rowcontainer' id="<?php print $id.'yes'" ?> > Hello </h1>
</body>
</html>

PHP comments appearing on the webpage

I commented out PHP comments on my script. but they still appear on my webpage in HTML. Do you have any idea how do I fix this?
kind regards,
/*if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not copied multiple times
require_once('LoginFunctions.php');*/
this text appear on my webpage:
my whole script:
Here is my whole script so you can identify where the mistake is.
<link rel="stylesheet" href="style.css">
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
include 'Header.php';
?>
<style>
body
{
background-color:#FFFFC2;
alignment-adjust: central;
float: none;
background-image: url("images_1/sea-sanctuaries-siteimage01.jpg");
alignment-baseline: central;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height:100%;
}
#div_1 {
width: 40%;
hight: 80%;
background-color: bisque;
border: 5px;
border-radius: 25px;
}
#div_2 {
font-family: sans-serif;
padding-bottom: 10px;
padding-right: 50px;
margin-top: 5px;
margin-right: 50px;
}
</style>
<body>
<div id="container">
<br>
<?php
/*
if($_DEBUG)
{
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
}
$page_title = 'Login';/* */
//in this page we do things slightly differently - the code for validation and displaying messages is done
//before we display the form
echo '<div id = "div_1><h1>Login</h1>';
//display the form
echo '<div id="div_2"><div id="div_2">
<form action="index.php" method="post">
<label>UserName<br>
<span class="small">enter your username</span>
</label>
<input type="text" name="UserName" value=""/>
<label><br>Password<br>
<span class="small">enter your password</span>
</label>
<input type="password" name="Password" />
<button type="submit" name="submit" value="Login" />Log in</button>
<input type ="hidden" name="submitted" value="TRUE">
</form>
</div>
</div>';
/* if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not copied multiple times
require_once('LoginFunctions.php');
//list() is a way of assigning multiple values at the same time
//checkLogin() function returns an array so list here assigns the values in the array to $check and $data
list($check, $data) = checkLogin($_POST['UserName'], $_POST['Password']);
if ($check) {
setcookie('FName', $data['FName'], time()+ 900 ) ; //cookie expires after 15 mins
setcookie('LName', $data['LName'], time() + 900 ) ;
//
//use session variables instead of cookies
//these variables should now be available to all pages in the application as long as the users session exists
$_SESSION['FName'] = $data['FName'];
$_SESSION['LName'] = $data['LName'];
$_SESSION['UserName'] = $data['UserName'];
//to enable $_SESSION array to be populated we always need to call start_session() - this is done in header.php
//print_r is will print out the contents of an array
//print_r($_SESSION);
//
//Redirect to another page
$url = absolute_url('Index.php'); //function defined in Loginfunctions.php to give absolute path for required page
$logged = true;
//this version of the header function is used to redirect to another page
header("Location: $url");//since we have entered correct login details we are now being directed to the home page
exit();
} else {
$errors = $data;
}
}
//create a sopace between the button and the error messages
echo'<div class="spacer"></div>';
if (!empty($errors)) {
echo '<br/> <p class="error">The following errors occurred: <br />';
//foreach is a simplified version of the 'for' loop
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
}
//this is the end of the <div> that contains the form
echo '</div>';
/* */
?>
</div>
</body>
<?php
include 'Footer.php';
?>
comment them inside PHP code sections
<?php /* code here will not display in html */ ?>
<!-- code here will be visible (in view source) -->
If your php interpreter is not running there's no way to hide php code.
You forgot one " in the line
echo '<div id = "div_1><h1>Login</h1>';
which apparently causes it, somehow, to continue echoing what comes after.
Solution: add the missing " after the div_1

How can I display userID in Sessions?

I would like to get except of the username and user ID in a page. About that I created two php pages. Also my database consists of 3 columns userid, username, password. The login.php page is
<?php
session_start();
//#$userid = $_GET['userid'];
#$username = $_POST['username'];
#$password = $_POST['pass'];
if(#$_POST['Submit']){
if($username&&$password)
{
$connect = mysql_connect("localhost","*****","") or die("Cannot Connect");
mysql_select_db("project") or die("Cannot find the database");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
//$query = mysql_query("SELECT * FROM users WHERE userid='$userid' and username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while ($row = mysql_fetch_assoc($query))
//while ($row = mysql_fetch_array($query))
{
$dbuserid = $row['userid'];
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername&&$password==$dbpassword)
{
echo "You are login!!!!! Continue now with the survey <a href='mainpage.php'>here</a>";
$_SESSION['username']=$username;
$_SESSION['userid']=$userid;
}
else
{
echo "<b>Incorrect Password!!!!</b>";
}
}
else
//die("That user does not exist");
echo "<b>That user does not exist</b>";
}
else
echo "<b>You must enter a username and a password</b>";
}
?>
<!--<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />-->
<title>Login Page</title>
<style type="text/css">
h2 {letter-spacing: 10px; font-size: .2in; background-color: #33CC00; color: #000000; text-transform:uppercase; width:260px}
span {color: #FF00CC}
legend {font-variant: small-caps; font-weight: bold}
fieldset {width: 260px; height: 100px; font-family: "Times New Roman", Times, serif; background-color: #CCCCCC; color: #000000}
label {display:block;}
.placeButtons {position: relative; left: 0px; width: 70px; margin: 5px; 0px;}
</style>
</head>
<body background="images/good.jpg">
<h2>Login Page</h2>
<form name="loginform" method='POST'>
<fieldset>
<legend>Form</legend>
<label>Username: <input type="text" name="username"/><span>*</span></label><br/>
<label>Password: <input type="password" name="pass"/><span>*</span></label>
<input class="placeButtons" type="reset" value='Reset'/>
<input class="placeButtons" type="submit" name="Submit" value='Login'/>
<a href='registration.php'>Register</a>
</fieldset><br>
<a href='firstpage.php'><-- Go Back</a>
</form>
</body>
</html>
and the page which is a welcome page of the user
<?php
session_start();
if ($_SESSION['username'])
{
//echo "Welcome, ".$_SESSION['username']."! <a href='logout.php'>Logout</a>";
echo "Welcome, ".$_SESSION['username']."<br>".$_SESSION['userid']. "<a href='logout.php'>Logout</a>";
}
else
die("You must be logged in!!");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />-->
<title></title>
</head>
<body background="images/good.jpg">
</body>
</html>
The problem is that in the welcome page it shows me only the username and not the UserID. What am I missing? Furthermore, I know that my login page is not the best and is a typical example of SQL injection attack. I have to improve it.
A quick thing i noticed. That might be the problem. The $_SESSION['userid'] is getting value from $userid which is not set. Also using # to supress your error is not a good practice. use isset to check if the variable is set and continue.
$_SESSION['userid'] = $userid; //where are you getting $userid from?
This should be
$_SESSION['userid'] = $dbuserid;
Also instead of using statement like
if ($_SESSION['username'])
First check if the variable is set like this
if ( isset($_SESSION['username']) ){
//now continue your work
}
and make sure you use ini_set('session_save_path', 'new_dir') or the function session_save_path when you are on a shared webhost. sessions that are in the same directory from different websites are prone to session stealing / snooping / modification.
I checked the PHP source code PHP doesn't keep track which session id's are made by with website (HOST) that why this attack works if the attacker has a account on the same webhosting
So never put to much trust in the SESSION array because you think it's safe because it's server generated
it's not if you don't make countermeasures...

php script- Allow one session only at a time

Please help me to validate one session only at a time, kindly see the below script which currently allows the same username to login any number of sessions.
I am not sure when and where to validate the session, help me in adding only those few lines which can validate the session for a username.
<?php // accesscontrol.php
include_once 'common.php';
include_once 'db.php';
session_start();
$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];
if(!isset($uid)) {
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<head>
<style type="text/css">
<!--
.style1 {
font-size: 16px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.style3 {
font-size: 12px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
body {
background-color: #D7F0FF;
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
-->
</style>
</head>
<body>
<h1 class="style1"> <br><br>Amogh Site - Login Required </h1>
<span class="style3"><br>
You <strong>must login to access this area </strong>of the site. <br>
<br>
If you are not a registered user, please contact your Admin
to sign up for instant access!</span>
<p><form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<span class="style3">User ID:
<input type="text" name="uid" size="12" />
<br>
<br />
Password:</span>
<input type="password" name="pwd" SIZE="12" />
<br>
<br />
<input type="submit" value="Login" />
</form></p>
</body>
</html>
<?php
exit;
}
$_SESSION['uid'] = $uid;
$_SESSION['pwd'] = $pwd;
dbConnect("hitek_svga3");
$sql = "SELECT * FROM user WHERE
userid = '$uid' AND password = '$pwd'";
$result = mysql_query($sql);
if (!$result) {
error('A database error occurred while checking your '.
'login details.\\nIf this error persists, please '.
'contact you#example.com.');
}
if (mysql_num_rows($result) == 0) {
unset($_SESSION['uid']);
unset($_SESSION['pwd']);
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Access Denied </title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<style type="text/css">
<!--
.style1 {
font-size: 16px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.style3 {
font-size: 12px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
-->
</style>
</head>
<body>
<br/>
<br/>
<h1 class="style1"> Access Denied </h1>
<p class="style3">Your user ID or password is incorrect, or you are not a
registered user on this site. To try logging in again, click
here. To access, please contact our Admin !</a>.</p>
</body>
</html>
<?php
exit;
}
$username = mysql_result($result,0,'fullname');
$_SESSION['user'] = mysql_result($result,0,'userid');
$_SESSION['email'] = mysql_result($result,0,'email');
$_SESSION['notes'] = mysql_result($result,0,'notes');
?>
Firstly, why are you storing passwords in session variables?
Secondly, your code assumes that the session variables 'uid' and 'pwd' will exist if the POST vars 'uid' and 'pwd' don't, so you'll need to make sure that either or exist before you allow your script to continue. This will have to be done AFTER the session_start() function:
<?php // accesscontrol.php
include_once 'common.php';
include_once 'db.php';
session_start();
if(
(!isset($_SESSION['uid']) || !isset($_SESSION['pwd'])) &&
(!isset($_POST['uid']) || !isset($_POST['pwd']))
{
//Redirect or throw exception or whatever
}
$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];
You should not:
Keep cleartext password in the database
Using mysql extension
Develop in 2012 without a framework
The point of the question is: how does PHP tell which user a request comes from? Last time I checked it used a token sent as a GET parameter or with a cookie in the HTTP request header section (I think it was called PHPSESSID).
Obviously to guarantee that nobody steals sessions, identity token must be exchanged over a secure channel, ie once the user logs in you have to generate a session id and disable plain HTTP sockets on port 80. The scripts that need a logged user must be kept in a separate host which only allows HTTPS on port 443.
The session ID will be assigned from the login script and will be kept in a column in the user table. BTW, regular applications use a separate table to associate sessions to user, but since you require one client per user a column in the user table is enough.
So when a request comes with a session token, your authorization logic will check in the user table if the token is still valid. It should use the token to authenticate the user, so if the request doesn't contain one or the token is not found in the database, you issue a 403 FORBIDDEN and suggest the login URL in the Location header - you can also write a HTML page with an <a> link in the case the agent doesn't automatically follows the redirect.
The login script is committed to update the column with the token, depending on what you want to do: invalidate the old session or prevent the creation of new ones until the user explicitely logs out on the other client (the latter causes troubles in the case the user can't access the old machine where he previously logged in from, maybe because if powered off the mobile device or because it was in a different building)

Ajax, PHP, MySQL retrieve data

i'm trying to auto retrieve data from mysql server in specific DIV without manual refresh the web page.
My PHP code is:
function lastCodes(){
include('mysql.php');
include('config.php');
echo "<div id='content_data'>";
$get = mysql_query("SELECT * FROM scripts ORDER by date_added DESC");
if(mysql_num_rows($get)>0){
while($row = mysql_fetch_assoc($get)){
$get2 = mysql_query("SELECT * FROM accounts WHERE username = '$row[s_owner]'");
while($red = mysql_fetch_assoc($get2)){
echo "<table>
<tr>
<td width='22px'>";
if(!empty($red['avatar'])){
echo "<center>
<img src='$red[avatar]' style='width: 52px; height: 52px; margin-left: -30px; border: 2px solid #fff;' title='$row[s_owner]'/>
</center>
</td>";
} else {
echo "<td width='22px'>
<center>
<img src='/theme/$tema/icons/empty_avatar.png' style='width: 52px; height: 52px;' title='$row[s_owner]'/>
</center>
</td>";
}
echo "<td>
<a style='font-family: IndexName; color: #000; font-size: 14px; margin-left: 5px;'><b>$row[s_owner]</b> написа <a title='$row[s_name], Категория: $row[s_category].' href='#' style='text-decoration: none;'>нов код</a> <a style='font-family: IndexName; color: #000; font-size: 14px; margin-right: 10px;'>в $row[date_added]</a>
</td>
</tr>
</table>";
}
}
}
echo "</div>";
}
What should be in my case the jquery/ajax code if I want to retrieve this information in DIV called "content_data" in interval of 5 seconds? Thanks a lot!
You could place the contents of your lastCodes() function inside an otherwise empty PHP file, let's call it lastCodes.php.
And then use the load function from JQuery on the page where you want to retrieve the data
<div id="divTarget"></div>
<script type="text/javascript">
$("#divTarget").load("lastCodes.php");
</script>
But keep in mind that this way of coding can get messy real fast. I would recommend you to try any of the many great template systems available. It's not necessary for clean code but without one you will need some discipline keeping logic out of your view code.
And when you feel comfortable with one of those you could go even further and try a template system on the frontend using Javascript, for example Handlebars. With one of those you will be able to write clean code and send your data using JSON which will lower the size of the HTTP response and at the same time make the data more usable for other scenarios than simply rendering it as HTML.
Edit: To update the data every 5 seconds:
<script type="text/javascript">
window.setInterval(function() {
$("#divTarget").load("lastCodes.php");
}, 5000);
</script>
You just have to use the setInterval() function to load the contents of the page every 5 seconds(5000 milliseconds)
</div>
<script src="jquery.js"></script>
<script>
setInterval(function(){
$('#container').load('page.php');
}, 5000);
</script>
I can see that you have a function so you might as well call it. If that doesn't work then try to put your code outside of the function.
lastCodes();
Be sure that its actually changing its contents and that the page that you're calling actually works, you can test it by accessing the page itself and see if it has any output.

Categories