If Statement with Empty _Get - php

I am busy learning PHP. However doing a small website with PHP where I control the Variables passed, I am stuck at a If statement issue.
Every internal page link I have passes a variable to control the content I pull from a database. even links from other internal pages to my Index.php page. The thing is the index.php page gives errors because there is a empty _Get issue when you enter the saite from external link. There are four pages. all other pages work with no errors but loading index page gives error.
My code:
$Section = $_GET['SID'];
if ( $Section == "HOME" ) {
$SectionTitle = 'Start';
$SectionID = 'HOME';
}
if ( $Section == "BDIR" ) {
$SectionTitle = 'Directory';
$SectionID = 'BDIR';
}
if ( $Section == "ACOM" ) {
$SectionTitle = 'Accommodation';
$SectionID = 'ACOM';
}
if ( $Section == "REST" ) {
$SectionTitle = 'Restaurants';
$SectionID = 'REST';
}
What I need to achieve is when there is an empty _Get its must assign the same value as the Home (First If) Values.
I have tried
if (!empty($_GET)) {
$SectionTitle = 'Start';
$SectionID = 'HOME';
}
and a few other variations with no luck.
But I think I am out of my league, as I wonder, should some if my statements not be within(under) other if statements here?

$Section = !isset($_GET['SID']) || empty($_GET['SID']) ? 'HOME' : $_GET['SID'];
switch($Section) {
case "BDIR":
$SectionTitle = 'Directory';
$SectionID = 'BDIR';
break;
case "ACOM"
$SectionTitle = 'Accommodation';
$SectionID = 'ACOM';
break;
case "REST":
$SectionTitle = 'Restaurants';
$SectionID = 'REST';
break;
case "HOME":
default:
$SectionTitle = 'Start';
$SectionID = 'HOME';
break;
}

In order not to write many similar if-statements i'd rather add an array and check it by key presence.
Then define default SectionTitle and SectionID like this:
<?php
$SectionTitle = 'Start';
$SectionID = 'HOME';
$sections = [
'BDIR' => 'Directory',
'ACOM' => 'Accommodation',
'REST' => 'Restaurants'
];
if (!empty($_GET['SID']) && array_key_exists($_GET['SID'], $sections)) {
$SectionTitle = $sections[$_GET['SID']];
$SectionID = $_GET['SID'];
}

May be this will help you. try this code.
if($_GET)
{
$Section = $_GET['SID'];
if ( $Section == "HOME" ) {
$SectionTitle = 'Start';
$SectionID = 'HOME';
}
if ( $Section == "BDIR" ) {
$SectionTitle = 'Directory';
$SectionID = 'BDIR';
}
if ( $Section == "ACOM" ) {
$SectionTitle = 'Accommodation';
$SectionID = 'ACOM';
}
if ( $Section == "REST" ) {
$SectionTitle = 'Restaurants';
$SectionID = 'REST';
}
}

Related

Problem of Curly Brackets in my controller Php Symfony

I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.

Magento code need precision

