$_SESSION doesn't seem to work across files? - php

I am making a game for my computing class. The user has to change settings of their robot before playing. Most are using Visual Basic or Game Maker but I felt more comfortable with web based languages.
The issue I have just run into is when I am checking whether $_SESSION variables are set. This is a screenshot of my script:
http://i60.tinypic.com/2ia4hnr.jpg
As you can see on the left their is a button called "Play". On the customisation page the user fills in all the settings and they are stored as $_SESSION variables however when I use the If statement on all other pages it always sees them as not being set, so it does not allow them to play.
This is the customise.php page code (sorry for posting all the code but I felt it was needed for me to best explain my issue):
<?php $layout_context = "public"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<h2><i><u>Navigation</u></i></h2>
<br />
<u>Welcome<br /><br />
<u>How to Play?</u><br /><br />
<u><font color="orange">Customisation</font></u><br /><br />
<?php if (isset($_SESSION['RobotName'], $_SESSION['traction'], $_SESSION['passenger'])) {
?>
<u>Play</u>
<?php
} else {
?>
<u>Play</u>
<?php
}
?>
</div>
<div id="page">
<h1>Robot Customisation</h1>
<br />
<p><h3>Welcome to the BotMod Robot Customisation!</h3><br />
Below you will have three options that enable you to play BotMod. Those are: Your Robot name, Traction Type and Passenger Size.<br /> See the bottom of this page for further guidance.<br /><br />
<br />
<form id="settings" name="settings" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h4>Robot Name:</h4> <input type="text" name="RobotName"><br />
<h4>Traction Type:</h4>
<select name="traction">
<option value="">Please Select Your Traction Type...</option>
<option value="Wheels">Wheels</option>
<option value="Tracks">Tracks</option>
<option value="Skis">Skis</option>
</select>
<br />
<h4>Passenger Size:</h4>
<select name="passenger">
<option value="">Please Select Your Passenger Size...</option>
<option value="Large">Large</option>
<option value="Medium">Medium</option>
<option value="Small">Small</option>
</select>
<br />
<input type="submit" name="Submit" value="Save Settings" />
</form>
<?php
require_once("session_start.php");
// Store all submitted $_POST fields to their own $_SESSION ID to be called
// later. Must use session_start();
if (isset($_POST['Submit']) && $_POST['RobotName'] != '' && $_POST['traction'] != '' && $_POST['passenger'] != '') {
$_SESSION['RobotName'] = $_POST['RobotName'];
$_SESSION['traction'] = $_POST['traction'];
$_SESSION['passenger'] = $_POST['passenger'];
} elseif (isset($_POST['Submit'])) {
echo "<br />";
echo "<br />";
echo "<strong>Error: You must complete all fields on this page!</strong><br />";
}
?>
<br />
<style>
div.container
{
width:30em;
border:1em solid;
}
div.box
{
box-sizing:border-box;
-moz-box-sizing:border-box; /* Firefox */
width: 50%;
border: 1em solid red;
float: left;
}
</style>
<?php if (isset($_POST['Submit']) && $_POST['RobotName'] != '' && $_POST['traction'] != '' && $_POST['passenger'] != '') {
echo "<h4>Your Settings (Click Play BotMod) to begin.</h4>";
?>
<div class="container">
<div class="box"><strong><i>Robot Name:</i></strong> <?php echo $_SESSION['RobotName']; ?><br /></div>
<div class="box"><strong><i>Traction:</i></strong> <?php echo $_SESSION['traction']; ?><br /></div>
<div class="box"><strong><i>Passenger:</i></strong> <?php echo $_SESSION['passenger']; ?><br /></div>
<div class="box"><strong>Play BotMod</strong><br /></div>
<div style="clear: both;"></div>
</div>
<?php
}
?>
</div>
</div>
<?php include("footer.php"); ?>
As you can see I have created an If statement on the play navigation.
<?php if (isset($_SESSION['RobotName'], $_SESSION['traction'], $_SESSION['passenger'])) {
?>
<u>Play</u>
<?php
} else {
?>
<u>Play</u>
<?php
}
?>
This doesn't work on any of the pages: customise.php index.php or instructions.php.
I have created the variables on the customise.php page with this code:
If (isset($_POST['Submit']) && $_POST['RobotName'] != '' && $_POST['traction'] != '' && $_POST['passenger'] != '') {
$_SESSION['RobotName'] = $_POST['RobotName'];
$_SESSION['traction'] = $_POST['traction'];
$_SESSION['passenger'] = $_POST['passenger'];
} elseif (isset($_POST['Submit'])) {
echo "<br />";
echo "<br />";
echo "<strong>Error: You must complete all fields on this page!</strong><br />";
}
?>
My index.php navigation code:
<u><font color="orange">Welcome</font><br /><br />
<u>How to Play?</u><br /><br />
<u>Customisation</u><br /><br />
<?php require_once("session_start.php"); ?>
<?php if (isset($_SESSION['RobotName'], $_SESSION['traction'], $_SESSION['passenger'])) {
?>
<u>Play</u>
<?php
} else {
?>
<u>Play</u>
<?php
}
?>
So does anyone know why the $_SESSION variables do not seem to work? I am using MAMP for this at the moment just in case that has something to do with it.

