Function parameters when variables values are not set - php

How can I call a function without throwing any errors when certain variables are not set?
For example, I need to logUserActivity($uName,$uId). This'll work ok if a user is logged in and both those variables are set. However, it will not work if a user is not logged in, and will throw an error.
In that case can, something be done to make those two values NULL?
I did this: logUserActivity($uName=NULL,$uId=NULL) but this makes them forever NULL.
I also did function logUserActivity($uName=NULL, $uId=NULL), by this still throws an error.

You have to set default value of a function to make it optional
Like try this
function logUserActivity($uName='', $uId='')

function logUserActivity($uName=NULL, $uId=NULL){
if($uName != ''){
echo 'Uname is set - '.$uName;
}
if($uId != ''){
echo 'uId is set - '.$uId;
}
}
logUserActivity(NULL,20);//O/p - uId is set - 20
logUserActivity('Test',NULL);//O/p - Uname is set - Test
logUserActivity('Test',20);//O/p - uId is set - 20,uId is set - 20
logUserActivity(NULL,NULL);//NO O/p

Write like this:
function logUserActivity($uName=NULL, $uId=NULL) // If nothing is passed it will take it as null
{
if($uName==NULL && $uId == NULL) {
//User is not logged in
}
else
{
//user is logged in
}
}
And Call it as when user is logged in
logUserActivity("userName", 12345);
And When user is not logged in
logUserActivity();
For more information you can check this out:http://us2.php.net/manual/en/functions.arguments.php

function logUserActivity($uName=null,$uId=null) {
if ( !isset($uName) || !$uName ) {
$uName = 'some default'; // optionally, return; could be sued
}
if ( !isset($uId) || !$uId) {
$uId = 'some default'; // optionally, return; could be sued
}
}

Related

Checking for a specific user

I have the following code which makes sure that the user is logged in. But I want to change to code to check for a specific user id. Can anyone help me with this?
function protect_page() {
if (logged_in() === false) {
header('Location: protected.php');
exit();
}
}
You could update your login function with an extra optional variable.
If you don't specify the $user_id variable it will take the value 0, which will only check if the user is logged in. If you do specify a certain $user_id then the function will return true if the user is logged in and the $user_id matches the id stored in the session.
function logged_in($user_id = 0)
{
return (isset($_SESSION['user_id']) && (($user_id == 0) || ($_SESSION['user_id'] == $user_id))) ? true : false; //this function checks if the user is logged in and matches the given user identifier.
}
You can modify your function logged_in and pass the specific user id to the function:
function logged_in($id) {
//this function checks if the user is logged in and has a specific id
return (isset($_SESSION['user_id']) && $_SESSION['user_id'] === $id) ? true : false;
}
You have to change your protect_page function to fit the new logged_in function:
function protect_page() {
if (logged_in(7) === false){
header('Location: protected.php');
exit();
}
}

two if statements in php

