Having sesstion_start error on index page - php

I am working on a new project www.merapalwal.com. I have created a user login panel for this project where the user can login with their email id and password. Everything is working fine, user created and updated correctly. I used login form in header page which is included in all other pages.
I have created two db files, db-user.php (for db config) and db-sess.php (for db config with session_start). But if I use db-sess.php on the login form in header-top.php, it gives me the error:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/mypalwal/public_html/index.php:16) in /home/mypalwal/public_html/includes/db-sess.php on line 3
When I use db-user.php, it allows a user to log in but does not show the username after welcome, please advise me code as under:
header.php:
<?php
ini_set('session.bug_compat_42',0);
ini_set('session.bug_compat_warn',0);
include('includes/db-sess.php');
$error = '';
$form = $_POST['login'];
$lemail = $_POST['lemail'];
$pass = $_POST['pass'];
$_SESSION['lemail'] = $_POST['lemail'];
if( isset($form) ) {
if( isset($lemail) && isset($pass) && $lemail !== '' && $pass !== '' ) {
$sql = mysql_query("SELECT * FROM `userdata` WHERE email='$lemail' and pass='$pass' and type='Normal User';");
if( mysql_num_rows($sql) != 0 ) { //success
$_SESSION['logged-in'] = true;
print "<script type=\"text/javascript\">";
print "window.location.href = \"users/index.php\"";
print "</script>";
exit;
}
else { $error = "Login Detail Incorrect"; }
} else { $error = 'Login Detail Missing';}
}
?>
db-user.php:
<?php
$dbhost = 'localhost';
$dbuser = '######';
$dbpass = '######';
$db = '#######';
$conn = mysql_connect($dbhost, $dbuser, $dbpass );
mysql_select_db($db);
?>
If I use the above code for db config, it allows login and redirects to the next page but does not show user details but when I use db-sess.php which has session_start in it, the login form allows me to login and shows the username.
If I use db-sess.php, it shows an error on index.php page:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/mypalwal/public_html/index.php:16) in /home/mypalwal/public_html/includes/db-sess.php on line 3

There is some space before in one of the 3 files, which causes the page output to be started and headers to be sent. Remove the space and especially remove the ?>
P.S.: You have 2 astonishing security issues in your code: SQL Injection possibilities and clear text passwords.

Related

Loggin into the backend fails while using online CPANEL

