Page has too many requests - php

having an issue with page chrome saying there are too many redirects, the page, finally does what i want(at least does function correctly as far as i know, as i tested it with a close connection, sticking at the top of page, and it is displaying the userID. When logged in this page does the redirecting, im not too sure how to fix this, found lots of different posts online, and each one was so different from the next.
<?php session_start();
include'../../connection.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href=".../../../../style.css">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include('../../main/main.php');?>
</head>
<body>
<div class=containermain>
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating" >
<option>
<option value="1">1 </option>
<option value="2">2</option>
<option value="3">3 </option>
<option value="4">4</option>
<option value="5">5</option>
</option>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
<?php echo "Hello " . $_SESSION['user']; ?>
<p> </p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
<!---------------------------------------COMMENT BOX---------------------------------------------------->
<div class="comments" align="center">
<form action="" method="post" >
<textarea rows="4" cols="50" name="comment">
Please type a comment if you are logged in....
</textarea>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])) {
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
if(mysqli_query($conn, $sqlinsert)){
header("Location: i5-6600k");
} else {
echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn);
}
}
// close connection
$sql = "SELECT `users`.`username`, `comment`.`comment`, `comment`.`timestamp`\n"
. "FROM `users`\n"
. "LEFT JOIN `comment` ON `users`.`userID` = `comment`.`userID` \n"
. "where dCpuID = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Username</th><th>Comment</th><th>Timestamp</th>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["username"]. "</td><td>" . $row["comment"]."</td><td>" . $row["timestamp"]. "</td>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</div>
<?php include('../../assets/footer.php');?>
<div class="fb-comments" data-href="http://www.computercomparison.tk/#home" data-numposts="5"></div>
</body>
</html>

