I'm setting up a system where if a users group number is present the user will have access to the page. For example I want people in group 7,8, and 14 to have access to the page. This works fine for the users in group 7 and 8 but if the user is group 14 access appears to be denied. Here's what I tried so far I tried to go this two ways but to no avail. Any help would be appreciated.
An if statment with more than two conditions.
if ($_SESSION['userrole'] == 8 || $_SESSION['userrole']== 7 || $_SESSION['userrole']== 14) {
//text
}else{
echo "access denied";
An array that have values to check against
$acc = array("8","7","14");
if (in_array($_SESSION['userrole'],$acc)){
//text
}else{
echo "access denied";
as Syscall mentioned in his comment you are trying to look for the value "2,14"
in array contain values like this array("8","7","14");
this is want work
what you need to do in this case is use explode()
in your scenario, it will look like this
$acc = array("8", "7", "14");
$user_group = explode(',',$_SESSION['userrole']);
foreach ($user_group as $group) {
if (in_array($group, $acc)) {
//text
} else {
//text
}
}
Related
I'm creating a basic form to purchase adult & child tickets from. With the way the form is set up, the user must purchase an adult ticket, but they don't need to purchase a child ticket. I've added some error messages/validations to enforce rules within the form. All of the adult ticket error messages work correctly, but the child ones aren't working right.
I want the child ticket rules to check the following: that a valid number (aka not a letter) has been entered, the quantity is greater than 0, and a whole number has been entered. I thought I had the rules set so they only start validating if the child ticket input is not empty, but instead they're still trying to validate when it is empty, which I don't want it to do considering no child tickets need to be purchased. How do I get this to work correctly?
Here is my PHP code with the error messages.
<?php
$adult=$_POST['adult'];
$child=$_POST['child'];
$date=date('m/d/Y');
function isInteger($input) {
return(ctype_digit(strval($input)));
}
if (empty($adult)) {
$error_message='You must purchase at least 1 Adult ticket!';
}
else if (!is_numeric($adult)) {
$error_message="You must enter a valid number!";
}
else if ($adult <= 0) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!isInteger($adult)) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if (!empty(!is_numeric($child))) {
$error_message="You must enter a valid number!";
}
else if (!empty($child <= 0)) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!empty(!isInteger($child))) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if ($adult + $child > 5) {
$error_message="Sorry, there is a limit of 5 total tickets per customer!";
}
else {
$error_message='';
}
if($error_message !=""){
include('index.php');
exit();
}
?>
If $child = 1
if(!empty($child <= 0) ) is equivalent to if(!empty(false)) which makes no sense.
Same with (!empty(!is_numeric($child)))
Use if(isset($child) && $child <= 0) {} instead
You can also use $child = isset($_POST['child']) ? $_POST['child'] : 0
Not looking for an accepted answer, just wanted to suggest a more practical approach.
PHP has some very powerful built-in functions for validation. Two you can use are filter_var and filter_input, which can easily validate numeric values as integers, without needing to check each variation of an integer.
Additionally instead of chaining several elseif conditions, I suggest using throw to immediately raise an Exception that needs to be handled, otherwise halting execution at that point. Accompanied within a try/catch block to handle the exception as desired.
Example https://3v4l.org/PJfLv
$adult = filter_var($_POST['adult'] ?? null, FILTER_VALIDATE_INT);
$child = filter_var($_POST['child'] ?? null, FILTER_VALIDATE_INT);
try {
if (false === $adult || false === $child) {
throw new \InvalidArgumentException('You must enter a whole number (1, 2, etc...)');
}
if (0 >= $child || 0 >= $adult) {
throw new \InvalidArgumentException('You must enter a quantity greater than zero!');
}
// at this point child and adult must be >= 1
// ensure total is at least 1 and at most 5
$total_options = ['options' => ['min_range' => 1, 'max_range' => 5]];
$total = filter_var($adult + $child, FILTER_VALIDATE_INT, $total_options);
if (false === $total) {
throw new \InvalidArgumentException('Sorry, there is a limit of 5 total tickets per customer!');
}
// what should happen next...
} catch(\InvalidArgumentException $e) {
$error_message = $e->getMessage();
require __DIR__ . '/index.php';
## always use absolute paths to prevent include_path overrides/overhead
} finally {
// do something else no regardless of success or Exception...
}
For PHP < 7.0 replace
$_POST['child']) ?? null
with
isset($_POST['child']) ? $_POST['child'] : null
This question already has answers here:
The 3 different equals
(5 answers)
Closed 4 years ago.
I have a custom field in a WP post called "profession." If this profession is RN, then I want one piece of text displayed. If the profession is not RN, then I want another piece of text displayed.
I added the following code to execute this function:
<?php if ( $profession = 'RN' ) {
echo '<li>Minimum 2 years experience</li><li>Current license in this state</li><li>Graduated from accredited Nursing school</li><li>BCLS required</li><li>BSN and ACLS preferred</li><li>Other requirements to be determined by our client facility</li>';
} else {
echo '<li>Minimum 2 years experience</li><li>Other requirements to be determined by our client facility</li>';
} ?>
The problem is, the first echo statement is displaying even when the post does not have RN in the profession field. If I purposely break the if variable, then it defaults to the second echo statement across the board. I can't get the post to respond dynamically to one vs the other.
Am I missing something in this code that is causing one or the other to display for all instead of based on the parameter I am trying to set?
You need to compare in your if not assign.
= is used to assign values
== is used for comparison, checks if value is equal
=== is used for strict comparison, checks if value and type are equal.
So your php if statement should look like this
if ( $profession == 'RN' ){
code
}else{
code
}
Please read how to use condition before writing.
http://php.net/manual/en/control-structures.if.php
<?php if ( $profession == 'RN' ) {
echo '<li>Minimum 2 years experience</li><li>Current license in this state</li><li>Graduated from accredited Nursing school</li><li>BCLS required</li><li>BSN and ACLS preferred</li><li>Other requirements to be determined by our client facility</li>';
} else {
echo '<li>Minimum 2 years experience</li><li>Other requirements to be determined by our client facility</li>';
} ?>
<?php if ( $profession == 'RN' ) {
echo '<li>Minimum 2 years experience</li><li>Current license in this state</li><li>Graduated from accredited Nursing school</li><li>BCLS required</li> <li>BSN and ACLS preferred</li><li>Other requirements to be determined by our client facility</li>';
} else {
echo '<li>Minimum 2 years experience</li><li>Other requirements to be determined by our client facility</li>';
} ?>
I'm having a bit of a brain-fart here...lol
I was using a forloop() initially for this.. but then the conditions got a bit more advanced on things I needed to check for, as well as the output based on found/not found..
My problem is ensuring that on consecutive loops.. the 'else' on the (no access) potion only gets echo'd once... but of course on every 'loop' it will check from the top and if not a match output the 'no-access' text.. (on every iteration).. where it should only output once.
Originally there was only a few if() statement/checks in the foreach() loop.. where a simple break; took care of things fine...
but these if()'s turned into if/else.. which means the else will get 'triggered' on the next 'loop'.. how can this be prevented?
$arrwebinars = ("Name1", "Name3");
foreach($arrwebinars as $webinar) {
/* Webinar 1 */
if($webinar == 'Name1') {
if($web01_title != '') {
echo "available";
} else {
echo "not available";
}
} else {
echo "no access";
}
/* Webinar 2 */
if ($webinar == 'Name2') {
if ($web02_title != '') {
echo "available";
} else {
echo "not available";
}
} else {
echo "no access";
}
/* Webinar 3 */
if ($webinar == 'Name3') {
if($web03_title != '') {
echo "available";
} else {
echo "not available";
}
} else {
echo "no access";
}
}
is there some other sort of 'control' I can use to ensure the main if/else only gets executed once?
Sorry , I am having a hard time trying to describe this one, hopefully the code explains it all (and the problem)
thanks.
update:
Current State: reverted back to foreach() loop.
User is only authorized for 2 vids (#5 & #6 we'll say..can be any of the 6 in reality)
Upon first loop/iteration.. vids 1-4 output (no access for you!) (because they dont, only #5 & #6 as stated above)
no. 5 outputs the embed code fine (access)
no. 6 says 'No access for you'.. (even though they do/should have access)
Upon the scond iteration..vids 1-4 are duplicated, and again say "No access for you" (outside of it being a duplication..this is correct).. however, vid #5 NOW says "no access for you" (first loop it outputted fine, second loop it is looking for a new 'match' while not what I want.. in theory this is correct.. but should have a duplicate)
Vid #6 is NOW outputting the embed code (where as on first loop it did not)..
The user has only purchased access to 2 vids.. so the loop only happens twice.
but I get '12' echo's
No matter what I should only get 6 echo's with 1 out put per video (available/not available -or- no access)
I cant seem to wrap my head around this today.. :(
Goal I want achieve:
6 outputs TOTAL
each output (echo) should ONLY have:
available or not available printed (this is the nested conditional check for the blank title)
-or-
no access
there are 6 video to check against.
the user can have purchased access to 1 or up to all 6 vids
first check is: is the webinar name in their purchased array found in the total available 6 vids available
second tier conditional check:
if YES (match found == access)...then check to see if the title is missing (if there output access [video embed code]... if not there output text 'not available yet')
(going back to first conditional check) if there is NO ACCESS (match not found).. output 'no access' text.
This works if I wanted duplicates on the stage/page.. (but I dont!) LOL..
I need to be limited to ONLY 6 outputs,.. as there are only a total of 6 vids available.
I DO NOT WANT:
on loop 1 it outputs access for vid#1 and #2-#6 are no access..
on loop 2 it re-states all of these outputs, has vid#1 no-access now, vid#2 has access and vids #3-#6 are no access...
etc.etc.. and the cycle continues. I'm getting lost on this one!..
thanks!
If you wish to stop considering that "row" when you encounter a "no access" then you could simply continue; after each no-access. or do you wish to check the others even if you encounter "no access" on the first, just to fail silently in that case?
Not sure exactly what you're trying to achieve, but your code could be shortened greatly.
$webinars = array('one', 'two', 'Name3');
$web0_title = 'not empty'; // Just a demo
for ( $i = 0; $i < count($webinars); $i++ )
{
$access = FALSE;
$available = FALSE;
$name = 'Name' . $i;
$title = 'web' . $i . '_title';
if ( $webinars[$i] == $name ) {
if ( ! empty( $$title ) ) {
$available = TRUE;
}
$access = TRUE;
}
// Simple debug, not sure what you want to accomplish
echo 'Webinar: ' . $webinars[$i] . ' <br />';
echo 'Availability: ' . ( $available ? 'Available' : 'Not Available' ) . '<br />';
echo 'Access: ' . ( $access ? 'Access' : 'No Access' ) . '<br /><br />';
}
Edit: Just read your comments so I updated it.
Im trying to do a verify level function to use on top of my pages, to control access to each page depending on the level of administrator.
I did this function now for this purpose:
function verifyLevel($userId){
$pdo = start();
$read = $pdo->prepare("SELECT * FROM admins where id = :userId");
$read->bindValue(":userId", $userId);
$read->execute();
$result = $read->fetch(PDO::FETCH_ASSOC);
echo $result['level'];
}
And now Im trying to use this function.
Admins have level 1, 2 or 3.
In this page, I want to allow that users with level 1 and 3 can see the content.
Only admins with level 2 canĀ“t see content of this page and I want to show a message saying that they dont have permissions to admins with level 2.
Im trying like this:
if(function_exists('verifyLevel')){
if(verifyLevel($_SESSION['admin']['id'] == '2')){
echo 'Sorry, but you dont have permissions to acess this page.';
}
else{
//I show page content
}
}
But its not working, all levels are having acess to content of this page.
Do you see where is my error?
You're echoing the result from verifyLevel(), you need to return it for it to be comparable:
function verifyLevel($userId){
// ...
return $result['level'];
}
// bracket in wrong place -----------V--not--v
if(verifyLevel($_SESSION['admin']['id']) == '2') {
echo 'Sorry, but you dont have permissions to acess this page.';
}
As mentioned by Jeremy Miller, the way you had your function call set up, it would be passing in a boolean of either true or false, which is loosely equivalent to 0 or 1, so your user would probably not be returned correctly from the database either:
// incorrect comparison here, passing boolean instead (0 or 1)
var_dump(verifyLevel($_SESSION['admin']['id'] == '2'));
Should be:
// true representation of your function's processing and comparison
var_dump(verifyLevel($_SESSION['admin']['id']) == '2');
// verifyLevel($_SESSION['admin']['id']) will either be 1, 2 or 3
I'm having a small problem. In a class called reservation that has an attribute called reserve , which in the database is a tinyint(4), and an attribute kamp, which is int(10). I'm trying to do this:
if ($this->kamp == 387 || $this->kamp == 388 || $this->kamp == 389) {
$this->reserve = 0;
} else {
$this->reserve = 1;
}
Now my problem is, the code ALWAYS jumps straight to the else bracket. Even when I'm 100% sure $this->kamp is 387, 388 or 389.
Does this have anything to do with datatypes or am I missing something? I think the problem lies within this piece of code, since in my database there are objects showing up where reserve = 1 and the kamp is one of the three numbers I mentioned.
Thanks!
i think this will work for you.
$val = intval($this->kamp);
and then print or echo for result it will giving you value or not ?
let me know if i can help you more.