PHP Check if user is logged in with a function - php

I'm working on a website and the index page checks if the user is logged in or not with this piece of code:
if (!$_SESSION['login'] && $_SESSION['login'] == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} elseif ($_SESSION['login'] == 1) {
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}
But I want it to look cleaner, then I started wondering if was possible to achieve something like this with a function:
checklogin($_SESSION['login']);
I don't have much experience with functions, so i'm sorry if my question looks stupid, so thanks in advance.

Try this
if(check_login()) {
echo 'You are in!';
} else {
header('Location: login.php');
exit;
}
function check_login () {
if(isset($_SESSION['login'] && $_SESSION['login'] != '') {
return true;
} else {
false;
}
}

Just use empty:
if ( empty($_SESSION['login']) ) {
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} else {
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}
Or condense it:
include_once $_SERVER['DOCUMENT_ROOT'].(empty($_SESSION['login']) ? "/login/" : "/main/");

There is what you need:
function userCheck()
{
return (isSet($_SESSION['login']) && $_SESSION['login']);
}
if(userCheck())
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
else
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");

Disregarding the fact of whether or not your approach makes sense, I think this would do what you expect:
function checklogin($login){
if (!$login && $login == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/path/");
}
}
// **** call to the function
checklogin($_SESSION['login']);
// ****

You can use this function:
function checklogin() {
return (isset($_SESSION['login'])) ? true : false;
}
then on pages you want to check whether the user is logged in or not, you can:
if(checklogin() === true){
//here you would put what you want to do if the user is logged in
} else {
//this would be executed if user isn't logged in
header('Location: protected.php');
exit();
//the above would redirect the user
}

Related

Using PHP function for shortening repeating code

My code in PHP is pretty long and I want to make it shorter with creating one function with different values and than I would just write one line with function name instead of many lines of code, but it doesn't seem to work.
This is that repeating code:
if (!isset($_POST['ID_user']) || empty($_POST['ID_user'])) {
$_SESSION['ID_user_missing'] = "error";
header("location: index.php");
} else {
$ID_user = $_POST['ID_user'];
}
if (!isset($_POST['meta_name']) || empty($_POST['meta_name'])) {
$_SESSION['meta_name_missing'] = "error";
header("location: index.php");
} else {
$meta_name = $_POST['ID_user'];
}
if (!isset($_POST['meta_value']) || empty($_POST['meta_value'])) {
$_SESSION['meta_value_missing'] = "error";
header("location: index.php");
} else {
$meta_value = $_POST['meta_value'];
}
And this was the plan, instead of that code up ther, I would just have this down below:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
$$value = $_POST[$value];
}
}
ifIssetPost('ID_user');
ifIssetPost('meta_name');
ifIssetPost('meta_value');
But it just doesn't work, when you try to echo for example variable $meta_name it shows that it's empty. Can you help me ? Thank you very much.
NOTE: when I doesn't that function and do it the long way, everything works just fine, but the problem comes when I use that function.
The variable is in the scope of function. That's why you cannot access to it outside the function. You could return the value:
function ifIssetPost($value) {
if (empty($_POST[$value])) { // Only empty is needed (as pointed out by #AbraCadaver)
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
exit; // add exit to stop the execution of the script.
}
return $_POST[$value]; // return value
}
$ID_user = ifIssetPost('ID_user');
$meta_name = ifIssetPost('meta_name');
$meta_value = ifIssetPost('meta_value');
You can also follow your specification, using $$value:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
return $_POST[$value];
}
}
$value = 'ID_user';
$$value = ifIssetPost($value);
echo $ID_user;
$value = 'meta_name';
$$value = ifIssetPost($value);
echo $meta_name;
You can use an array to iterate over the $_POST vars. If you want to declare a variable using a string or another variable containing an string, you need to use {}. like ${$value}
$postValues = ["ID_user", "meta_name", "meta_value"];
foreach ($postValues as $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value."_missing"] = "error";
header("location: index.php");
} else {
${$value} = $_POST[$value];
}
}

How to nest if (isset($_POST['submit'])) (with tokens also)

