Unable to get session in different PHP page - php

Unable to get session from different PHP page other than where i initialized it
This is my first PHP page where i initialize the session.
<?php
$i =1;
$team = htmlentities($_POST['team']);
$id = htmlentities($_POST['id1']);
$mobile = htmlentities($_POST['mobile1']);
if(isset($_POST['id2']))
{
$ids = htmlentities($_POST['id2']);
$mobiles = htmlentities($_POST['mobile2']);
$i=2;
}
if(isset($_POST['id3'])){
$ids = $ids.','.htmlentities($_POST['id3']);
$mobiles = $mobiles.','.htmlentities($_POST['mobile3']);
$i=3;}
echo $team;
echo $i;
$connect =new mysqli('localhost', 'root', 'password','test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
$data = "INSERT INTO `Users`(`team_name`, `id`, `mobile`, `ids`, `mobiles`) VALUES ('$team','$id','$mobile','$ids','$mobiles')" ;
$createData="CREATE TABLE `$id`(
`id` INT NOT NULL ,
`ansOpChoosen` INT NOT NULL,
`realAns` INT NOT NULL
);";
echo 'pass';
$link ="/test.html";
$link2 = "/signups.html";
if(mysqli_query($connect,$data) && mysqli_query($connect,$createData) )
{
session_start();
$_SESSION['user'] = $id;
header('Location: '.$link);
echo "new record created successfully";
}
else{
header('Location: '.$link2);
echo "error";
}
$connect->close();
?>
This is another php page where i try to retrive data but it doesnt fetch any thing
<?php
$id = $_SESSION['user'];
$quesNo = $_POST['questionNo'];
$optionCho = $_POST['optionchoosen'];
$optionReal =$_POST['optionreal'];
echo $id;
//echo "hbbhkhb";
$connect =new mysqli('localhost','root','password`','test');
if($connect->error){
echo "connection error";
}
$check ="SELECT * FROM `$id` WHERE `id`=$quesNo";
if($res=mysqli_query($connect,$check)){
$count = mysqli_num_rows($res);
if($count>0)
{
$data ="UPDATE `$id` SET `ansOpChoosen`=$optionCho,`realAns`=$optionReal WHERE `id`=$quesNo";
}
else{
$data = "INSERT INTO `$id`(`id`,`ansOpChoosen`,`realAns`) VALUES ($quesNo,$optionCho,$optionReal)";
}
$store=mysqli_query($connect,$data);
}
?>

Put session_start(); at the top of every page that you want to use sessions on.

You always have to call session_start() before doing something with the session.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
Source: http://php.net/manual/en/function.session-start.php

A session is started with the session_start() function.
Be careful : it must be top of every page.
For example :
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Manual : http://php.net/manual/en/session.examples.basic.php

Related

direct user to another page using php

