Clarification on session_start() when using AJAX - php

I recently got the following error in my logs:
session_start(): Cannot send session cache limiter - headers already sent
I am new to using sessions so I am not surprised. I use the following code in my header.php file:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['usr_id'])) {
header("Location: login.php");
}
?>
I mostly use AJAX to interact with some files that handle database-related functions. Do I need to add the session_start() on my backend php files too? I am currently doing this:
<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
include_once 'database.php';
session_start();
if(!isset($_SESSION['usr_id'])) {
header("Location: login.php");
}
$uid = $_SESSION['usr_id'];
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if( !$errors ) {
// insert your query
$mysqli->query("
INSERT INTO `contributions`(`uid`, `contributionname`, `contributiontype`, `contributionamount`, `employee`)
values ('".$uid."', '".$inputvalues['contributionname']."', '".$inputvalues['contributiontype']."', '".$inputvalues['contributionamount']."', '".$inputvalues['employee']."');
");
// select your query
$addresult = "Success";
$returnResult = $addresult;
}
// close connection
mysqli_close($mysqli);
// print result for ajax request
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
Is this what is causing my error?

Related

After Login, My index.php redirects to Login.php

i have used this code for years and never experienced this, using a new hosting service prior to the ones i have always used and am getting this issue.
session_start();
$rec_page = $_SERVER['REQUEST_URI'];
$cPage = $_SERVER['PHP_SELF'];
if(!isset($_SESSION['isadmin'])){
header('location: login.php?l=i');
}
include('includes/constants.php');
include('includes/functions.php');
$admin_login = $_SESSION['login'];
$admin_psw = GetAdminInfo($admin_login,'1');
if(isset($_REQUEST['cmd'])){
if($_REQUEST['cmd']=="logout"){
session_destroy();
header('location: login.php');
}
}
this is the section of the code with the issues, once i login i get redirected to the login.php if i delete this
`if(!isset($_SESSION['isadmin'])){
header('location: login.php?l=i');
}`
i can login successfully but if i click on another page i will have to login again, so im guessing its a Session problem.
here is the action php for the login.php
<?php
include('../includes/constants.php');
include('../includes/functions.php');
if(isset($_POST['xin'])){
$ikey = addslashes($_POST['textKey']);
$nkey = addslashes($_POST['textname']);
$mysqli = mysqli_connect($dbserver,$dbuser,$dbpass) or die('Cannot connect to db');
mysqli_select_db($mysqli, $db_db) or die('Cannot select db');
$result=mysqli_query($mysqli, "SELECT * FROM admins WHERE login = '".$ikey."' && adminname = '".$nkey."'");
$cnt = mysqli_num_rows($result);
if($cnt > 0){
while($rw=mysqli_fetch_array($result)){
session_start();
$_SESSION['isadmin']=true;
$_SESSION['login'] = $ikey;
$_SESSION['adminname'] = $nkey;
header('location: ../index.php?cm='.$_SESSION['isadmin']);
}
}else{
header('location: ../login.php?err=1'.mysqli_error($mysqli));
}
mysqli_close($mysqli);
}
?>
use javascript instead of header. No long story
echo "<script>parent.self.location='index.php';</script>";

PHP Sessions Disappearing

I come from a classic ASP programming background and boy PHP is really frustrating. What's the deal with PHP Sessions? In Classic ASP you Simply put:
<% Session("Name") = "XYZ" %>
And that Session is always available unless you kill it or it times out. With PHP I get a Session to work from one page to another but when I refresh the page I lose my session. Here is the code I have:
Page: modules.php
// Start the session
session_start();
Page: index.php
include 'modules/modules.php';
$_SESSION['username'] = "MyName";
if (isset($_SESSION['username']) && !empty($_SESSION['username']) {
header('Location: main.php');
}
Page: main.php
include 'modules/modules.php';
echo "My username: ".$_SESSION['username'];
exit();
Now because I gave Session Username a default value it will redirect to main.php and it shows the username fine. But if I refresh the page it disappears. I ran this to see if there was any errors in the modules.php page right below the start session:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
None were returned. But I can't figure out why my PHP Sessions just disappear. I am trying to create a login page where the user will login and his/hers info will be carried along each page so I can have there ID info and to make sure they are logged in. So could someone please tell me what I am doing wrong?
My Modules Page:
// Start the session
session_start();
/* Database Connection Settings */
$_SESSION['servername'] = "localhost";
$_SESSION['mysql_username'] = "xxxxxxx";
$_SESSION['mysql_password'] = "xxxxxxx";
$_SESSION['dbname'] = "mydb";
//Turn on Error Report. True = On / False = Off
ErrorReporting(true);
//Display Error.
function ErrorReporting($ErrOn){
if ($ErrOn == true) {
//Show Error
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
}
}
function db_conn($servername, $mysql_username, $mysql_password, $dbname) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
}
/**************************************
Close Database Connection Function.
***************************************/
function db_disconn() {
$conn = null;
}
/***************************************
Employee Login Check:
****************************************/
function CheckLogin($strUserName, $strPassword) {
if (isset($strUserName) && !empty($strUserName) && isset($strPassword) && !empty($strPassword)) {
$conn = new mysqli($_SESSION['servername'], $_SESSION['mysql_username'], $_SESSION['mysql_password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname, user_name, password FROM tbl_employees WHERE user_name='$strUserName' AND password='$strPassword' AND account_disabled='';";
$result = $conn->query($sql);
//Check and see if there are records avaiable.
if ($result->num_rows > 0) {
// output data of each row with a loop.
while($row = $result->fetch_assoc()) {
//Store the info into a session variable.
$_SESSION['eid'] = $row["id"];
$_SESSION['firstname'] = $row["firstname"];
$_SESSION['lastname'] = $row["lastname"];
return $_SESSION["eid"];
//break; //Stop the loop process.
}
} else {
//No records found prompt the user.
return "User name or Password was Incorrect! Please try again!";
}
db_disconn(); /*Close db*/
}
}
You're calling $_SESSION as if it were a function - $_SESSION("username") - while it's actually an array.
You should use $_SESSION["username"] to get the variable value.
You should be getting a Fatal error: Can't use function return value in write context ... but you probably did something wrong with turning on error reporting and you're not getting any errors.
The correct working code would look like this:
<?php
session_start();
if (isset($_SESSION["username"]) && !empty($_SESSION["username"])) {
echo "My username: ".$_SESSION["username"];
} else {
echo "Not set";
$_SESSION["username"] = "MyName";
}

php session is not working in server

I want after register the page should continue with session. for that i have create following code.
if($_POST['action']=='finder_quick_reg')
{
extract($_POST);
print_r($_POST);
$result=$dbg->exec("INSERT INTO `login_register`(`email`, `password`, `reg_date`, `complite_register`, `type`) VALUES ('$client_mail','$client_password', now(),'0','c_finder')") or die("Insert Failed ".mysql_error());
$lastId = $dbg->lastInsertId();
$results=$dbg->exec("INSERT INTO `care_finder`(`postal_code`,`user_pic`, `login_id`,`f_name`, `l_name`, `gender` ) VALUES ('$postal_code', 'default.jpg','$lastId', '$f_name', '$l_name', '$gender')")or die("Insert Failed ".mysql_error());
}
else{echo 'error';}
if($results){
include_once 'connection.php';
$con=new connection();
$dbg=$con->db;
$sql="SELECT * FROM `login_register` WHERE `login_id`='$lastId'";
$stmt=$dbg->query($sql);
$rows=$stmt->fetch(PDO::FETCH_ASSOC);
session_start();
//echo $lastId;
$_SESSION['Uname']=$rows['email'];
$_SESSION['pword']=$rows['password'];
$_SESSION['Utype']=$rows['type'];
$_SESSION['Uid']=$rows['login_id'];
}
after this db.php page it will go to user_index.php
following code is using in user_index.php
<?php
session_start();
if (!isset($_SESSION['Uname'])) {
//header("location:index.php");
echo 'no sesseion';
}
else {
......
......
}
can some one help me
You're outputting before starting the session
if($_POST['action']=='finder_quick_reg')
{
// ...
print_r($_POST);
// ...
}
else { echo 'error'; }
And from the title I'd assume that error_reporting is turned off on the production server, otherwise you'd have seen an error message along the lines of
Warning: Cannot modify header information - headers already sent...
You should start the session exactly like in you're doing in your other file - at the very beginning of it, before all other statements.
On a side note, have a look at the point notes in the documentation for export() function, there it's written why/that it's a bad idea to use it on untrusted data.
session_start();
should come from login page on.

Can't enter the home page, always directing back to login page

As this page is owned by it users, so it has each credentials to enter it which it is by using login form of php (that's what I know so far, I am not very good in php, to be honest).
The problem I do really guess about this must be in the using of session function (and this is the most complicated things to me know, I am not very familiar of using this.)
In the config of the form, I set the session like this (Well, I just copy paste the code from somewhhere) as follow:
// User Redirect Conditions will go here
if($count==1)
{
// Save type and other information in Session for future use.
$_SESSION[type]=$row[0];
$_SESSION[Region]=$row[1];
$_SESSION[myemail]=$myemail;
// if user type is ACTAdmin only then he can access protected page.
if($row[0] == 'ACTAdmin') {
header( "location:index.php");
}
else {
header( "location:login.html");
}
}
else
{
header("location:login.html");
}
// Closing MySQL database connection
$dbh = null;
In the head of the home page (and in each all related pages), I write a session start there like this:
<?php
include('UserSessionAdmin.php');
?>
In which it will get the data from UserSessionAdmin.php:
<?php
session_start();
if($_SESSION[type]!='ACTAdmin'){
header('location:login.html');
exit();
}
include('configPDO.php');
?>
What is included in the configPDO.php is here:
<?php
// mysql hostname
$hostname = 'mysql.com';
// mysql username
$username = 'alkushh';
// mysql password
$password = 'alkush';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=user", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It's been more than two days for me just to solve it but I don't have any idea how to. Some people who are experts in here may help me with this thing, please.
Thank you and regards,
Here is the full script that define the $count==1
<?php
// Start Session because we will save some values to session varaible.
session_start();
// include connection file
include("configPDO.php");
// Define $myusername and $mypassword
$myemail=$_POST['myemail'];
$mypassword=$_POST['mypassword'];
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT Type,Region FROM user WHERE myemail = :myemail AND mypassword = :mypassword");
// bind paramenters, Named paramenters alaways start with colon(:)
$STM->bindParam(':myemail', $myemail);
$STM->bindParam(':mypassword', $mypassword);
// For Executing prepared statement we will use below function
$STM->execute();
// Count no. of records
$count = $STM->rowCount();
//just fetch. only gets one row. So no foreach loop needed :)
$row = $STM -> fetch();
// User Redirect Conditions will go here
if($count==1)
.....
.....
Here it is
if ( $count == 1 ) {
$_SESSION['login_id'] = $row['id']; // i prefer to name it login_id, you can use $row['id'] or $row[0]. but i prefer to write with the column name
if ( $_SESSION['login_id'] == 1 ) { // it means if login id = 1 then go to index.php
header("location: index.php");
} else {
header("location: login.html");
}
}
else { header("location: login.html"); }
i cut session region because you didnt have a region column and also i cut session myemail because you didnt need it
UserSessionAdmin.php
<?php
session_start();
if ( $_SESSION['login_id'] == 0 || $_SESSION['login_id'] == '' ) {
header('location: login.html');
exit();
}
require_once('configPDO.php');
?>
Please turn on your error reporting to see, that there is no constants such as type, Region, myemail. Use " or ' around parameter of session:
if (strcmp($_SESSION['type'], 'ACTAdmin') !== 0) {
header('location:login.html');
exit();
}

Session Flag Doesn't Direct to Login Page

I have a home page that before entering the page the user must login first. I have put session start in the head of the page, but when I enter the url of the page, it doesn;t direct me to the login page in fact I have not login yet.
This is my session start (index.php):
<?php
#session_start();
$username = $_SESSION['username'];
if( $_SESSION['flag']==1)
echo'<script>window.location="login.php";</script>';
?>
This is the login-config.php:
<?php
ob_start();
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", true);
error_reporting(-1);
ini_set('display_errors', 'On');
$con =mysqli_connect(".com","sih","st1","ceuser");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myemail= $_POST['myemail'];
$mypassword= $_POST['mypassword'];
$sql= "SELECT * FROM user WHERE myemail='".$myemail."' and mypassword='".$mypassword."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
$_SESSION['username']=$username;
$_SESSION['logged-in'] = true;
header("location:index.php");
exit;
}
ob_end_flush();
?>
I guess I am missing something. I am very new in Php and I want to learn it. Please help me.
I would redo your logic so that;
No sessions indexes are created without the user logging in
For your index, use;
<?php
session_start();
if( array_key_exists('logged_in', $_SESSION) ) {
//They've logged in
//Redirect to whatever page
//You may want to check that $_SESSION['username'] holds a valid username
header('Location: loggedin.php');
die;
} else {
//They've not logged in
//Redirect to login page
header('Location: login.php');
die;
}
Now that we have a basic "router", we can modify your login-config.php file.
// ...
if( $count == 1 ) {
$_SESSION['username'] = $username;
$_SESSION['logged_in'] = true;
header("location:loggedin.php");
exit;
}
Now, loggedin.php
<?php
session_start();
if( array_key_exists('logged_in', $_SESSION) ) {
//Check $_SESSION['username'] holds a valid username in your database.
if( $blUsernameIsValid ) {
// Continue
echo "Hello ". $_SESSION['username'] ."! You have logged in";
} else {
session_destroy();
unset($_SESSION['logged_in']);
header('Location: index.php');
die;
}
} else {
//Unauthorised access
http_response_code(401);
echo "Unauthorised. Please Login";
die;
}
Useful resources
How to Create a Secure Login Script in PHP and MySQL
PHP-Login Project
A Google search
Stackoverflow Questions

Categories