Php, session id control doesnt work? - php

here is the code drives me crazy:)
<?php
$deger=0;
if (session_id() == '') {
session_start();
$deger=1;
}
else{
$deger=0;
}
$row = mysql_fetch_row($result);
$counter =$row[2];
if($deger==1){
$counter--;
}
echo $counter;
?>
This basic code drives me crazy. the deger==1 condition always returns true and keeps decrementing the counter. What I would like to do is check the session if the session is new decrement it only once. after that dont decrement the value. Am I missing something here? I am new to php maybe I am missing something.
I look forward to your answers thanks.

i think you have to call session_start(); before any chacks like if (session_id() == '') cause theres really nothing in session_id when session has not been started. this code i one used is working for me (may be not perfect):
session_start();
$user = (isset($_SESSION['user']) && $_SESSION['user'] != '' ? $_SESSION['user'] : null);
if ($user == null) {
//it's a not logged in user
//checking users credentials and if it's ok
$_SESSION['user'] = $uid; //or whatever you want to use to identify a user
} else {
//it's logged in user
}

There is always a user session, but not always a php session. So if you did not do a session_start() yet, you can check that with something like this:
if (isset($_SESSION]['loggedin'])){
$deger = 0;
} else {
$deger = 1;
session_start();
$_SESSION['loggedin'] = true;
}
Wherever you start the session, also fill the $_SESSION var.

Related

Managing two different SESSION in PHP

I have a table for users in my MySQL database with a tinyint value (0 or 1) which I use to determinate the category of the user.
So, at my login.php, I get the value (stored as 'admin'):
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
$isadmin = intval($row['admin']);
Then I assign the session:
if (password_verify($pwd, $row['password']) && $count==1){
if($isadmin==1) {
$_SESSION['admin_session'] = $row['userid'];
header("location: adminpanel.php");
} else {
$_SESSION['user_session'] = $row['userid'];
header("location: adminpanel.php");
}
}
And when it comes to check the session, I do this:
if (isset($_SESSION['user_session'])){
header("location: adminpanel.php");
exit;
} else if(isset($_SESSION['admin_session'])){
header("location: adminpanel.php");
exit;
}
But... It's not working. The page doesn't load and it shows a browser error message saying there are too many redirections being made. How can I do this?
I know both sessions are heading to the same "adminpanel.php". What I'm trying to do is both can access but once they're logged, depending on its category (whether they're admin or not), they'll be able to do certain stuff.
I would suggest simplifying the process and just keeping a User in the session with a flag telling you if they are an admin or not.
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
if (password_verify($pwd, $row['password'])){
$_SESSION['user'] = $row['userid'];
$_SESSION['isadmin'] = $row['admin'] == 1 ? true : false;
}
And when it comes to check the session, I do this:
if (isset($_SESSION['isadmin']) && $_SESSION['isadmin']){
header("location: adminpanel.php");
exit;
} else
// NOTE you had this redirecting exactly as above to adminpanel
header("location: userpanel.php");
exit;
}
Try to add ob_start(); on the top of your php script. I think it's because of your using header function many times.

Register form Error Correction in PHP - Best solution?