I have two seperate if statements, the first if statement is not working but the second one is.
The first if statement works on my other pages and I am unsure of how to properly code this as I am a beginner to PHP.
<?php
session_start();
if($_SESSION['loggedin'] != 'true') {
header("location:login.php");
}
if ($_SESSION['admin']=='N') {
header("location:errorpage.php");
}
?>
What is true in your conditions? It can be bool type or string type.
If You set like this:
$_SESSION['loggedin'] = TRUE;
$_SESSION['loggedin'] = 'true';
You have got two different variable sets.
You can compare it using == or === to include variable type.
For example:
$_SESSION['test_1'] = TRUE;
$_SESSION['test_2'] = 'true';
var_dump( $_SESSION );
array(2) { ["test_1"]=> bool(true) ["test_2"]=> string(4) "true" }
$_SESSION['loggedin']?
Why don't just clear every SESSION var on logout and if the SESSION vars are set => the user is logged in.
And use after the header(); an exit();
Try var_dump($_SESSION['loggedin']) and edit your question.
Or maybe your loggedin var is not a string but a boolean so you could do if(!$_SESSION['loggedin'])
Try using Boolean values rather than strings. I would also use a const for the admin variables. I would do the following;
$_SESSION['loggedin'] = true/false;
$_SESSION['admin'] = true/false;
public class Priviledges
{
public CONST Admin = 0;
public CONST User = 1;
public CONST Contributor = 3;
//change this to however you want to do it :)
public static function isAdmin($val)
{
if ($val == Priviledges::Admin)
{
return true;
}
else
{
return false;
}
}
}
then when you set the admin session variable you can go;
$_SESSION['admin'] = Priviledges::Admin;
if(!$_SESSION['loggedin'])
{
header("location:login.php");
exit()
}
else if (!Priviledges::isAdmin($_SESSION['admin']))
{
header("location:errorpage.php");
exit()
}
else
{ //do your stuff if none of these conditions are met.. }
Always add an exit() or die() after sending a "Location" HTTP header:
<?php
session_start();
if($_SESSION['loggedin'] !== 'true') {
header("location:login.php");
exit();
}
if ($_SESSION['admin'] === 'N') {
header("location:errorpage.php");
exit();
}
Check: php - Should I call exit() after calling Location: header?.
From aaronsaray blog:
Remember, just because the browser is smart enough not to show the
content, doesn’t mean that this isn’t dangerous. So, it’s a little
less dangerous say if this page is just showing a user search option
or some information. It is much more dangerous if this is a page that
executes an action. This is because the entire PHP page will execute
if you don’t put a die() statement.
On other cases, if you want a condition to be evaluated only when a previous condition is false, you may use a "else if".

Album coding errors, simple PHP

I'm currently trying to develop the following function:
When someone wants to see their album or profile photos, I would like to use either album_id or id in the url, like this:
album.php?album_id=(numeric Number)
album.php?id=(numeric number)
I am currently able to execute the first command and when I attempt the second, it fails to load instead I'm taken to the index page (as per the script's design.)
Here is my code:
$album_id = addslashes(is_numeric($HTTP_GET_VARS["album_id"]));
$profile_id = addslashes(is_numeric($HTTP_GET_VARS["id"]));
?>
<?php
if($album_id==Null||!$profile_id==Null)
{
print("<script language='JavaScript'> window.location='index.php'; </script>");
}
else
{
if ($album_id==$album_id)
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/album_photos.php");
}
else
{
if ($profile_id==$profile_id)
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/profile_photos.php");
}
else
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/album_photos.php");
}
}
}
?>
And to clarify, those "pages" contain nothing but bold saying:
Show album photos and Show user photos
But what I can't seem to fathom as to what my problem might be.
If you call album.php?album_id={id}, $_GET['id'] is null, making your first if statement return to the index page.
if (($album_id == null) || ($profile_id == null)) { ... }
One will always be null unless you call album.php?album_id={aid}&id={pid}
if (($album_id == null) && ($profile_id == null)) {
# redirect to index.php
} else {
if ($album_id != null) {
# load album
} else if ($profile_id != null) {
# load profile
} else {
# both given, redirect to error.
}
}
Your condition if($album_id==$album_id) will always be true because they both are same and the else part is never executed.

Running _remap() once