I'm currently checking a Magento extension and I have a slight doubt about a piece of code. I would like you to explain. I understand all of it but not this one :
$customerID == " "
Is there a case where Magento have a customer id like that ( a space?) ?
Thanks a lot for your reply !
Here the entire function.
public function isAvailable(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$method = $event->getMethodInstance(); //$method return the payment method
$result = $event->getResult(); //$result return true if method is active
$quote = $event->getQuote(); //$quote return var from cart
if($method->getCode() == 'custompayment' ){
//$customerGroup = $quote->getCustomerGroupId();
// $customerGroup="";
// $customerID="";
$login = Mage::getSingleton( 'customer/session' )->isLoggedIn(); //Check if User is Logged In
if($login)
{
$customerGroup = Mage::getSingleton('customer/session')->getCustomerGroupId(); //Get Customers Group ID
$customerID = Mage::getSingleton('customer/session')->getCustomerId(); //Get Customers ID
}
$selectedCustomerGroups = Mage::getStoreConfig('payment/custompayment/specificcustomers');
$selectedCustomerGroupsArray = explode(",", $selectedCustomerGroups);
if($selectedCustomerGroups != "" || $customerID == " "){
if(!in_array($customerGroup, $selectedCustomerGroupsArray)) {
$result->isAvailable = false;
}
}
else{
if($result->isAvailable==1){
$result->isAvailable = true;
}
}
}
Answered by adrien54 and JokiRuiz.

Codeigniter prevent repeat data

I have a controller with 2 functions:
images
videos
I have created a header and footer template to load with my views and I want to set the css stylesheet to the user preferred setting "light" or "dark". So for example the user sets their theme to be dark I want to update the header view with dark.css, but I am currently repeating my code and I want to prevent that. I am having to do this twice. Once for images:
public function images()
{
//is the user logged in? if not redirect to login page
if ( ! $this->my_auth->logged_in())
{
redirect('auth/login', 'refresh');
}
//set the view data
$data['title'] = 'Upload Images | My Idea Cloud';
$data['heading'] = 'Upload Images';
$data['attributes'] = array(
'class' => 'dropzone',
'id' => 'image-dropzone'
);
// get users style and set the correct style sheet
$user_data = $this->my_auth->user()->row();
if ($user_data->style == 'light')
{
$data['flat_css'] = 'flat-ui-light.css';
$data['navbar_class'] = 'navbar-default';
$data['footer_class'] = 'bottom-menu-default';
$data['custom_css'] = 'custom-light.css';
$data['dropzone_css'] = 'dropzone-light.css';
}
elseif ($user_data->style == 'dark')
{
$data['flat_css'] = 'flat-ui-dark.css';
$data['navbar_class'] = 'navbar-inverse';
$data['footer_class'] = 'bottom-menu-inverse';
$data['custom_css'] = 'custom-dark.css';
$data['dropzone_css'] = 'dropzone-dark.css';
}
else
{
$data['flat_css'] = 'flat-ui-dark.css';
$data['navbar_class'] = 'navbar-inverse';
$data['footer_class'] = 'bottom-menu-inverse';
$data['custom_css'] = 'custom-dark.css';
$data['dropzone_css'] = 'dropzone-dark.css';
}
//load the views
$this->load->view('templates/frontend/front_header', $data);
$this->load->view('templates/frontend/front_navbar');
$this->load->view('frontend/upload_images', $data);
$this->load->view('templates/frontend/front_footer', $data);
And once for the videos function
public function videos()
{
if ( ! $this->my_auth->logged_in())
{
redirect('auth/login', 'refresh');
}
$data['title'] = 'Upload Videos| My Idea Cloud';
$data['heading'] = 'Upload Videos';
$data['attributes'] = array(
'class' => 'dropzone',
'id' => 'video-dropzone'
);
// get users style and set the correct style sheet
$user_data = $this->my_auth->user()->row();
if ($user_data->style == 'light')
{
$data['flat_css'] = 'flat-ui-light.css';
$data['navbar_class'] = 'navbar-default';
$data['footer_class'] = 'bottom-menu-default';
$data['custom_css'] = 'custom-light.css';
$data['dropzone_css'] = 'dropzone-light.css';
}
elseif ($user_data->style == 'dark')
{
$data['flat_css'] = 'flat-ui-dark.css';
$data['navbar_class'] = 'navbar-inverse';
$data['footer_class'] = 'bottom-menu-inverse';
$data['custom_css'] = 'custom-dark.css';
$data['dropzone_css'] = 'dropzone-dark.css';
}
else
{
$data['flat_css'] = 'flat-ui-dark.css';
$data['navbar_class'] = 'navbar-inverse';
$data['footer_class'] = 'bottom-menu-inverse';
$data['custom_css'] = 'custom-dark.css';
$data['dropzone_css'] = 'dropzone-dark.css';
}
$this->load->view('templates/frontend/front_header', $data);
$this->load->view('templates/frontend/front_navbar');
$this->load->view('frontend/upload_videos', $data);
$this->load->view('templates/frontend/front_footer', $data);
There is more code so that is why I do not combine the two. I am only showing partial code.
Can someone guide me in the right direction on how I can consolidate my code?
There is no use of elseif block in your code, also if you pull out common data to be passed via data, this is one attempt of minimization i can think of.
To apply this, remove if, elseif and else blocks from your code and put,
if($user_data->style == 'light')
{
$intensity = 'light';
$default = 'default';
}
else
{
$intensity = 'dark';
$default = 'inverse';
}
$data['flat_css'] = "flat-ui-{$intensity}.css";
$data['navbar_class'] = "navbar-{$default}";
$data['footer_class'] = "bottom-menu-{$default}";
$data['custom_css'] = "custom-{$intensity}.css";
$data['dropzone_css'] = "dropzone-{$intensity}.css";
If you want to make it more universal, create a function in same controller as,
function apply(&$data,$style)
{
if($style == 'light')
{
$intensity = 'light';
$default = 'default';
}
else
{
$intensity = 'dark';
$default = 'inverse';
}
$data['flat_css'] = "flat-ui-{$intensity}.css";
$data['navbar_class'] = "navbar-{$default}";
$data['footer_class'] = "bottom-menu-{$default}";
$data['custom_css'] = "custom-{$intensity}.css";
$data['dropzone_css'] = "dropzone-{$intensity}.css";
}
and replace the first code block shown in my answer with, one single line
$this->apply($data,$user_data->style);
and you will get those five variables defined in $data

Pulling articles from specific category through Joomla! 3.0 Module

Here is the scenario, and let me start off saying any help would be a god-send, I have cloned the Article Category module inside Joomla! Basically changed all the articles_category to breed_articles (for my purpose). This worked fine, where I am stuck at is where in the module code can I define a specific category to pull articles from.
I know I can do this in the backend but I am working on a dynamic way to pull articles by categories and need to define the category in the module code. That being said, I will also need to pull the categoies by the slug not id.
Where I have been looking is the helper.php file in the module and I believe that I am on the right path there. I have tried replacing a few things and tracing the code but I am not very familiar with Joomla!
helper.php
$com_path = JPATH_SITE.'/components/com_content/';
require_once $com_path.'router.php';
require_once $com_path.'helpers/route.php';
JModelLegacy::addIncludePath($com_path . '/models', 'ContentModel');
abstract class modBreedArticlesHelper
{
public static function getList(&$params)
{
// Get an instance of the generic articles model
$articles = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$articles->setState('params', $appParams);
// Set the filters based on the module params
$articles->setState('list.start', 0);
$articles->setState('list.limit', (int) $params->get('count', 0));
$articles->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$articles->setState('filter.access', $access);
// Prep for Normal or Dynamic Modes
$mode = $params->get('mode', 'normal');
switch ($mode)
{
case 'dynamic':
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content') {
switch($view)
{
case 'category':
$catids = array($app->input->getInt('id'));
break;
case 'categories':
$catids = array($app->input->getInt('id'));
break;
case 'article':
if ($params->get('show_on_article_page', 1)) {
$article_id = $app->input->getInt('id');
$catid = $app->input->getInt('catid');
if (!$catid) {
// Get an instance of the generic article model
$article = JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request' => true));
$article->setState('params', $appParams);
$article->setState('filter.published', 1);
$article->setState('article.id', (int) $article_id);
$item = $article->getItem();
$catids = array($item->catid);
}
else {
$catids = array($catid);
}
}
else {
// Return right away if show_on_article_page option is off
return;
}
break;
case 'featured':
default:
// Return right away if not on the category or article views
return;
}
}
else {
// Return right away if not on a com_content page
return;
}
break;
case 'normal':
default:
$catids = $params->get('catid');
$articles->setState('filter.category_id.include', (bool) $params->get('category_filtering_type', 1));
break;
}
// Category filter
if ($catids) {
if ($params->get('show_child_category_articles', 0) && (int) $params->get('levels', 0) > 0) {
// Get an instance of the generic categories model
$categories = JModelLegacy::getInstance('Categories', 'ContentModel', array('ignore_request' => true));
$categories->setState('params', $appParams);
$levels = $params->get('levels', 1) ? $params->get('levels', 1) : 9999;
$categories->setState('filter.get_children', $levels);
$categories->setState('filter.published', 1);
$categories->setState('filter.access', $access);
$additional_catids = array();
foreach($catids as $catid)
{
$categories->setState('filter.parentId', $catid);
$recursive = true;
$items = $categories->getItems($recursive);
if ($items)
{
foreach($items as $category)
{
$condition = (($category->level - $categories->getParent()->level) <= $levels);
if ($condition) {
$additional_catids[] = $category->id;
}
}
}
}
$catids = array_unique(array_merge($catids, $additional_catids));
}
$articles->setState('filter.category_id', $catids);
}
// Ordering
$articles->setState('list.ordering', $params->get('article_ordering', 'a.ordering'));
$articles->setState('list.direction', $params->get('article_ordering_direction', 'ASC'));
// New Parameters
$articles->setState('filter.featured', $params->get('show_front', 'show'));
$articles->setState('filter.author_id', $params->get('created_by', ""));
$articles->setState('filter.author_id.include', $params->get('author_filtering_type', 1));
$articles->setState('filter.author_alias', $params->get('created_by_alias', ""));
$articles->setState('filter.author_alias.include', $params->get('author_alias_filtering_type', 1));
$excluded_articles = $params->get('excluded_articles', '');
if ($excluded_articles) {
$excluded_articles = explode("\r\n", $excluded_articles);
$articles->setState('filter.article_id', $excluded_articles);
$articles->setState('filter.article_id.include', false); // Exclude
}
$date_filtering = $params->get('date_filtering', 'off');
if ($date_filtering !== 'off') {
$articles->setState('filter.date_filtering', $date_filtering);
$articles->setState('filter.date_field', $params->get('date_field', 'a.created'));
$articles->setState('filter.start_date_range', $params->get('start_date_range', '1000-01-01 00:00:00'));
$articles->setState('filter.end_date_range', $params->get('end_date_range', '9999-12-31 23:59:59'));
$articles->setState('filter.relative_date', $params->get('relative_date', 30));
}
// Filter by language
$articles->setState('filter.language', $app->getLanguageFilter());
$items = $articles->getItems();
// Display options
$show_date = $params->get('show_date', 0);
$show_date_field = $params->get('show_date_field', 'created');
$show_date_format = $params->get('show_date_format', 'Y-m-d H:i:s');
$show_category = $params->get('show_category', 0);
$show_hits = $params->get('show_hits', 0);
$show_author = $params->get('show_author', 0);
$show_introtext = $params->get('show_introtext', 0);
$introtext_limit = $params->get('introtext_limit', 100);
// Find current Article ID if on an article page
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content' && $view === 'article') {
$active_article_id = $app->input->getInt('id');
}
else {
$active_article_id = 0;
}
// Prepare data for display using display options
foreach ($items as &$item)
{
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid ? $item->catid .':'.$item->category_alias : $item->catid;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$menuitems = $menu->getItems('link', 'index.php?option=com_users&view=login');
if (isset($menuitems[0]))
{
$Itemid = $menuitems[0]->id;
}
elseif ($app->input->getInt('Itemid') > 0)
{
// Use Itemid from requesting page only if there is no existing menu
$Itemid = $app->input->getInt('Itemid');
}
$item->link = JRoute::_('index.php?option=com_users&view=login&Itemid='.$Itemid);
}
// Used for styling the active article
$item->active = $item->id == $active_article_id ? 'active' : '';
$item->displayDate = '';
if ($show_date) {
$item->displayDate = JHTML::_('date', $item->$show_date_field, $show_date_format);
}
if ($item->catid) {
$item->displayCategoryLink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid));
$item->displayCategoryTitle = $show_category ? ''.$item->category_title.'' : '';
}
else {
$item->displayCategoryTitle = $show_category ? $item->category_title : '';
}
$item->displayHits = $show_hits ? $item->hits : '';
$item->displayAuthorName = $show_author ? $item->author : '';
if ($show_introtext) {
$item->introtext = JHtml::_('content.prepare', $item->introtext, '', 'mod_articles_category.content');
$item->introtext = self::_cleanIntrotext($item->introtext);
}
$item->displayIntrotext = $show_introtext ? self::truncate($item->introtext, $introtext_limit) : '';
$item->displayReadmore = $item->alternative_readmore;
}
return $items;
}
public static function _cleanIntrotext($introtext)
{
$introtext = str_replace('<p>', ' ', $introtext);
$introtext = str_replace('</p>', ' ', $introtext);
$introtext = strip_tags($introtext, '<a><em><strong>');
$introtext = trim($introtext);
return $introtext;
}
/**
* Method to truncate introtext
*
* The goal is to get the proper length plain text string with as much of
* the html intact as possible with all tags properly closed.
*
* #param string $html The content of the introtext to be truncated
* #param integer $maxLength The maximum number of charactes to render
*
* #return string The truncated string
*/
public static function truncate($html, $maxLength = 0)
{
$baseLength = strlen($html);
$diffLength = 0;
// First get the plain text string. This is the rendered text we want to end up with.
$ptString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = false);
for ($maxLength; $maxLength < $baseLength;)
{
// Now get the string if we allow html.
$htmlString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = true);
// Now get the plain text from the html string.
$htmlStringToPtString = JHtml::_('string.truncate', $htmlString, $maxLength, $noSplit = true, $allowHtml = false);
// If the new plain text string matches the original plain text string we are done.
if ($ptString == $htmlStringToPtString)
{
return $htmlString;
}
// Get the number of html tag characters in the first $maxlength characters
$diffLength = strlen($ptString) - strlen($htmlStringToPtString);
// Set new $maxlength that adjusts for the html tags
$maxLength += $diffLength;
if ($baseLength <= $maxLength || $diffLength <= 0)
{
return $htmlString;
}
}
return $html;
}
public static function groupBy($list, $fieldName, $article_grouping_direction, $fieldNameToKeep = null)
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
if (!isset($grouped[$item->$fieldName])) {
$grouped[$item->$fieldName] = array();
}
if (is_null($fieldNameToKeep)) {
$grouped[$item->$fieldName][$key] = $item;
}
else {
$grouped[$item->$fieldName][$key] = $item->$fieldNameToKeep;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
return $grouped;
}
public static function groupByDate($list, $type = 'year', $article_grouping_direction, $month_year_format = 'F Y')
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
switch($type)
{
case 'month_year':
$month_year = JString::substr($item->created, 0, 7);
if (!isset($grouped[$month_year])) {
$grouped[$month_year] = array();
}
$grouped[$month_year][$key] = $item;
break;
case 'year':
default:
$year = JString::substr($item->created, 0, 4);
if (!isset($grouped[$year])) {
$grouped[$year] = array();
}
$grouped[$year][$key] = $item;
break;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
if ($type === 'month_year') {
foreach($grouped as $group => $items)
{
$date = new JDate($group);
$formatted_group = $date->format($month_year_format);
$grouped[$formatted_group] = $items;
unset($grouped[$group]);
}
}
return $grouped;
}
}
It looks like my issue was really specific to the project I am working on. If anyone happens to find this or wants to accomplish something similar, read on.
Decided to accomplish what I was doing using a JDatabase query. To retrieve the articles using the category alias, I queried the DB to match the alias I was giving the query to the category ID. Then joined the content table to get the article information.
All the information you need to make a proper JDatabase query can be found here: http://docs.joomla.org/Accessing_the_database_using_JDatabase