what is the best way to direct the user to another page given the IF statement is true. i want the page to direct the user to another page using PHP, when the IF statement is run, i tired this but it doesn't work??
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
Below is the full source code for the page.
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p><span>Room No: </span><?php $room = $_SESSION['g'];
echo $room; // echo's room ?>
</p>
<p><span>Computer No: </span><?php
$select3 = $_POST['bike'];
echo $select3;
?>
</p>
<p><span>Date: </span><?php $date = $_POST['datepicker'];
echo $date; // echo's date
?>
</p>
<p><span>Start Session: </span>
<?php
if(isset($_POST['select1'])) {
$select1 = $_POST['select1'];
echo $select1;
echo "";
}
else{
echo "not set";
}
?>
</p>
<p><span>End Session: </span>
<?php
if(isset($_POST['select2'])) {
$select2 = $_POST['select2'];
echo $select2;
echo "";
}
else{
echo "not set";
}
?>
</p>
</div>
<div id="success">
<?php
$servername = "localhost";
$name = "root";
$password = "root";
$dbname = "my computer";
// Create connection
$conn = mysqli_connect($servername, $name, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `booked` WHERE
`date` = '{$date}' AND
`computer_id` = '{$select3}' AND
`start_time` = '{$select1}' AND
`end_time` = '{$select2}' AND
`room` = '{$room}'
";
$result = mysqli_query($conn, $query);
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
else
{
$sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
</div>
<form action="user.php">
<input type="submit" value="book another" class="bookanother" />
</form>
</div>
</body>
</html>
If the header is sent already, for example you have echo something before then the header will not work, because the header cannot be set after data flow has started, (since php would have already set the default headers for you). So, in this case if that is so, I do the redirect using javascript.
PHP Docs:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
WORK-AROUND: This is a function I have written long back and include in controllers.
/**
* Safely redirect by first trying header method but if headers were
* already sent then use a <script> javascript method to redirect
*
* #param string
* #return null
*/
public function safeRedirect($new_url) {
if (!headers_sent()) {
header("Location: $new_url");
} else {
echo "<script>window.location.href = '$new_url';</script>";
}
exit();
}
add the function and simply call:
safeRedirect('index.php');

Unable to get session variable to save into my database

Can anyone help me in getting the group_id from a session and save into the database, it seems not to working, been working on it for a while now. The error i am getting is Notice: Undefined index: group_name
This is my script
include('db.php')
//Get User Info
if(isset($_SESSION['username'])){
$LoggedUser = $_SESSION['username'];
if($GetUser = $mysqli->query("SELECT * FROM users WHERE username='$LoggedUser'")){
$UserInfo = mysqli_fetch_array($GetUser);
$LoggedUsername = strtolower($UserInfo['username']);
$LoggedUserLink = preg_replace("![^a-z0-9]+!i", "-", $LoggedUsername);
$LoggedUserLink = strtolower($LoggedUserLink);
$UserId = $UserInfo['user_id'];
$GetUser->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
}
//Get Group info
if(isset($_SESSION['group_name'])){
$LoggedGroup = $_SESSION['group_name'];
if($GetGroup = $mysqli->query("SELECT * FROM groups WHERE group_name='$LoggedGroup'")){
$GroupInfo = mysqli_fetch_array($GetGroup);
$LoggedGroupname = strtolower($GroupInfo['group_name']);
$LoggedGroupLink = preg_replace("![^a-z0-9]+!i", "-", $LoggedGroupname);
$LoggedGroupLink = strtolower($LoggedGroupLink);
$GroupId = $GroupInfo['group_id'];
$GetGroup->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
}
//getting variables and inserting into a database
if($_POST)
{
$User = $UserId;
$Group = $GroupId;
$mysqli->query("INSERT INTO tb_name(group_id_fk, user_id_fk) VALUES ('$Group', '$User')");
die('<div class="alert alert-success" role="alert">You have been added successfully to the group.</div>');
}else{
die (mysqli_error());
}
?>
Thanks
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
<?php
// Start the session
session_start();
// Set session variables
if(isset($_SESSION['username'])) {
---- Your Statements -----
}
?>
you need to start a session first by session_start(); before using $_SESSION global

how can i display sql query in php? CLOSED

<?php
include 'config.php'; //connect to db
if(isset($_REQUEST["pwd"]) && isset($_REQUEST["name"])) {
$password = $_REQUEST['pwd']; //pass from previous page
$name = $_REQUEST['name']; //pass from previous page
$checkUserPass = mysql_query("SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //check if the user exist
if(mysql_num_rows($checkUserPass) == 1) {
$personnelId = mysql_query("SELECT PersonnelID FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //query user id
while($row = mysql_fetch_assoc($personnelId)) {
echo $row['PersonnelD']; // print user id
}
mysql_close($conn);
//echo "<br/><br/>";
//echo "<script>alert('Logged In.')</script>";
//header("Refresh: 1; url=profile/profile.php?id="'.$id.');
//header('Refresh: 1; url=test.php?id=$personnelId');
} else {
echo "<br/><br/>";
echo "<script>alert('Wrong Password.')</script>";
header('Refresh: 1; url=personnelselect.php');
}
}
?>
i cannot echo the $row['PersonnelD'] the page shows blank. i cannot understand where did i go wrong. this page quesion have been solved
Looks like you have mistake in code:
echo $row['PersonnelD'];
shouldn't it be following?
echo $row['PersonnelID'];
check the mysql_fetch_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using var_dump() function. Ex: var_dump($row); in while loop.
In both your querys, you have
"SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'"
It should be:
"SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';"
PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.

headers not working PHP

Page 1 abc.html.. on submit it will jump to this PHP page .
This is page PHP1.php here i am trying to validate user input if name and id in in data he will be forwarded to fill out second part of registration if not it will just give error.
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = mysql_connect("localhost", "user", "password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("mydbName");
if(isset($_POST['team_name'],$_POST['id'])){
$team_name = mysql_real_escape_string($_POST['team_name']);
$id = mysql_real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result= mysql_query("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$team_result = mysql_fetch_row($result);
if ($team_result[0] == '0') { //if does not exist print failed.
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}} } ?>
RegisterPART2.php is where i am checking my session exist or not (the one i started in last file). if not i want to redirect back to form one and fill that first then come to registration part 2
`<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page1.html'); //take back to stage 1 coz user did not fill first part.
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
If you're using the new MySQL version (MySQLi), so the first page will become:
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = new mysqli("localhost", "user", "password", "mydbName");
if (!$con) {
die('Could not connect: ' . $con->error());
};
if (isset($_POST['team_name'],$_POST['id'])) {
$team_name = $con->real_escape_string($_POST['team_name']);
$id = $con->real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result = $con->prepare("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$result->execute();
$result->bind_result($one,$two,$three,$etc);
$result->fetch();
if (empty($one) and empty($two) and empty($three) and empty(etc)) { // may be and/or (pick one)
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}
}
}
?>
You may use the following alternative to header.
prinf('<script>window.location = "URL HERE"</script>');
It should do the same thing as header does.

Retrieving information from database

I am trying to check if the session username matches the record in my database and if it does, I want to include a file.
This is my code
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT * FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez)
{
include('check.php');
}
else
{
echo "error";
}
?>
The session username does not match the record in my database, yet the file is being included. Why?
OH, I FOUND THE ISSUE. IT IS CONSIDERING MY USERNAME TO BE ROOT...BUT WHEN I SAY ECHO $_SESSION['USERNAME'] IT IS CRAIG#CRAIG.COM..WHY SO>
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT sessionusername FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez["sessionusername"]==$username)
{
include('check.php');
}
else
{
echo "error";
}
?>
You are simply testing whether the array $geez is empty or not. If the array has anything in it, you if($geez) will return true. To stop this behaviour, please see ceteras' answer, particularly this part:
if($geez["sessionusername"]==$username)
{
include('check.php');
}
I believe that's the only part that has changed.
Thanks,
James

Categories