When a user is logged in, I would like them to be able to visit http://website.com/user and be taken to http://website.com/1/johndoe, where 1 is their user ID, and johndoe is their user name.
I'm trying to use _remap() to catch all attempts at http://website.com/user/, so even incomplete URIs like http://website.com/user/1 or http://website.com/user/1/joh are redirected to http://website.com/user/1/johndoe.
Here's what I've tried:
class User extends CI_Controller {
function index($uID, $user) {
echo $uID;
echo $user;
}
function _remap() {
$uID = 3;
$user = 'johndoe';
//redirect('user/'.$uID.'/'.$user); // Updates URI, but redirect loop
//$this->index($uID, $user); Works, but doesn't update the URI
}
}
I could of course detect the method first, and do something like this:
function _remap($method = '') {
if ($method != 'view') {
$uID = 3;
$user = 'johndoe';
redirect('user/view/'.$uID.'/'.$user);
}
}
function view($uID, $user) {
echo $uID;
echo $user;
}
But then I think the URI would look like http://website.com/user/view/1/johndoe, and I'd rather view was excluded. How should I go about this problem?
If you have a _remap() method - it will always be called, so redirecting to user/anything will still call _remap() on the next request, so not only do you need to catch the router method and its parameters - you must do it if you want to use _remap() in a way that makes any sense:
public function _remap($method, $args)
{
if ($method === 'user' && (empty($args) OR ! ctype_digit($args[0])))
{
// determine and handle the user ID and name here
}
else
{
return call_user_func_array(array($this, $method), $args));
}
}
The solution I use is:
$route['user/(:num)/:any'] = 'user/view/$1';
$route['user/(:num)'] = 'user/view/$1';
Really, the username should only be for SEO purposes and in which case, should not be passed to the action. You will of course be able to access the username from the UserID when you look up the user anyway, so I feel it's redundant.
The above will match
/user/1/jdoe
/user/1
but will only pass 1 to your user/view action.
Edit: With your comment in mind:
$route['user/(:num)/(:any)'] = 'user/view/$1/$2';
$route['user/(:num)'] = 'user/view/$1';
function view($UserID, $UserName = null) {
// Load the model and get the user.
$this->model->load('user_model');
$User = $this->user_model->GetByUserID($UserID);
// If the user does not exist, 404!
if (empty($User)) {
show_404();
return;
}
// If the UserName does not exist, or is wrong,
// redirect to the correct page.
if($UserName === null || strtolower($User->UserName) != strtolower($UserName)) {
redirect("user/$UserID/{$User->UserName}");
return;
}
}
The above will accept the username as the parameter, however if it is not supplied or if it is not correct, it will redirect to the correct url and continue.
Hopefully this solves your problem?

$_SESSION never getting set

I'm working on an assignment on a PHP course, and I'm stucked at the last part of it.
The assignment is to create a simple login form and use a session as well as hardcoded usernames and passwords (i.e. no db).
What I have problems with is the class that handles the login, and sessions especially. There's a lot of code and I didn't know what I could remove and therefore I've put it on Pastebin instead, hope that's alright.
Thing is that the unit tests that's built into the class passes except for nr. 4, the one that's checking that the user is logged in. The problem seems to be that $_SESSION[$this->loginSession] doesn't get set, and this is what I need help with.
The variable $loginSession is declared in the beginning of the class, and should be set to "isLoggedIn" when a user types a correct username and password, but that doesn't happen (no error message).
My class is:
<?php
class LoginHandler {
private $loginSession;
public function IsLoggedIn() {
if($_SESSION[$this->loginSession] == "isLoggedIn") {
return true;
}
else {
return false;
}
}
public function DoLogin($username, $password){
if ($username != null && $password != null){
switch ($username){
case "hello";
if ($password == "1234"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
case "hello2";
if ($password == "12345"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
}
}
else {
return false;
}
}
public function DoLogout(){
unset($_SESSION[$this->loginSession]);
}
public function Test() {
$this->DoLogout();
// Test 1: Check so you're not logged in.
if($this->IsLoggedIn() == true){
echo "Test 1 failed";
return false;
}
// Test 2: Check so that it's not possible to login with wrong password.
if ($this->DoLogin("hello", "4321") == true){
echo "Test 2 failed";
return false;
}
// Test 3: Check that it's possible to log in.
if ($this->DoLogin("hello", "1234") == false){
echo "Test 3 failed";
return false;
}
// Test 4: Check that you're logged in
if ($this->IsLoggedIn() == false){
echo "Test 4 failed";
return false;
}
return true;
}
}
?>
I hope it's enough to include the class and not all the other files, otherwise I'll put them up.
Now I see it :-)
$_SESSION[$this->loginSession] == "isLoggedIn";
== should be =
== compares while = sets
You need to start the session. session_start(); Place it at the very top of the documents (only one time on a page load) you are using.
$this->loginSession is never set so it's NULL
$_SESSION[null] is not possible as far as i know
change your code to
private $loginSession = 'testing';
and it should work
Why do you put semicolon in your case instruction case "hello";There should be a colon. case "hello": { ...instructions}

Categories