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;
}
Related
What I want is to check if the columns $campo01 and $campo02 are empty or not, if not empty it displays on my page, the problem is that if a variable is empty it does not display the result of the variable that is not empty
class Test extends URLDynamic
{
public function Testando( $campo01, $campo02, $linguagem, $audio )
{
$CRUD = new CRUD;
$this->SetParametro();
$VerificaAudio = $this->SelectDados(
"campo01, campo02",
"table_01",
"WHERE mCat = ? AND mSlug = ? AND mStatus = ?",
array ( $this->SepURL[0], $this->SepURL[1], 1 )
);
foreach ( $VerificaAudio as $VerificouAudio ) {
$campo01 = $VerificouAudio['campo01'];
$campo02 = $VerificouAudio['campo02'];
if ( empty ( $campo01 ) ) {
echo 'Empty Campo 01';
} elseif ( empty ( $campo02 ) ) {
echo 'Empty Campo 02';
} else {
// Returns the value of each column.
echo $linguagem;
$Temporadas = $this->SelectDados(
"*",
"table_02",
"WHERE mCat = ? AND mSlug = ? AND tAudio = ? AND tStatus = ?",
array ( $this->SepURL[0], $this->SepURL[1], $audio, 1 )
);
} // end else
} // end foreach
}
}
$Test = new Test;
$Test->Testando( "Legendado", "Legendado" ); // campo01
$Test->Testando( "Dublado", "Dublado" ); // campo02
class Test
{
public $Teste01;
public $Teste02;
public function Testando($Param01, $Param02)
{
$this->Teste01 = '';
$this->Teste02 = 'Has value';
echo $this->checkIfEmpty($this->$Param01);
echo $this->checkIfEmpty($this->$Param02);
}
private function checkIfEmpty($var)
{
if (empty($var)) {
return 'Empty';
} else {
return $var;
}
}
}
I'm trying to save my data using php. This is how I tried:
<?php
session_start();
if(!isset($_SESSION["MemberID"])) header("Location:logout.php");
include '../config.php';
include '../momdb.php';
$page_title = "Customers";
$mode = "Save";
$db = 'db';
$showmessage = false;
$message = "";
if (isset ( $_POST ["btnSave"] )) {
$data = new table ();
$data->MomID = $_POST ["CustomerID"];
$data->CustomerName = $_POST ["CustomerName"];
$data->FromDate = string_to_date ( $_POST ["FromDate"] );
$data->ToDate = string_to_date ( $_POST ["ToDate"] );
$data->CreatedBy = $_SESSION["MemberID"];
$data->CreatedDatetime = date ( "Y-m-d H:i:s" );
$data->LastModifiedBy = $_SESSION["MemberID"];;
$data->LastModifiedDatetime = date ( "Y-m-d H:i:s" );
$rows = array ();
if (intval ( $data->CustomerID) > 0) {
$rows = $db::Update ( $data );
} else {
$rows = $db::Save ( $data );
}
if (intval ( $rows ["WebID"] ) > 0) {
$date = new DateTime ();
header ( "Location: customerlist.php?msg=yes&msgt=s&t=" . $date->getTimestamp () . "&mtext=Record saved successfully" );
} else {
$showmessage = true;
$message = $rows ["Message"];
}
} elseif (isset ( $_GET ["CustomerID"] )) {
$data = $db::GetByID ( $_GET ["CustomerID"] );
if ($data == false) {
$data = new table ();
$data->CustomerID = 0;
}
}
if ($data->CustomerID == "0")
$mode = "Save";
else
$mode = "Update";
?>
This code is for sending my values to the db page for saving them in the DB. I've used the PDO method. This is the first time I'm saving the record this way. That's why there is lots of confusion. The following code shows the Save() method, which I used to save the values to the DB.
public function Save(table $customer) {
$data = new DB ();
$stmt = $data->connection->prepare ( "CALL proc_CreateCustomer (:CustomerName, :FromDate,:ToDate,:CreatedBy, :CreatedDatetime, :LastModifiedBy, :LastModifiedDatetime)" );
$stmt->bindParam ( ':CustomerName', trim ($customer->CustomerName ));
$stmt->bindParam ( ':FromDate', $customer->FromDate );
$stmt->bindParam ( ':ToDate', $customer->ToDate);
$stmt->bindParam ( ':CreatedBy',$customer->CreatedBy );
$stmt->bindParam ( ':CreatedDatetime', $customer->CreatedDatetime );
$stmt->bindParam ( ':LastModifiedBy',$customer->LastModifiedBy );
$stmt->bindParam ( ':LastModifiedDatetime', $customer->LastModifiedDatetime );
$stmt->execute ();
$record = $stmt->fetch ( PDO::FETCH_OBJ );
if ($record == false) {
return array (
"WebID" => 0,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
} else {
return array (
"WebID" => $record->CustomerID,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
}
}
This is how I've tried. But, whenever I try to save the details, it shows: " Trying to get property of non-object in D:\Workspace\Application\momdb.php on line 39", ie it shows error in the line "Message" => $record->Message,"AppID" => $customer->AndroidID. I don't what's wrong with this. Can someone tell me what should I change so that it work fine?
if ($record == false) {
return array (
"WebID" => 0,
"Message" => $record->Message,
"AppID" => $customer->AndroidID
);
}
In this piece of code $record is false(y), so $record->Message doesn't exist.
I'm wondering if there is another way to refactor my conditionals if/else statements. I feel I'm repeating the same thing over and over,
Here is a snippet (Keep in mind is wayyyy longer than that, but it follows the same principle) I could do a switch statement but it does not reduce the total code quantity.
I just want to get a second opinion of the best approach for this code to go into production. Also important to mention that the statements that I'm comparing $screen->id; are most likely to be dynamically generated if the user selects the checkbox, but that is outside of the scope of the question.
//check admin screen
$screen = get_current_screen();
if ( $screen->id === 'topic') {
$in['content_css'] = get_template_directory_uri() . "/build/styles/tiny-mce-editor.css";
$in['block_formats'] = $topics_blocks;
return $in;
}
elseif ( $screen->id === 'provider-jobs') {
$in['content_css'] = get_template_directory_uri() . "/build/styles/tiny-mce-editor.css";
$in['block_formats'] = $providers_blocks;
return $in;
}
//for all the page options
else {
$in['block_formats'] = $global_blocks;
return $in;
}
}
Thanks! Any guidance is appreciated.
UPDATE! Here is the refactored code, a little bit more cleaner! And complete so the whole context shows.
//check admin screen
$screen = get_current_screen();
//global ones
$in['block_formats'] = $global_blocks;
$in['toolbar1'] = $global_toolbar;
if ( $screen->id === 'topic') {
$in['block_formats'] = $topics_blocks;
$in['toolbar1'] = $topics_toolbar;
} elseif ( $screen->id === 'forum') {
$in['block_formats'] = $forums_blocks;
$in['toolbar1'] = $forums_toolbar;
} elseif ( $screen->id === 'post') {
$in['block_formats'] = $blogs_blocks;
$in['toolbar1'] = $blogs_toolbar;
} elseif ( $screen->id === 'jobs') {
$in['block_formats'] = $jobs_blocks;
$in['toolbar1'] = $jobs_toolbar;
}
elseif ( $screen->id === 'provider-jobs') {
$in['block_formats'] = $providers_blocks;
$in['toolbar1'] = $providers_toolbar;
}
return $in;
You might register key/value pairs all known options/blocks. So your code becomes straight reduced, like this:
$options = [
'topic' => $topics_blocks,
'provider_jobs' => $providers_blocks,
// ...
];
//check admin screen
$screen = get_current_screen();
if (array_key_exists($screen->id, $options) {
$in['content_css'] = get_template_directory_uri() . "/build/styles/tiny-mce-editor.css";
$in['block_formats'] = $options[$screen->id];
} else {
$in['block_formats'] = $global_blocks;
}
return $in;
Edit, applies to the 2nd version of the OP
Here the problem appears a bit different, so here is another solution:
$options = [
'topic' => 'topics',
'forum' => 'forums',
'post' => 'blogs',
'jobs' => 'jobs',
'provider_jobs' => 'providers',
];
//check admin screen
$screen = get_current_screen();
//global ones
$in['block_formats'] = $global_blocks;
$in['toolbar1'] = $global_toolbar;
// variable ones
if (array_key_exists($screen->id, $options) {
$in['block_formats'] = ${$options[$screen->id] . '_blocks'};
$in['toolbar1'] = $options[$screen->id] . '_toolbar'};
}
return $in;
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';
}
}
Can someone help why my JSON file can't show? I beginner for JSON. This is my code, its only show blank document. I am learning this tutorial from this website http://contohprogramandroid.blogspot.com/2013/10/contoh-program-android-aplikasi-wisata.html. thank you so much.
this my image when running the code.
//this is the code webservice.php
<?php
class Database {
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "wisata_jogja";
private $conn;
// constructor
function __construct() {
try{
$this->conn = new PDO( "mysql:host=".$this->host.";dbname=".$this->db, $this->user, $this->pass );
}catch( PDOException $e ) {
echo "error pdo $e";
}
}
public function showAllData( $table ) {
$sql ="SELECT * FROM $table";
$q = $this->conn->query( $sql ) or die( "Failed !!" );
while ( $r = $q->fetch( PDO::FETCH_ASSOC ) ) {
$data[] = $r;
}
return $data;
}
}
$database = new Database();
$response = array();
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
$response['location'] = array();
foreach ( $database->showAllData( 'lokasi' ) as $value ) {
$kode = array();
extract( $value );
$kode['id'] = $id;
$kode['nama'] = $nama;
$kode['alamat'] = $alamat;
$kode['gambar'] = $gambar;
$kode['lat'] = $lat;
$kode['lng'] = $lng;
array_push( $response['location'], $kode );
}
echo json_encode( $response );
}
?>
Your condition to output is this:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
Thus, the script won't output any JSON since condition is not met.
From your screenshot it is clear your are missing the GET parameters.
In your browser add the parameter to the url:
http://localhost/wisata/webservice.php?get=lokasi
It's always good to take alternative action when condition is not true.
You should always echo something just so you know what is going on:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
//..............
echo json_encode( $response );
}else{
echo "cannot output JSON data: parameter is missing!!;
}
Are you sure that you pass the GET variable "lokasi" to your script ?
Otherwise, it would not go through the if condition
if(isset($_GET['get'] ) && $_GET['get']=='lokasi')
You can check this by trying to dump the variable or any foobar data inside the if condition to verify your code goes that far, for instance :
if(isset($_GET['get'] ) && $_GET['get']=='lokasi') {
$response['location'] = array();
$myTest = array('test');
var_dump($myTest); // Should display something on screen
// The rest of your code here