I have that code and it work fine:
if (isset($_POST['submit1']))
{
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
include_once('./token.php');
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php'); //**PAGE WITH SUBMIT1**
}
token.php
$form_token = uniqid();
$_SESSION['user_token'] = $form_token;
The form in my1page.php contains:
<input type="hidden" name="user_token" value="<?php echo $_SESSION['user_token'];?>">
Now i need to nest a second if isset submit (token must be unset in the last submit).
WHAT I TRIED WITHOUT SUCCESS
if(isset($_POST['submit'])){
$_SESSION['submit']=true;
}
if (isset($_POST['submit']) || ( isset($_SESSION['submit']) && $_SESSION['submit'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit1'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
$_SESSION['submit']=false;
include_once('./script/token.php');
include_once('./my3page.php');
} else {
header("location: ./3.php");
}
}
include_once('./my2page.php');
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
HTTP works stateless. That means that what is happening here is the following:
User calls this page for the first time. He sends a GET request so isset($_POST['submit1']) is false.
Now he clicks on submit and sends the first POST request. (I assume that you set a value for submit1 there.) isset($_POST['submit1']) is true and my2page.php gets returned.
He sends the third request. Again a POST request, but this time with a value for submit2. Your server template engine starts evaluating the php. isset($_POST['submit1']) is false, so it returns the old my1page.php
Basically, don't nest your checks, but use a it else instead. (Think of it as a switch/case
isset($_POST['submit1']) → ./my2page.php
isset($_POST['submit2']) → //end page
none → ./my1page.php
You can't have 2 submits in the same time so what happens here is
if(condition){
if(!condition){
//do somthing
}
}
this will never works try to use another page or i advice to save the first submit in the $_SESSION;
ADD this lign
$_SESSION['submit1'] = (isset($_POST['submit1']))? true: false;
than change the first condition
if (isset($_POST['submit1']) || $_SESSION['submit1']) {
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit2'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
$_SESSION['submit1']=false; //or unset($_SESSION['submit1']);
//DO SOMETHINGS
} else {
header("location: ./index.php");
}
}
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
This is how it should be;
if(isset($_POST['submit1'])){
$_SESSION['submit1']=true;
}
if (isset($_POST['submit1']) || $_SESSION['submit1']) {
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit2'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
$_SESSION['submit1']=false; //or unset($_SESSION['submit1']);
//DO SOMETHINGS
} else {
header("location: ./index.php");
}
}
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
Your close you could possible just change this
if (isset($_POST['submit1'],$_POST['submit2'])) { //check isset on both
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit2'])) {
// if($_SESSION['user_token'] == $_POST['user_token']) { <--redundant check
unset($_SESSION['user_token']);
//DO SOMETHINGS
}
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
Depending on if you want an AND or an OR the above is equivalent to this
if (isset($_POST['submit1']) && isset($_POST['submit2'])) {
Obviously if you want an or then just put it here
if (isset($_POST['submit1']) || isset($_POST['submit2'])) {
It's not clear if you are talking about 2 POST's that are separate or concurrent

Why header() doesn't redirect me correctly?

Here is my website's folder structure:
myweb/
index.php
files/
autoloader.php
login.php
And here is my script:
// login.php
class login{
public function __construct () {
function signed(){
header('Location: ../');
exit;
}
}
public function index(){
echo isset($_SESSION['error_message']) ? $_SESSION['error_message'] : null;
if ( $_SESSION['login'] == 1 ) {
signed();
}
$_SESSION['login'] = 1;
if ( $_SESSION['login'] == 1 ) {
$_SESSION['error_message'] = 'something is wrong';
header('location: ../login');
}
}
}
When I load this path:
localhost/myweb/login
Here is two cases:
$_SESSION['login'] is equal to 1: My script redirects me to this path: localhost/myweb
$_SESSION['login'] isn't equal to 1: My script redirects me to this path: localhost
The first case is fine, I mean it works as expected. But the second case is wrong, I mean it doesn't work as expected. In the second case, it should redirect me to this path: localhost/myweb/login. Well how can I fix it?
Note: All pages pass through the index.php.
You can use ob_start(); on top of the page and ob_end_flush(); after header . It should work
last option you can use JavaScript for redirecting the page
ob_start();
class login{
public function __construct () {
function signed(){
header('Location: ../');
ob_end_flush();
exit;
}
}
public function index(){
if ( $_SESSION['login'] == 1 ) {
signed();
}
$_SESSION['login'] = 1;
if ( $_SESSION['login'] == 1 ) {
header('location: ../login');
ob_end_flush();
}
}
}
Based on your code, I don't see any condition of $_SESSION['login'] being compared as not equal (!=) to 1.
And this part does not make any sense,
$_SESSION['login'] = 1;
if ( $_SESSION['login'] == 1 ) {
$_SESSION['error_message'] = 'something is wrong';
header('location: ../login');
}
you always set the session login to 1, thus there's no way it will enter to that condition.

Can visitors still send POST if they're not logged in?

I have a code that goes the following:
if($_SESSION["verified"] !== true) {
header('location:login.php');
exit();
}
else {
//do code...
if(isset($_POST["submit"])) {
//do stuff with code...
}
}
Do I need to specify in the 2nd if tag that it should only run if they're logged in?
if($_SESSION["verified"] !== true) {
header('location:login.php');
exit();
}
else {
//do code...
if(isset($_POST["submit"]) && $_SESSION["verified"] === true) {
//do stuff with code...
}
}
To prevent people from submitting a POST on a page they shouldn't actually be able to access?
Or is there some better way to do it?

How to change the elements in the page base on user who is logged in

Please give me an idea on how to display elements in a page depending on who is logged in. For example, a user or an administrator.
I'm thinking of something like this but I get a parse error, what do I lack in this code?:
EDIT:
<?php
session_start();
if (!(isset($_SESSION['loginAdmin']) && $_SESSION['loginAdmin'] != '')) {
header ("Location: loginam.php");
}
else if (!(isset($_SESSION['loginAdmin']) && $_SESSION['loginAdmin'] =='')) {
include('head2.php');
}
else if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}
else if (!(isset($_SESSION['login']) && $_SESSION['login'] =='')) {
include('head3.php');
}
?>
Please help, there's no error but its not functioning properly. Whenever I try to access the page where I have this code. And login as a user. It redirects to loginam.php(the page where the admin will login). But there's no problem when I log in as admin. It works properly. What do I do?
Use
if (condition)
{
}
else if (condition) {
}
Also Just to make things simpler .. try something like ..
function is_admin() {
if(isset($_SESSION['loginAdmin']) && $_SESSION['loginAdmin'])
return true;
} else {
return false;
}
}
and then check
if(is_admin()) {
///admin block
} else {
//admin login
}
if(is_user()) {
///user block
} else {
//user login
}
if else is not valid. It's else if.
Other than that, it would help if you posted the parser error along with your code.
You're also not closing your <?php statement before opening it again.
because you have an invalid code.
he's the trimmed code:
&lt?php
session_start();
if (!isset($_SESSION['loginAdmin']) && ($_SESSION['loginAdmin'] != '')) {
header ("Location: loginam.php");
} else {
include('head2.php');
}
?>
&lt?php
if (!isset($_SESSION['login']) && ($_SESSION['login'] != '')) {
header ("Location: login.php");
} else {
include('head3.php');
}
?>
pay a little attention to the code.

Categories