I think I see what you are doing here, you are missing how to effectively process an action. You are triggering your comment by checking if something, which is persistent, exists and acting on it. If it's a session variable, it will persist, therefore the action is infinite until it stops persisting. You need an action in your submission.
I would have a config page that you include with all pages that contains re-usable variables. It would be stored in the root of the site. In general, you have some HTML errors and some unsafe SQL injection issues. I have created a little more complicated version of your page (without the bottom half, that needs a lot of work and should be wrapped as well) but it's only complicated to make the view less complicated...if that makes sense. Anyway, if you have issues let me know, I haven't tested this.
/config.php
<?php
# Create some absolute defines for consistent includes
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('VENDOR',ROOT_DIR.DS.'vendor');
define('SITE_URL','http://www.example.com');
# Start session
session_start();
# Autoloads all the classes we intend to use
spl_autoload_register(function($class){
$path = VENDOR.DS.trim(str_replace('\\',DS,$class),DS).'.php';
if(is_file($path))
require_once($path);
});
/vendor/App.php
<?php
# General/base class used for various time-saving actions
class App
{
# Store this object for re-use
protected static $singleton;
# Store others (if using getHelper() method)
protected static $apps;
# Create singleton
public function __construct()
{
if(!(self::$singleton instanceof \App))
self::$singleton = $this;
# Return back the same object
return self::$singleton;
}
# Get either the full post or just one key/value
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Get session or just one key/value pair
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Write and destroy session value
public function writeError($key)
{
$error = $this->getSession($key);
$this->destroy($key);
return $error;
}
public function destroy($key = false)
{
if(!empty($key)) {
if(isset($_SESSION[$key]))
$_SESSION[$key] = NULL;
return;
}
session_destroy();
}
# Sets a session value
public function setSession($key,$value)
{
$_SESSION[$key] = $value;
}
# Consistent way to write the site url (set in the config)
public function siteUrl($path = false,$ssl=false)
{
return ($ssl)? str_replace('http://','https://',SITE_URL).$path : SITE_URL.$path;
}
# Creates an instance if this object
public static function call()
{
return new \App();
}
# Saves and uses classes
public function getHelper($class,$inject=NULL)
{
$setKey = str_replace('\\','',$class);
if(isset(self::$apps[$setKey]))
return self::$apps[$setKey];
self::$apps[$setKey] = new $class($inject);
return self::$apps[$setKey];
}
}
/vendor/Router/Model.php
<?php
# Use for redirects, can be expanded out to do other router-type things
namespace Router;
class Model extends \App
{
public function addRedirect($path)
{
header('Location: '.$path);
exit;
}
}
/vendor/View/Model.php
<?php
# This is a wrapper for the page
namespace View;
class Model extends \App
{
public function render($path)
{
if(!is_file($path))
return;
# Create a buffer and render contents
ob_start();
include($path);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
/vendor/Commenter/Model.php
<?php
namespace Commenter;
class Observer extends \Router\Model
{
# Listen for action name, do action when required
public function listen($conn)
{
if($this->getPost('action') != 'addcomment')
return false;
if(!empty($this->getSession('login_id'))) {
$id = $this->getSession('login_id');
# You will want to bind parameters on this. This is an opening for SQL Injection (Google it)
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '".$this->getPost('comment')."', '1')";
if(mysqli_query($conn, $sqlinsert))
$this->addRedirect("i5-6600k");
else
$this->setSession('error',"ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn));
}
}
}
whatever this page is called...
<?php
# Create separator
$DS = DIRECTORY_SEPARATOR;
# Include config file
include(realpath(__DIR__.$DS.'..'.$DS.'..').$DS.'config.php');
# Check to see if this file is being wrapped by render class
if(!isset($this)) {
# Include this file into the renderer
echo \App::call()->getHelper('\View\Model')->render(__FILE__);
exit;
}
# Include connection
include(ROOT_DIR.DS.'connection.php');
# Listen for the add comment action
$this->getHelper('\Commenter\Observer')->listen($conn);
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href="<?php echo $this->siteUrl('/style.css') ?>">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include(ROOT_DIR.DS.'main'.DS.'main.php');?>
</head>
<body>
<div class="containermain" style="padding-bottom: 60px;">
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating">
<?php for($i=1; $i<=5;$i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php } ?>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
Hello <?php echo $this->getSession('user') ?>
</div>
<div class="fb-like" data-share="true" data-width="450" data-show-faces="true"></div>
<!--- COMMENT BOX --->
<div class="comments" align="center">
<?php echo $this->writeError('error') ?>
<form action="" method="post" >
<!-- YOU NEED TO SEND AN ACTION WORD HERE AND CHECK FOR IT
TO PROCESS POST -->
<input type="hidden" name="action" value="addcomment" />
<textarea rows="4" cols="50" name="comment">Please type a comment if you are logged in...</textarea>
<input type="submit" value="Submit">
</form>
...etc.

Related

PHP session_id() being overridden

I really don't know how to describes this, but here goes. I'm trying to make a Login for an online multiplayer game (cluedo to be exact) that is written using mainly the LAMP stack (php,js,etc), and creating a session when someone logs in/registers works for me and all and I even save it to a sql database, but it seems that as soon as a next user Logs in/registers the session id to the previous user is overridden to the new ones details. In other words they both now have the same session for some reason.
My Game LogIn basically:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<meta charset="UTF-8">
<title>Game Setup</title>
</head>
<body>
<header>
<h1>Game Setup</h1>
</header>
//My form for user details and character select
<form name="Registration" id=Form1 action="Lobby.php" method="POST">
<fieldset>
<legend>Player information:</legend>
<label for="Pid">Player Name(required): </label><br>
<input autofocus type="text" id="Pid" name="Pid" placeholder="Player ID" required><br>
<label for="Avatar">Character(required):</label><br>
<select name="Avatar">
<option value="Miss White">Miss White</option>
<option value="Col Mustard">Col Mustard</option>
<option value="Miss Scarlet">Miss Scarlet</option>
<option value="Mr Green">Mr Green</option>
<option value="Madame Plum">Madame Plum</option>
<option value="Benjamin Blue">Benjamin Blue</option>
</select><br><br>
<input type="submit" value="Register">
</fieldset>
</form>
</body>
and the lobby (where I wait for someone to press game start or for more people to register)
<?php
session_start() ;
session_regenerate_id();
$_SESSION["UserName"]=$_POST['Pid'];
$_SESSION["Avatar"]=$_POST['Avatar'];
?>
<?php require 'DatabaseConnect.php' ?>
<?php include 'Users.php' ?>
<?php
$PlayerID = mysqli_real_escape_string($conn, $_POST['Pid']);
$PlayerChar = mysqli_real_escape_string($conn, $_POST['Avatar']);
$SesID = session_id();
$sql = "INSERT INTO users (UserName, Avatar, sessionID)
VALUES ('$PlayerID', '$PlayerChar','$SesID')";
if ($conn->query($sql) === TRUE) {
echo "Welcome $PlayerID , currently in Lobby: <br>";
$User = new Users();
$User->setUserName($_SESSION['UserName']);
$User->setAvatar( $_SESSION['Avatar']);
$User->isPlaying = false;
$_SESSION['User'] = serialize($User);
?>
<html>
<body>
<div id="Players"> </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src ="Display.js"></script>
</body>
</html>
<?php
}
else {
if($conn->errno == 1062){//when a userName or Character already in use
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
$sql = "ALTER TABLE users AUTO_INCREMENT = ".$result->num_rows;
$conn->query($sql);
echo "<script type='text/javascript'>alert('ERROR :Username or Character already in use!')</script>";
echo" <script>
window.location = 'LogIn.php';
</script>";
}
}
?>
and then the Display.js runs in a loop until either 6 people connect or a user presses start. It also displays everyone currently waiting for a game by outputting the SQL database, but I don't think that code is necessary to add, but then when that's done I go to the Cluedo.php page and if I echo session_id() there on two different browsers(same machine) I get the same session_id()
<?php
session_start() ;
?>
<?php require 'DatabaseConnect.php' ?>
<?php include 'Users.php' ?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<meta charset="UTF-8">
<title>Cluedo</title>
</head>
<body>
<?php
$User = unserialize($_SESSION['User']);
echo session_id();
?>
</body>
</html>
Also I'm using XAMPP and running it all locally at the moment so don't know if there's a problem there maybe?
Here's an example of my database with the saved values, the table saves unique sessions however when the session_id() is echoed at the Cluedo.php page it is always the last registered user:
UserTable

Weird failure in PHP if statement

OK, so here's my code. (I'll sanitize it later. Don't worry about it.)
gallery_upload_new.php
// Check if user wants to upload to existing or new album
if (isset($_POST['album'])) {
if ($_POST['album'] == '') {
$_POST['album'] = $_POST['new_album'];
}
}
// Populate album dropdown menu
$albums = $database->query("SELECT DISTINCT(album) FROM images")->fetchAll(PDO::FETCH_COLUMN);
// Load the 'upload new photo' interface if user's not uploading it already
if (!isset($_FILES['image_link']) || !isset($_POST['caption']) || $_POST['caption'] == '') {
//var_dump($_FILES);
//var_dump($_POST);
include('views/gallery_upload_new.php');
// Otherwise store the image file, register it into database, and put the user back in the list of photos
} else {
$new_image = new Image($_POST['caption'], $_POST['album']);
$new_image->register($_FILES['image_link']['tmp_name'], $_FILES['image_link']['name']);
header('location: gallery_management.php');
}
?>
views/gallery_upload_new.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $site_title; ?></title>
<?php include('views/header.php'); //Just the global CSS and JavaScript ?>
</head>
<body>
<?php include('views/nav_menu.php'); //Site navigation panel ?>
<div id="content">
<h1>Upload new photo</h1>
<form enctype="multipart/form-data" action="gallery_upload_new.php" method="post">
<p>
<strong>Upload to album: </strong>
<select name="album">
<?php
foreach($albums as $album_name) {
echo "<option value='$album_name'>$album_name</option>";
}
?>
<option id="selectNewAlbum" value="" selected>New album</option> <input type="text" placeholder="New album name" name="new_album" id="newAlbumName">
</select>
</p>
<p><strong>Photo caption</strong> <input type="text" name="caption"></p>
<p><strong>Photo file: </strong><input type="file" required name="image_link"></p>
<input type="submit" value="Unggah">
</form>
</div>
</body>
</html>
Here's the weird part: without those two var_dump's up there, the else block won't execute. I've made sure the indexes in the $_POST and $_FILES are correct. Yet without those dummy dumps, this thing won't work. It'd just load the views/gallery_upload_new.php no matter what.
It doesn't even matter if they're commented out or not. They just need to be there.
What did I do wrong? Did I made a syntax error somewhere?

return data from php dropdownlist after submit

hey guys i've passed way more time on this then what i originally wanted to...
so i have this code here, where i have a drop list give me data from a sql database from the selection of 3 radio buttons, that all works fine.
My problem come when i want to submit my form and get info of the data in said droplist. all i want is put the selected radio and the selected item in the single drop list in variables in the submission.php that comes after the post method of the form...
anyway thats what i want to do for now
<?php
require "../Scripts/config.php"; // database connection here
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>test</title>
<SCRIPT language=JavaScript>
function reload()
{
for(var i=0; i < document.form1.type.length; i++){
if(document.form1.type[i].checked)
var val=document.form1.type[i].value
}
self.location='bob.php?type=' + val ;
}
</script>
</head>
<body>
<?Php
$tp=$_GET['type']; // getting the value from query string
if(strlen($tp) > 1){$sql="SELECT * FROM Subcategory where cat_id='$tp'";}
echo $sql;
echo "<form name=form1 id=form1 method=post action=submissions2.php>";
echo "<select name=Subcategory id=Subcategory value=''>Subcategory</option>"; // printing the list box select command
foreach ($dbo->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[cat_id]>$row[Subcategory]</option>";
/* Option values are added by looping through the array */
} echo "</select>";// Closing of list box
echo "<br>";
echo "<br>";
echo "<br>";
echo "
<b>Type</b>
<input type=radio name=type value='1_Cosplay' onclick=\"reload()\";>Cosplay
<input type=radio name=type value='1_Modeling' onclick=\"reload()\";>Modeling
<input type=radio name=type value='1_Zombie' onclick=\"reload()\";>Zombie
<input type=submit value=Submit> </form>";
echo "<br>";
echo "<br>";
echo "<br>";
?>
</body>
</html>
and this is the submissions2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../Scripts/jquery-1.8.0.min.js"></script>
</head>
<body>
<?php
function filter($data) {
/*$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);*/
return $data;
return $row;
}
foreach($_POST as $key => $value) {
$mydata[$key] = filter($value);
}
echo $mydata['Subcategory'];
echo "<br>";
?>
</body>
</html>
all i seem to be able to get is the radio button choice.
Here is an all-in-one solution. You need to change some references like what the name/local path of the file path is, but anyway, this contains all the code. I can not test the DB stuff but the ajax works if you have the correct url path in the jQuery portion. Note, this solution references itself, not a new page:
// Display errors for troubleshooting
ini_set('display_errors','1');
error_reporting(E_ALL);
class CategorySelector
{
public function LoadSubCat()
{
// You will be subjected to an injection hack if you don't filter or encode this variable
// You should do PDO with prepared statements
$parent_cat = htmlspecialchars($_GET['parent_cat'], ENT_QUOTES);
$query = $this->Fetch("SELECT id,subcategory_name FROM subcategories WHERE categoryID = '$parent_cat'");
// Uncomment this to see how this returns
// $this->PrintPre($query); ?>
<label for="sub_cat">Sub Category</label>
<select name="sub_cat" id="sub_cat">
<?php
if($query !== 0) {
foreach($query as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subcategory_name']; ?></option>
<?php
}
} ?>
</select>
<?php
}
public function Form()
{
// Get rows for categories
$results = $this->Fetch("SELECT id,category_name FROM categories");
// Uncomment this to see how this returns
// $this->PrintPre($results); ?>
<form name="form1" id="form1" method="post">
<label for="parent_cat">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php
if($results !== 0) {
foreach($results as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php }
} ?>
</select>
<!-- This is a container that will load in your next menu -->
<div id="sub_cat_container"></div>
<input type="submit" name="submit" value="submit" />
</form>
<?php
}
public $rowCount;
// This is strictly a returning engine for SQL statements
protected function Fetch($_sql)
{
include_once('config.php');
// You really should do prepared statements (PDO)
// This way of calling sql is depricated
$query = mysql_query($_sql);
// Save the row count
$this->rowCount = mysql_num_rows($query);
// If there are rows return them
if($this->rowCount > 0) {
$_array = array();
// Loop through
while($result = mysql_fetch_array($query)) {
$_array[] = $result;
}
}
// Send back your query results for processing
// If no results, return false/0
return (isset($_array))? $_array:0;
}
protected function PrintPre($_array)
{ ?>
<pre>
<?php print_r($_array); ?>
</pre>
<?php
}
}
// Uncomment this for testing that the AJAX is working.
// print_r($_REQUEST);
// This is probably not the best way to do this all, but for sake
// of trying to get it all to work, this whole thing will ajax to
// itself, but if you can get it to work on this one page, you
// can split it up into two pages.
// Ok, so this creates a new instance of this whole system
$builder = new CategorySelector();
// If this page receives a GET request for $_GET['parent_cat'], just process it.
// That action is to call the sub_cat dropdown menu from this object
if(isset($_REQUEST['parent_cat']) && !empty($_REQUEST['parent_cat'])) {
$builder->LoadSubCat();
}
// If there is no request, display the html page
else {
// You should not have space before the <!doctype>. Some browsers act funky if there is space before
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
// I'm not a javascript person, so this portion is kind of sloppy
$(document).ready(function(){
$('#parent_cat').change(function() {
// Get value
var ElmVal = $('#parent_cat').val();
$.ajax({
// You need to reference this page in the "thispage.php" whatever this page is called
url:"/thispage.php?parent_cat="+ElmVal,
success:function(result) {
$("#sub_cat_container").html(result);
}});
});
});
</script>
</head>
<body>
<?php
// Display the form.
$builder->Form(); ?>
</body>
</html>
<?php } ?>
Quote all your HTML attributes like name='Subcategory', and
echo "<option value=$row[cat_id]>$row[Subcategory]</option>"
should be
echo "<option value='{$row['cat_id']}'>{$row['Subcategory']}</option>";
Your coding practice is horrible, by the way. You are not testing to see how many rows you have in your MySQL query, and you don't need to echo on each line. You can do this:
echo '<br />'.
'<br />';
Of course, using line breaks like that is a bad practice, as well. Use CSS.

How to pass data from mysql database to $_SESSOIN

Hello Everyone I am new in PHP and I am trying to create a very small application in php
I am trying to access the userid of a user using session in php for this I am following these steps
I create these classes in my application
My first class is Database Manager which I place in model folder
public function executeQuery($query) {
$result = mysql_query($query);
if ($result === false) {
$this->closeConnection($this->conn);
exit;
}
// extract data from results, returning an associative array
$rows = Array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
and then I create these two classes
First is loginManager
class LoginManager
{
function checkLogin($arr)
{
require_once(FRONT_ROOT_PATH.'DatabaseManager.php');
$query ="Select * from tbusers where username='".$arr['username']."' and password='".$arr['password']."'";
$db= new DatabaseManager();
$result=$db->executeQuery($query);
return $result;
}
}
and second is LoginInit
<?php
session_start();
include(LIB_PATH."Login/LoginManager.php");
if(isset($_POST['addlogin']))
{
$obj= new LoginManager();
$userlist=$obj->checkLogin($_POST);
if(Count($userlist)>0)
{
$_SESSION['uid']=$userlist['userid'];
header('location:/ProjectDream/view/home/home.php');
}
else
{
echo "Login Failed";
}
}
}
In this class I add the session and after that I call these classes on this php page
<?php
include('Include/config.inc.php');
include(LIB_PATH."Login/Logininit.php");
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login</title>
<!-- CSS -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<!-- Main HTML -->
<body>
<!-- Begin Page Content -->
<div id="container">
<form action="" method="post">
<input type="hidden" name="addlogin"/>
<label for="name">Username:</label>
<input type="name" name="username">
<label for="username">Password:</label>
<p>Forgot your password?
<input type="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div>
</form>
</div>
<!-- End Page Content -->
</body>
</html>
and when user login I send user to home.php page I write this code on home.php
<?php
session_start();
if(isset($_SESSION['uid']))
{
echo $_SESSION['uid'];
}
else
{
echo "No Session ";
}
?>
Now when I run this application then it show me no value in my $_SESSION variable
Is it possible to call session on class level in php. Please tell me how can I use session here
Thanks
try it like this it should work:
$_SESSION['uid']=$userlist[0]['userid'];
In your code:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
You are adding $row to $rows so you're having $rows[0]=$row; then $rows[1]=$row;
so actually $rows['userid'] isn't set, it is $rows[0]['userid'] that is set
the varible to which the value is assigned should be in left side of equation.
so
change
$userlist['userid']=$_SESSION['uid'];
to
$_SESSION['uid']=$userlist['userid'];
You must assign some value to $_SESSION['uid'] when reading values from database. Something like:
$_SESSION['uid'] = $row['uid'];
Also note that when you want to use data from $_SESSION variable you must call session_start().

PHP: Array appears to reinitialize

I'm trying to make a basic html form that passes information to a php object then adds said object to an array. It works to the point of passing the information from the form, to the object, and adding it to the array and displaying said object. However, when I try to add a second object to the array it only seems to replace the array with a new single element array rather then adding to it. Here is my code... any ideas?
index.php file:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
include_once 'clientInfo.php';
include_once 'clientList.php';
if ($_POST) {
$clientArray[] = new clientInfo($_POST["Fname"], $_POST["Lname"]);
}
if (!empty($clientArray)) {
$clientList = new clientList($clientArray);
}
?>
<p>go to client list</p>
</body>
</html>
clintInfo.php file:
<?php
class clientInfo {
private$Fname;
private$Lname;
public function clientInfo($F, $L) {
$this->Fname = $F;
$this->Lname = $L;
}
public function __toString() {
return $this->Fname . " " . $this->Lname;
}
}
?>
clientList.php file:
<?php
class clientList {
public function clientList($array) {
foreach($array as $c) {
echo $c;
}
}
}
?>
EDITED WORKING CODE WITH ANSWER
index.php file:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
if ($_POST) {
$testClient = new clientInfo($_POST["Fname"], $_POST["Lname"]);
echo $testClient . " was successfully made. <br/>";
$_SESSION['clients'][] = $testClient;
echo end($_SESSION['clients']) . " was added.";
}
?>
<p>go to client list</p>
</body>
</html>
clientList.php file:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>
Accessing session variables
</title>
</head>
<body>
<h1>
Content Page
</h1>
<?php
for ($i = 0; $i < sizeof($_SESSION['clients']); $i++) {
echo $_SESSION['clients'][$i] . " was added. <br/>";
}
?>
<p>return to add data</p>
</body>
</html>
The object file clientInfo.php stayed the same. The objects needed to be stored in a multidimensional $_SESSION array and recalled with a for loop, a foreach loop would not work, unless some one else knows a way to make a foreach loop work, stick to a for. On a side note the $testClient variable could be skipped and just created and placed with in the $_SESSION at the same time, however doing it with the temp variable made it easier to trouble shoot and see how to make it work. Just thought I'd post the working code with the answer supplied by Josh!
You need to add persistance to your array object.
See PHP's $_SESSION.
If you don't store it to memory or disk in between requests, it cannot possibly exist on successive loads. There is a nice tutorial in that link that should get you up and running.
Alternatively, you can store things in a database, for larger needs.

Categories