session_start(); must be called at the top of every page where you use the $_SESSION variable.
Documentation: http://php.net/function.session-start

use session start method
example :
session_start();

You need to call session_start() before accessing any session variables

Related

Where to put $_Session[variable] in the code

Im trying to save a variable in the $_Session[deptselect] and call it in a different page but confused to where to declare it. when i echo $_Session[deptselect] it gives blank.
I have already tried in multiple places like inside the form or below it but nothing seems to work. i want to send it from appointment to appointment2 but appointment2 seems to not get the variable.
I have already tried to use $_post[deptselect] to get the value in second page and i get it there but it disappears as soon as i press submit in the second page.
appointment.php
<?php
include("dbconnection.php");
session_start();
if(!isset($_SESSION['username'])) {
die("Please login");
}
$_SESSION['deptselect']=$_POST['deptselect'];
?>
<form class="" action="appointment2.php" method="post">
<fieldset>
<legend>Appointment</legend>
<label>Select Department</label>
<select class="" name="deptselect" required>
<option ></option>
<?php
$deptsql=mysqli_query($con,"select deptname,deptid from department where status='1'");
while ($row = mysqli_fetch_assoc($deptsql))
{
echo "<option id='deptselect' value='" . $row['deptid'] ."'>" . $row['deptname'] ."</option>";
}
?>
</select>
</fieldset>
<input type="submit" name="submit" value="Submit">
</form>
<?php
include("footer.php");
?>
appointment2.php
<?php
session_start();
if(!isset($_SESSION['username']))
{
include('footer.php');
die("Please login");
}
if(!empty($_POST)){
include("dbconnection.php");
$dept=$_SESSION['deptselect'];
echo $dept;
$daate=$_POST['date'];
$doc = $_POST['doc'];
$tiime=$_POST['time'];
$user=$_SESSION['username'];
$pd="SELECT * from patient where name='$user'";
$pid=mysqli_query($con,$pd);
while($row = mysqli_fetch_assoc($pid)){
$piid=$row['pid'];
}
$query="insert into appointment (deptid, docempid,pid,apptime,appdate) VALUES ('$dept','$doc','$piid','$tiime','$daate') " ;
//$res=mysqli_query($con,$query);
// echo "$query";
//echo "$dept";
}
?>
<body>
<form class="" action="appointment2.php" method="post">
<label>Select doctor</label>
<select class="" name="doc" >
<option ></option>
<?php
$dee=$_POST['deptselect'];
$_SESSION['id']=$dee;
$sql="SELECT * FROM doctor where deptid='$dee'";
$docsql= mysqli_query($con,$sql);
while ($row = mysqli_fetch_assoc($docsql))
{
echo "<option value='" . $row['docempid'] ."'>" . $row['name'] ."</option>";
}
?>
</select>
<br><br><br>
<label>Enter Time</label>
<input type="time" name="time" placeholder="enter time" >
<br><br><br>
<label>Enter date</label>
<input type="date" name="date" placeholder="enter date" >
<br> <br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
<?php include("footer.php");
?>
I want the $_session[deptselect] in appointment2.php so i can run the command the insert, i have zero knowledge of js so doing the dependent list thing is not possible. TIA
In the beginning of the first script you have:
if(!isset($_SESSION['username'])) {
die("Please login");
}
And in the beginning of the second:
if(!isset($_SESSION['username']))
{
include('footer.php');
die("Please login");
}
Both stop immediately, if $_SESSION['username'] is not set.
So how should $_SESSION['username'] ever be set, if your body code is never executed?

Simple guest list. Do not show first added record

I wrote a simple list of guests. The problem is that when you add the first entry in this list is not displayed and each following is added as expected.
Maybe there is a better way to perform this task?
The script is designed to create a simple list of guests. I wonder whether the transmission of using a GET method in this case is appropriate.
<body>
<div style="float:left; vertical-align:top;">
<h2> Guest list </h2>
<?php
if (isset($_GET['my_list']))
{
$list = $_GET['my_list'];
$explode = explode(',', $list);
array_pop($explode);
foreach($explode as $name)
{
echo $name.'<br>';
}
}
?>
</div>
<div style="float:right; vertical-align:top;">
<h2> New entry: </h2>
<form method="GET">
<input type="text" name="new"><br>
<input type="hidden" name="my_list" value="
<?php
if (isset($_GET['my_list']))
{
if (isset($_GET['new']))
{
echo $_GET['new'].','.$_GET['my_list'];
}
else
{
echo '';
}
}
else
{
if (isset($_GET['new']))
{
echo $_GET['new'];
}
else
{
echo '';
}
}
?>">
<input type="submit" name="send" value="Save"><br>
</form>
</div>
</body>