I'm looking for as simple approach to correcting errors such as non-matching passwords and people inserting blank data into a form in HTML.
I want to use PHP to throw me back an error when this happens, I was considering using if statements but realised it would not show more than one error if it happens.
Here is an example of what I was doing, keeping in mind $firstname's input is from POST:
if ($firstname == "")
{
$_SESSION['nofirstname'] = 1;
header('Location: register.php');
}
In register.php it picks up this, and warns the user that he has entered no first name. This is cool but won't display additional errors if there are any. I'm guessing switches and arrays are the way forward but I don't really understand how to add a entry to an array.
Anyone able to help?
session_start();
....
$_SESSION['flag']=false;
if ($firstname == "")
{
$_SESSION['nofirstname'] = 1;$_SESSION['flag']=true;
}
if ($lastnamee == "")
{
$_SESSION['nolastname'] = 1;$_SESSION['flag']=true;
}
...
header('Location: register.php');
in register.php
session_start();
...
if ($_SESSION['flag']==true){
if ($_SESSION['nofirstname']==1) {///message}
if ($_SESSION['nolastname']==1) {///message}
...
}
Use a nested if, e.g;
<?php
if($firstcond){
if($secondcond){
}else{
$_SESSION['error'] = 'Second Condition not met!';
header('Location: register.php');
//error
}
}else{
$_SESSION['error'] = 'First Condition not met!';
header('Location: register.php');
//error
}
?>
This means that in order for $secondcond to be validated, $firstcond must pass whatever checks you perform on it first :)
session_start();
ob_start()
if ($firstname == "")
{
$_SESSION['nofirstname'] = "Enter your name";
header('Location: register.php');
}
Redirect the page and display
echo isset($_SESSION['nofirstname'])?$_SESSION['nofirstname']:'';
Try this.
Try this:
session_start();
$errors = array();
if ($firstname == "")
{
$errors['nofirstname'] = 1;
}
if ($lastname == "")
{
$errors['nolastname'] = 1;
}
$run = 1;
foreach ($errors AS $key => $value)
{
$_SESSION[$key] = $value;
$run = 0;
}
if (!$run)
header('Location: register.php');

creating two different sessions in PHP

I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.

how to set a session time for specific page

When you go to this page;
http://www.ctuchicago.com/registration/login.php
you will see the form that I made. I want to create a session if username and password is true than I wanna set a 20 minutes expire time for it. How can I do it ?
my check.php
$user = $_POST['user'];
$pass = $_POST['pass'];
$ruser = "a";
$rpass = "b";
if ($user == $ruser) {
$logn = "True";
} else {
$logn = "False";
}
if ($pass == $rpass) {
$logs = "True";
} else {
$logs = "False";
}
if ($logn == "False" && $logs == "False") {
echo '<script type="text/javascript">alert("The Username and The Password are both wrong ! Please check your information and try again.");history.go(-1);</script>';
} elseif ($logn == "True" && $logs == "False") {
echo '<script type="text/javascript">alert("The Username is True but something is wrong with the password you entered. Please check your information and try again.");history.go(-1);</script>';
} elseif ($logn == "False" && $logs == "True") {
echo '<script type="text/javascript">alert("The Password is True but something is wrong with the password you entered. Please check your information and try again.");history.go(-1);</script>';
} else {
$_SESSION['valid'] = "1";
echo '<script type="text/javascript">window.location = "http://www.ctuchicago.com/registration"</script>';
}
my index.php (this page I want to be login required.
if ($_SESSION['valid']) {
echo '<script type="text/javascript">window.location = "http://www.ctuchicago.com/registration/login.php"</script>';
} else { Code }
Thank You
According to http://prajapatinilesh.wordpress.com/2009/01/14/manually-set-php-session-timeout-php-session/
ini_set(’session.gc_maxlifetime’, 20*60);
Have you considered using a [client side] cookie that expires in 20 minutes ? then whenever the page is (re)loaded, check for the cookie, invalidate the session if the cookie is invalid/expired.
See How do I expire a session after 30 minutes
EDIT
Basically what you are doing is creating your own session timeout function. When you hit the page you look for a variable you set in $_SESSION lets call it $_SESSION['started']. If you don't find that variable then you create it and give the value of the current timestamp. What you do then is every time you load a new page, you compare the $_SESSION['started'] variable with the time now and if it exceeds 20 minutes then you expire log the user out or do whatever you need to do.

$_SESSION difficulties

I am creating a login script that stores the value of a variable called $userid to $_SESSION["userid"] then redirects the user back to the main page (a side question is how to send them back where they were?).
However, when I get back to that page, I am echoing the session_id() and the value of $_SESSION["userid"] and only the session id shows up. It had occurred to me that maybe my redirect page needs to have at the top, but if this were true, then the session_id I'm echoing would change each time I end up on the page that is echoing it. Here is the script:
<?php
session_start();
include_once("db_include.php5");
doDB();
//check for required fields from the form
if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) {
header("Location: loginform.php5");
exit;
} else if($_POST["username"] && $_POST["password"]){
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit; }
} else if($_POST["email"] && $_POST["password"]) {
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit;}
} else {
//redirect back to login form
header("Location: loginform.php5");
exit;
}
mysqli_close($mysqli);
?>
You're doing this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
Where you should do this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $info["id"];
}
Make sure:
<?php
session_start();
Is at the top of each page.
Additionally, you can test by commenting out your redirects and echo'ing the value you're setting with to make sure you're retrieving/storing the correct value to begin with.
You need to call session_write_close() to store the session data changes.
Side answer: you can use the $SERVER["HTTP REFERER"] to redirect back, if it was filled by the browser

Categories