PHP Regex String in Array

I would like to be able to set a global username like <anythinghere>#domain3.com as a username value in the $usernames array (in code below). This is so that I can then go and redirect users based on domain, having already been "authenticated".
I will put example in code below.
Can i do something like $usernames = array("username#domain1.com", $X) where $X = <anything-so-long-as-not-blank>#domain3.com?
Full Code Below:
<?php
//VALIDATE USERS
$usernames = array("username#domain1.com", "username2#domain1.com", "username3#domain1.com", "username1#domain2.com", "username2#domain2.com", "username1#domain3.com");
$passwords = array("password1", "password2", "password3", "password4", "password5", "password6");
//REDIRECT SPECIFIC VALID USERS OR DOMAIN
function get_page($username) {
$username = strtolower($username);
switch ($username) {
case "username#domain1.com" : return "http://www.google.com";
case "username2#domain1.com" : return "http://www.yahoo.com";
case "username3#domain1.com" : return "http://www.stackoverflow.com";
case "username1#domain2.com" : return "http://www.serverfault.com";
}
return preg_match('/#domain3\.com$/',$username) ?
"http://www.backblaze.com" : "DefaultBackupPage.php";
}
$page = get_page($_POST['username']);
for($i=0;$i<count($usernames);$i++)
{
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++)
{
if ($usernames[$i] == $_POST["username"])
{
$found = 1;
}
}
if ($found == 0)
{
header('Location: login.php?login_error=1');
exit;
}
if($logindata[$_POST["username"]]==$_POST["password"])
{
session_start();
$_SESSION["username"]=$_POST["username"];
header('Location: '.$page);
exit;
}
else
{
header('Location: login.php?login_error=1');
exit;
}
?>
#inhan Has already helped me like a champ. I am wondering if any one can get me over the line? Cheers!
Your code needed a clean-up first. There's a bunch of errors in it if you do a test run. It's also a bit hard to read IMO.
I've attached a working code sample below.
// Get users
$input_pwd = ( isset( $_POST["password"] ) ? $_POST["password"] : '' );
$input_user = ( isset( $_POST["username"] ) ? $_POST["username"] : '' );
// Your pseudo database here ;)
$usernames = array(
"username#domain1.com",
"username2#domain1.com",
"username3#domain1.com",
"username1#domain2.com",
"/[a-z][A-Z][0-9]#domain2\.com/", // use an emtpy password string for each of these
"/[^#]+#domain3\.com/" // entries if they don't need to authenticate
);
$passwords = array( "password1", "password2", "password3", "password4", "", "" );
// Create an array of username literals or patterns and corresponding redirection targets
$targets = array(
"username#domain1.com" => "http://www.google.com",
"username2#domain1.com" => "http://www.yahoo.com",
"username3#domain1.com" => "http://www.stackoverflow.com",
"username1#domain2.com" => "http://www.serverfault.com",
"/[a-z][A-Z][0-9]#domain2\.com/" => "http://target-for-aA1-usertypes.com",
"/[^#]+#domain3\.com/" => "http://target-for-all-domain3-users.com",
"/.+/" => "http://default-target-if-all-else-fails.com",
);
$logindata = array_combine( $usernames, $passwords );
if ( get_user_data( $input_user, $logindata ) === $input_pwd ) {
session_start();
$_SESSION["username"] = $input_user;
header('Location: ' . get_user_data( $input_user, $targets ) );
exit;
} else {
// Supplied username is invalid, or the corresponding password doesn't match
header('Location: login.php?login_error=1');
exit;
}
function get_user_data ( $user, array $data ) {
$retrieved = null;
foreach ( $data as $user_pattern => $value ) {
if (
( $user_pattern[0] == '/' and preg_match( $user_pattern, $user ) )
or ( $user_pattern[0] != '/' and $user_pattern === $user)
) {
$retrieved = $value;
break;
}
}
return $retrieved;
}

Categories