very slow search results - mysqli - php

I'm just learning how to do this so please forgive my ignorance!
This page loads VERY slow and the search almost doesn't run on my iphone (sometimes timesout).
Here is my test site: http://webtestkit.com/1KaraokeDJ/index.php
$view=$db->query("select * from 1KaraokeDJ where
Title like '%$data%' ||
Artist like '%$data%' ||
Disc like '%$data%' ||
Brand like '%$data%'
limit 50");
is there a better way to do this search?
There are 28,000+ records now, but it will be in the 100k range later.
here is the full code:
<?php
include("connect.php");
session_start();
if(isset($_POST['submit']))
{
$search=$_POST['search'];
$_SESSION['title']= $search;
if(($_SESSION['title'])!="")
{ header("location:index.php"); }
else
{ echo "<script> alert('Please enter something to search for') </script>"; }
}
?>
<html>
<head>
<title>1KaraokeDJ.com</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="login">
<form method="post">
<p><img src="top.jpg" /></p>
<p>
<?php if(isset($_SESSION['title'])) { ?>
<input name="search" type="search" list="searchkey" value="<?php echo $_SESSION['title'];?>" class="search" />
<?php } else { ?>
<input name="search" type="search" list="searchkey" placeholder="Just type your text here and press enter - ex : Abba" class="search" />
<?php } ?>
</p>
<datalist id="searchkey">
<?php
$tile=$db->query("SELECT * FROM `1KaraokeDJ`");
while($storetitle=mysqli_fetch_object($tile))
{ ?>
<option value="<?php echo $storetitle->title ?>">
<?php } ?>
</datalist>
<p><input type="submit" name="submit" id="click" class="searchbutton" value="Karaoke Search" /></p>
<hr style="width:100%">
<?php if(isset($_SESSION['title'])) {
if(($_SESSION['title']!=""))
{
$data=$_SESSION['title'];
$view=$db->query("select * from 1KaraokeDJ where
Title like '%$data%' ||
Artist like '%$data%' ||
Disc like '%$data%' ||
Brand like '%$data%'
limit 50");
$check=mysqli_num_rows($view);
if($check!="")
{ while($descri=mysqli_fetch_object($view)) { ?>
<div class="reslt">
<h3 id="results">
<?php
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Artist);
echo " - ";
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Title);
?>
</h3>
<p class="Description">
<?php
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Brand);
echo " - ";
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Disc);
echo " - ";
echo $descri->Track;
?>
<p>
<hr>
</div>
<?php } ?>
<p><?php echo $check ?> Results</p>
<p class="highlight">Showing Up To 50 Results - Try Refining Your Search</p>
<?php } else { ?>
<div class="reslt">
<h3 id="results">Nothing Found!</h3>
<p class="Description">Try Changing Your Search Terms<p><hr>
</div>
<?php } } } ?>
</form>
</div>
</body>
</html>
Your answer is:
Place full-text indexes on your columns. Use match instead of like to actually use said indexes
an example of match
WHERE MATCH(field1 , field2) AGAINST ('aaa*' IN BOOLEAN MODE)
manual for match
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
<datalist id="searchkey">
<?php
$tile=$db->query("SELECT * FROM `1KaraokeDJ`");
while($storetitle=mysqli_fetch_object($tile))
{ ?>
<option value="<?php echo $storetitle->title ?>">
<?php } ?>
</datalist>
for whatever reason, saving a datalist to the client browser is very slow!

How do I get two databases to display on two radio buttons selection one for each button