Hello guys i have a sight i have built in xampp it works well that is it can log in to the dashboard without hustle and create session and the user can afterwards log out. but after I launched the site the user cannot log it the site is just not responding. the log in screen is on i tried changing the script and all i get is just a white page, if i put the right script it redirects to the same login page. my host uses linux cpanel and thats the terminal i am using. mind you the site works fine connects well to the db and it even pulls the users available in the db but they issue is in the back end. here is the code i am using..
<?php
/* Main page with two forms: sign up and log in */
require '../config/config.php';
session_start();
?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['login'])) { //user logging in
require '../sessions/login.php';
}
elseif (isset($_POST['register'])) { //user registering
require '../sessions/register.php';
}
}
?>
<?php
// Check if form submitted with method="post"
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if (isset($_POST['reset'])) {
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM staff WHERE email='$email'");
if ( $result->num_rows == 0 ) // User doesn't exist
{
header("location: index.php?msg=".urlencode("User with this email does not exist!"));
}
else { // User exists (num_rows != 0)
$user = $result->fetch_assoc(); // $user becomes array with user data
$email = $user['email'];
$hash = $user['hash'];
$first_name = $user['first_name'];
// Send registration confirmation link (reset.php)
$to = $email;
$subject = 'Password Reset Link (site )';
$message_body = '
Hello '.$first_name.',
You have requested password reset!
Please click this link to reset your password:
http://sitename/reset.php?email='.$email.'&hash='.$hash;
mail($to, $subject, $message_body);
header("location: reset.php?msg=".urlencode("<p>Please check your email <span>$email</span>"
. " for a confirmation link to complete your password reset!</p>"));
}
}
}
?>
this is the login script
// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM staff WHERE email='$email'");
if ( $result->num_rows == 0 ){ // User doesn't exist
header("location: index.php?msg=".urlencode("User with that email doesn't exist!"));
}
else { // User exists
$user = $result->fetch_assoc();
if ( password_verify($_POST['password'], $user['password']) ) {
$_SESSION['email'] = $user['email'];
$_SESSION['f_name'] = $user['f_name'];
$_SESSION['l_name'] = $user['l_name'];
$_SESSION['image'] = $user['image'];
$_SESSION['id'] = $user['id'];
$_SESSION['active'] = $user['active'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: home.php");
}
else {
header("location: ../index.php?msg=".urlencode('You have entered wrong password, try again!'));
}
}
?>
If anyone have a clue ?
White Screen Of Death:
If you're seeing a blank page (and view-source is empty), make sure your php.ini contains error_reporting = -1 and display_errors = On (only recommended for development). Putting: at the top of your script might have no effect if your script fails to compile such as in the case of PARSE errors.
Your error will now appear on the page. However, that's not great for a live production system.
For the best error logging experience, set error_reporting to -1, turn display_errors off, and set a custom error_log. Then in the terminal, type tail -f /path/to/error_log. Your notices, warnings and errors will now scroll past in real time, without distorting your web page's display.

login code error, session_start()

I am trying to create a login form, I created the html form and wrote this PHP code but I keep on getting an error about session_start(); and header already sent
The error:
Warning: session_start(): Cannot send session cookie - headers already sent by
<?php
session_start();
if($_POST['submit'])
{
include_once('my_connection.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$sql = "SELECT id,username,password FROM users WHERE username = '$username' AND password = '$password'";
$query = mysqli_query($connect,$sql);
if($query) {
$row = mysqli_fetch_row($query);
$id = $row[0];
$dbusername = $row[1];
$dbpassword = $row[2];
if($username == $dbusername && $password == $dbpassword)
{
$_SESSION['username'] = $username;
$_SESSION['id'] =$id;
header('Location:home.php');
}else {
echo "Incorrect username or password.";
} } }?>
I put the session_start() on the top of the code but still don't work
Warning: session_start(): Cannot send session cookie
To start with, always have your start_session() at the top. Yes, adding ob_start() above it may fix it and adding ob_flush() at the bottom could but it looks like it hasn't so:
If you're requiring the same file or another file, ensure the file you're requiring does not have a session_start() function within it. Ensure you have no duplicates of session_start() anywhere else either in the same code.
Also, a big reason actually may be because you're missing syntax in your header() and the program is not finishing/ending, only requiring.
Change it to this:
header('Location: home.php');
exit;
Sources to further help you:
Source 1
Source 2

How do i write restrict access to a page?

I wrote custom login script for users to login to the main control page. I found out that even when users are not login they can still visit the main control of which I want someone to help me to write a restrict access to page().
Please look through my php login script and based on that code help me write the restrict access to the main control page. assume that my main crontrol page is: cecontrolpage.php
I know we use $_SESSION to that but I have little idea of it.
this is my login.php code which is working fine:
<?php
Session_start();
$Email = $_POST["email"];
$Password = $_POST["password"];
$cn = "localhost";
$db_username = "root";
$pas = "***";
$db_name = "cemembers";
//Open a connection to a MySQL Server
if ($Email && $Password) {
$connect = mysqli_connect($cn, $db_username, $pas, $db_name) or die("Could not connect to database");
//sending MySqli query
$query = mysqli_query($connect, "SELECT * FROM users WHERE Email= '$Email'");
$numrows = mysqli_num_rows($query);
//After PHP declaration we are going to create index file[form]
if ($numrows !== 0) {
while ($row = mysqli_fetch_array($query)) {
$dbEmail = $row["Email"];
$dbPassword = $row["Password"];
}
if ($Email == $dbEmail && $Password == $dbPassword) {
header("location:ce membership birthday system control_pannel.php");
#$_SESSION("Email") == $Email;
} else
header("location:index.php?login_attempt=1");
} else
header("location:index.php?login_attempt=2");
} else
header("Location:index.php?login_attempt=0");
?>
please can someone help me write the php code to restrict access to cecontrol.php ??
Please STEP by STEP with php comments on each part.
First you need to check if the user is logged in:
you do that by checking if the session has been set.
//Check if the user is logged in
function userlogged_in()
{
return(isset($_SESSION['userid']))?true:false;
}
Then you need to redirect the user to a page that says the access to is not authorised, they need to be logged in to view that page:
You do this by checking if the userlogged_in function returned a true or false
function user_restricted()
{
if (userlogged_in()=== false)
{
header('Location: permission.php ');
exit();
}
}
Then you need to call the user_restricted() function on each page, just after starting the session.
First you have to save user values in session after authentication from database like
$_SESSION['username'] = "name"; $_SESSION['user_id'] = 1;
function check_session() {
session_start();
if ($_SESSION['user_id']=='')
{
// redirect to login
}
}
On every page that you want to restrict access you can call check_session().

Session script not setting variable

I'm new to sessions and don't think my code is working correctly.
My aim is to use PDO and not SQL, but as I'm also new to PDO too, I'm getting a little stuck.
I'm trying to set up my $who as a session but things are getting confusing for me as I go between SQL and PDO. Can you help me make things kosher?
<?php
require_once('/scripts/include.php');
require_once('/scripts/includePDO.php');
$error = '';
$form = $_POST['submit'];
$email = $_POST['email'];
$password = $_POST['password'];
if( isset($form) ) {
if( isset($email) && isset($password) && $email !== '' && $password !== '' ) {
$sql = "SELECT * FROM tbl_users WHERE email = :email and password = :password";
$q = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that
$q->bindValue(':email',$email,PDO::PARAM_STR);
$q->bindValue(':password',$password,PDO::PARAM_STR);
$q->execute();
$r = $q->fetch(PDO::FETCH_ASSOC);
if(($r)!=0)
{ //success
$info = mysql_fetch_array( $sql );
$answer = $info['id'];
$_SESSION['logged-in'] = true;
$_SESSION['who']=$answer;
//If the login details are entered and they match those in the database, forward to new page.
header('Location: /social3/home/');
exit;
// If information is wrong or missing, provide error message.
} else { echo "Sorry, something hasn't worked. Are you entering all the information correctly?"; }
}
}
?>
I think everything is fine until I get to //success and then I lost my way.
----- Additional session question ----
At the top of each of my website pages, I include a php file that allows PDO to connect to my database. This is necessary as most of my pages use PDO queries.
But looking back at that coding now, it, for some reason, has some session coding at the top. Should this be there (taking into account, I assign a session on an entirely different page?
<?php
session_start();
$host = "xxxx";
$db = "xxxx";
$user = "xxxx";
$pass = "xxxxx";
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
?>
--- Further questioning ---
So, finally... more session and PDO wonderings.
At the top of each page, I include a file to ensure the user is logged in, if not they get forwarded to the login page.
I'm changing this code to PDO from SQL also, and obviously have gaps in my PDO knowledge which show in the below code. Help?
<?php
session_start();
$who = $_SESSION['who'];
$host = "xxx";
$username = "xxxx";
$password = "xxxx";
$db = "xxx";
#mysql_connect(:host,:username,:password);
$q = $conn->prepare($sql);
$q->bindValue(':host',$host,PDO::PARAM_STR);
$q->bindValue(':username',$username,PDO::PARAM_STR);
$q->bindValue(':password',$password,PDO::PARAM_STR);
$q->execute();
#mysql_select_db($db) or die("error");
// is the one accessing this page logged in or not?
if ( !isset($_SESSION['logged-in']) || $_SESSION['logged-in'] !== true) {
// not logged in, move to login page
header('Location: /social3/');
exit;
}
?>
You are using PDO, so these line will not work -
$info = mysql_fetch_array( $sql );
$answer = $info['id'];
You have already fetched the row and stored it in $r, so you just need -
$answer = $r['id'];
in response to your edit.
The session_start(); that is on the top of your included php code/page is necessary. Without it you could not do $_SESSION['logged-in'] = true; & $_SESSION['who']=$answer;. You need to start a session in order to set session values, and it must be before any data/headers are sent. Take a look at the manual - http://php.net/session_start

PHP session start "Cannot send session cookie and cache limiter"

I've changed my hosting server from a Windows to a Linux system. But when I run my PHP program, I get this errors:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/content/p/y/c/francis/html/login/login.php:2) in /home/content/p/y/c/francis/html/login/login.php on line 4
and
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/p/y/c/francis/html/login/login.php:2) in /home/content/p/y/c/francis/html/login/login.php on line 4
This is the code of my program:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password)
{
$connect = mysql_connect(***,***,***);
mysql_select_db("phploginregister") or die("Couldn't find db");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows != 0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//check to see if they match!
if ($username == $dbusername && md5($password) == $dbpassword)
{
echo "You're in! <a href='member.php'>Click</a> here to enter the member page.";
$_SESSION['username'] = $dbusername;
}
else
echo "Incorrect password";
}
else
die("That user doens't exist!");
}
else
die("Please enter an username and password");
?>
What is wrong in the code, because it workend fine on a Windows host...
You get the error because there are some output before you have initiated session_start(); This could be caused because of your editor that include a BOM character in the beginning of your file. Try open the code in notepad and see if there are any lines before session_start(), (spaces) or things like that and remove them.
To fix your editor if it add a bom in your file, you need to go to your settings and turn it off.
You have a leading BOM, new line or other whitespace character before the opening <?php tag.
The errors talk about line 2 and line 4, but in the actual code above session_start() is called on line 3. Therefore, leading whitespace is the problem...
i think you should add
ob_start();
in the first of your code
and in the bottom add
ob_get_contents();
ob_end_flush();
because of
session send headers to server , also you added echo ( this also tell server its html with headers )
server now has to headers so use the ob_start(); and ob_end_flush(); to work :)

Categories