I have two databases for local state and another one for country and i have two radio buttons for same as mentioned above.What should i do so that if i select local state it display only that database and if another it displays the other one.
This is just a testing code,will connect the database later.
enter code here
<html>
<?php include 'header.php';?>
<body>
<div class="radio-buttons">
<input type="radio" id="radio1" name="radios" value="all" >
<label for="radio1">Domestic</label>
<input type="radio" id="radio2" name="radios"value="false">
<label for="radio2">International</label>
</div>
<?php
$radio1 = "" ;
$radio2= "" ;
if($radio1=='checked'){
echo "correct";
}
else if($radio2=='checked'){
echo "awsome";
}
?>
You can use like below.
<?php
$radio = "" ;
if(isset($_GET["db"]))
{
$radio = $_GET["db"];
}
if($radio == 'domestic'){
echo 'domestic';
} else {
echo 'awsome';
}
?>
<html>
<head>
<script>
function autoSubmit()
{
var formObject = document.forms['dbForm'];
formObject.submit();
}
</script>
</head>
<body>
<form name='dbForm' id='dbForm'>
<input type="radio" name="db" <?php if ($radio == 'domestic') { ?>checked='checked' <?php } ?> value="domestic" onChange="autoSubmit();" />Domestic
<input type="radio" name="db" <?php if ($radio == 'international') { ?>checked='checked' <?php } ?> value="international" onChange="autoSubmit();" /> International
</form>
</body>
</html>

Task-list manager app in PHP doesn't show the list of tasks

I am working on a task list manager for my class that I am in. I have to include sessions and I need to push each task into an array and be able to delete it from the array.
I think I am doing it correctly,but when I run the program, the task list shows up as empty. I think I may not be adding the tasks to the task-list array correctly, and I really would like a fresh set of eyes to take a look, because maybe you will see what I haven't.
index.php
<?php
if (isset($_POST['tasklist'])) {
$task_list = $_POST['tasklist'];
} else {
$task_list = array();
}
// put the array in a session variable
$_SESSION['tasks']=$task_list;
$_SESSION['errors']=$errors;
//start the session to last one year
$lifetime = 60 * 60 * 24 * 365; // 1 year in seconds
ini_set('session.gc_maxlifetime', $lifetime);
//session_set_cookie_params($lifetime, '/');
session_start();
$errors = array();
switch( $_POST['action'] ) {
case 'add':
$new_task = $_POST['newtask'];
if (empty($new_task)) {
$_SESSION['errors'] = 'The new task cannot be empty.';
} else {
$_SESSION['tasks'] = $new_task;
}
break;
case 'delete':
$task_index = $_POST['taskid'];
unset($task_list[$task_index]);
$_SESSION['tasks'] = array_values($_SESSION['tasks']);
break;
}
include('task_list.php');
?>
task_list.php
<?php
session_start(); // Access the current session.
?>
</head>
<body>
<div id="page">
<div id="header">
<h1>Task List Manager</h1>
</div>
<div id="main">
<!-- part 1: the errors -->
<?php if (count($_SESSION['errors']) > 0) : ?>
<h2>Errors</h2>
<ul>
<?php foreach($_SESSION['errors'] as $error) : ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<!-- part 2: the tasks -->
<h2>Tasks</h2>
<?php if (count($_SESSION['tasks']) == 0) : ?>
<p>There are no tasks in the task list.</p>
<?php else: ?>
<ul>
<?php foreach($_SESSION['tasks'] as $id => $task) : ?>
<li><?php echo $id + 1 . '. ' . $task; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<br />
<!-- part 3: the add form -->
<h2>Add Task</h2>
<form action="." method="post" >
<?php foreach($_SESSION['tasks'] as $task) :
array_push($_SESSION['tasks'],$task);
endforeach; ?>
<!--<input type="hidden" name="action" value="add"/> -->
<label>Task:</label>
<input type="text" name="<?php $_SESSION['tasks'] ?>" id="newtask" value="<?php echo $task; ?>" /> <br />
<label> </label>
<input type="submit" value="Add Task"/>
</form>
<br />
<!-- part 4: the delete form -->
<?php if (count($_SESSION['tasks']) > 0) : ?>
<h2>Delete Task</h2>
<form action="." method="post" >
<?php foreach($_SESSION['tasks'] as $task) :
$_SESSION['tasks']=array_diff($_SESSION['tasks'],$task);
endforeach; ?>
<!--<input type="hidden" name="action" value="delete"/> -->
<label>Task:</label>
<select name="taskid">
<?php foreach($_SESSION['tasks'] as $id => $task) : ?>
<option value="<?php echo $id; ?>">
<?php echo $task; ?>
</option>
<?php endforeach; ?>
</select>
<br />
<label> </label>
<input type="submit" value="Delete Task"/>
</form>
<?php endif; ?>
</div><!-- end main -->
</div><!-- end page -->
</body>
</html>
You need to call session_start() before any interaction with the session. So if the files are accessed separately then you need it in both. If task_list.php is only included in index.php then just move it to the top of index.php. Additionally, in your logic for the add action you dont have your syntax right to add a task to $_SESSION['tasks'] array, instead you are overwriting it with whatever is in $new_task.
This is from Murach's PHP book. The book becomes bunk after like the 10th chapter. No valid explanations or examples and questions that assume you already know PHP because it doesnt teach you what you need to know.

Categories