PHP logic "and" "&&" for WordPress site restriction - php

I have two different user roles on my Website: Employer and Candidate. Every one had a type of profile but the profile from Candidate should see only employers and nobody else.
So I want a restriction in Wordpress like:
Employer CAN see Candidate
Candidate CAN'T see other Candidate
Candidate CAN see own Profile
This is controlled by a plugin but it seems to be broken BECAUSE:
Employer CAN see Candidate
Candidate CAN see other Candidate
Candidate CAN'T see own Profile
In the .php file from candidate profile is this code:
<?php
if (!$show_candidate_public_profile) {
if ($candidate->get_public_account() || get_current_user_id() == $candidate->get_author_id()) {
$check = 1;
} else {
$check = 2;
}
} else {
if (is_user_logged_in()) {
if ($show_candidate_public_profile == 2 && get_current_user_id() == $candidate->get_author_id()) {
if ($user->is_employer() && $candidate->get_public_account()) {
$check = 3;
} else {
$check = 4;
}
} else {
if ($candidate->get_public_account() || get_current_user_id() == $candidate->get_author_id()) {
$check = 1;
} else {
$check = 2;
}
}
} else {
$check = 0;
}
}
and the code for results right after code from above:
if (!$check) {
?>
<div class="iwj-alert-box">
<div class="container">
<span>
<?php echo sprintf(__('You must be logged in to view this page. Login here', 'iwjob'), add_query_arg('redirect_to', $candidate->permalink(), $login_page_id)); ?>
</span>
</div>
</div>
<?php
} else {
if ($check == 2) {
?>
<div class="iwj-alert-box">
<div class="container">
<span>
<?php echo esc_html__('This profile is not public now.', 'iwjob'); ?>
</span>
</div>
</div>
<?php } elseif ($check == 4) {
?>
<div class="iwj-alert-box">
<div class="container">
<span>
<?php echo esc_html__('This profile is not public or only employers can see.', 'iwjob'); ?>
</span>
</div>
</div>
<?php } else {
?>
<div class="iw-parallax" data-iw-paraspeed="0.1" style="background-image: url('<?php echo esc_url($cover_image_url); ?>');"></div>
<div class="iw-parallax-overlay"></div>
<div class="content-top">
<div class="container">
<div class="info-top">
<div class="candidate-logo">
The check 3 is the only one check showing profile.
I tried to change the "&&" "||" "==" but i can't figure it out how this logic work.
So much php is too much for me. I have asked the Plugin creator but I am always waiting 5 days to reply and I need it now.
I would be very happy if someone would help me with this.
Thank you very much!
Martin

This code should work according to the behavior you have described(of course it will depend on the good functionality of your plugin). I had to take off some conditions since I don't know what they are and also you didn't provide further details, if you need them you have to add later, but this is quite simple and this code is much more readable.
First portion:
<?php
if(!is_user_logged_in())
$check=false; //if user is not logged in check is false
else
{
//check if user is employer or if is the profile owner
if ($user->is_employer() || get_current_user_id() == $candidate->get_author_id())
$check = 1; //sets 1 if allowed
else
$check = 2; //sets 2 if denied
}
?>
Second portion:
if (!$check) //is check false? then show login message
{
?>
<div class="iwj-alert-box">
<div class="container">
<span>
<?php echo sprintf(__('You must be logged in to view this page. Login here', 'iwjob'), add_query_arg('redirect_to', $candidate->permalink(), $login_page_id)); ?>
</span>
</div>
</div>
<?php
}
else //check it's not false, so do more tests
{
if ($check == 2) //if equals 2 then shows access denied message
{
?>
<div class="iwj-alert-box">
<div class="container">
<span>
<?php echo esc_html__('This profile is not public now or only employers can see.', 'iwjob'); ?>
</span>
</div>
</div>
<?php
}
elseif($check == 1) //user is profile owner or is an employer, show everything
{
?>
<div class="iw-parallax" data-iw-paraspeed="0.1" style="background-image: url('<?php echo esc_url($cover_image_url); ?>');"></div>
<div class="iw-parallax-overlay"></div>
<div class="content-top">
<div class="container">
<div class="info-top">
<div class="candidate-logo">
If you want more tests, like about profile being public or not, you really have to provide more information. I hope it can help you.

Related

How to prevent duplicate results in For Each loop?

I am using a foreach loop to look at custom taxonomies associated with my custom post type. The issue I am having is that I am getting multiple buttons to display for posts that have more than one tax term selected.
What I would like to have happen is the loop search for one or more of the "age/grades" and then display a single button with the correct text and link. However, I am getting one button for each grade selected for the program (e.g. a Grade 3-6 program has four buttons: one for each applicable grade).
Any idea on how to prevent the duplicates?
Here is my current code:
<?php
$agegroup = wp_get_post_terms(get_the_ID(), 'camper_grade');
if ($agegroup) {
foreach ($agegroup as $group) {
if ($group->slug == 'age-2' || 'age-3' || 'age-4') { ?>
<a href="/preschool">
<div class="blue-btn">
More Preschool Camps
</div>
</a> <?php ;
}
elseif ($group->slug == '1st-grade' || '2nd-grade' || '3rd-grade' || '4th-grade' || '5th-
grade' || '6th-grade') { ?>
<a href="/grades-k-6">
<div class="blue-btn">
More Grade K-6 Camps
</div>
</a> <?php ;
}
elseif ($group->slug == '7th-grade' || '8th-grade' || '9th-grade' || '10th-grade' || '11th-
grade' || '12th-grade' ) { ?>
<a href="/teen">
<div class="blue-btn">
More Teen Adventures
</div>
</a> <?php ;
}
}
}
?>
Use separate foreach loops and break when it's found.
Your || is also not working how you want it to. You should use in_array which correctly compares the same value to many others:
<?php
$agegroup = wp_get_post_terms(get_the_ID(), 'camper_grade');
if ($agegroup) {
foreach ($agegroup as $group) {
if (in_array($group->slug, ['age-2', 'age-3', 'age-4'])) { ?>
<a href="/preschool">
<div class="blue-btn">
More Preschool Camps
</div>
</a> <?php ;
break;
}
}
foreach ($agegroup as $group) {
if (in_array($group->slug, ['1st-grade', '2nd-grade', '3rd-grade', '4th-grade', '5th-grade', '6th-grade'])) { ?>
<a href="/grades-k-6">
<div class="blue-btn">
More Grade K-6 Camps
</div>
</a> <?php ;
break;
}
}
foreach ($agegroup as $group) {
if (in_array($group->slug, ['7th-grade', '8th-grade', '9th-grade', '10th-grade', '11th-grade', '12th-grade'])) { ?>
<a href="/teen">
<div class="blue-btn">
More Teen Adventures
</div>
</a> <?php ;
break;
}
}
}
?>
You need to add a flag to indicate whether the button has been displayed already for that group, and only output the button if it hasn't. Note that your logical conditions are incorrect, you need to compare the slug with each value individually (or better yet, use in_array). For example:
if ($agegroup) {
$preschool = $grades_k_6 = $teen = false;
foreach ($agegroup as $group) {
if (in_array($group->slug, array('age-2', 'age-3', 'age-4')) && !$preschool) { ?>
<a href="/preschool">
<div class="blue-btn">
More Preschool Camps
</div>
</a> <?php ;
$preschool = true;
}
elseif (in_array($group->slug, array('1st-grade', '2nd-grade', '3rd-grade', '4th-grade', '5th-grade', '6th-grade')) && !$grades_k_6) { ?>
<a href="/grades-k-6">
<div class="blue-btn">
More Grade K-6 Camps
</div>
</a> <?php ;
$grades_k_6 = true;
}
elseif (in_array($group->slug, array('7th-grade', '8th-grade', '9th-grade', '10th-grade', '11th-grade', '12th-grade')) && !$teen) { ?>
<a href="/teen">
<div class="blue-btn">
More Teen Adventures
</div>
</a> <?php ;
$teen = true;
}
}
}

How to change <div> property of certain content panel in a php webpage?

<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="row text-center">
<?php
if($_GET[id] == 0)
{
$querysb = mysql_query("SELECT * FROM services WHERE parentid !=0 order by parentid, cid ");
}
else
{
$querysb = mysql_query("SELECT * FROM services WHERE parentid='".$_GET[id]."'");
}
while($rowsb = mysql_fetch_assoc($querysb))
{
if($val == '6' || $val =='10'){
$classname = 'whitebg';
} else {
$classname = 'bg-blue co-white';
}
?>
<div class="col-md-4 mrgnBtm15">
<div class="<?php echo $classname;?> padding30" style="min-height: 250px">
<h3 class="service-heading">
<?php echo $rowsb['cname'];?>
</h3>
<h4>
RS <?php echo $rowsb['price'];?><br>
</h4>
<div class="mrgnTop15 clearfix"></div>
<a class="btn bg-orange co-white" href="<?php echo MYWEBSITE;?>servicedetail/<?php echo to_prety_url($rowsb['cname']).'-'.$rowsb['cid'];?>.html">
<font style="size:14px; color:#000; font-weight:bolder;font-family: "Open Sans";">Register</font></a>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
I am working on a dynamic website. here is the code of a particular page. In this page there is a div section with class="col md-4". If the number of content panel in that division appears to 5 or 7 in that case I want only the last panel (i.e 5th and 7th) to be in full column (col-12). What should I do?
Since you are using col-md-4, 3 divs will be shown each row. So I think what you are looking for is a way to make the last div full width if its going to be alone in its row. In that case, you will need to make it col-md-12 on 4th (not 5th) and 7th and 10th records and so on. This is exactly what the following code does,
I think what you want to do is show the
<?php
if($_GET[id] == 0)
{
$querysb=mysql_query("SELECT * FROM services WHERE parentid !=0 order by parentid, cid ");
}
else
{
$querysb=mysql_query("SELECT * FROM services WHERE parentid='".$_GET[id]."'");
}
$number_of_records = mysql_num_rows($querysb);
$counter = 1;
while($rowsb=mysql_fetch_assoc($querysb))
{
if($val == '6' || $val =='10'){
$classname= 'whitebg';
}else{
$classname= 'bg-blue co-white';
}
//if($number_of_records %3 ==1 && $counter == $number_of_records)
if(($number_of_records == 5 || $number_of_records == 7) && $counter == $number_of_records)
$col_class = "col-md-12";
else
$col_class = "col-md-4";
?>
<div class="<?php echo $col_class;?> mrgnBtm15">
<div class="<?php echo $classname;?> padding30" style="min-height: 250px">
<h3 class="service-heading">
<?php echo $rowsb['cname'];?>
</h3>
<h4>
RS <?php echo $rowsb['price'];?><br>
</h4>
<div class="mrgnTop15 clearfix"></div>
<a class="btn bg-orange co-white" href="<?php echo MYWEBSITE;?>servicedetail/<?php echo to_prety_url($rowsb['cname']).'-'.$rowsb['cid'];?>.html">
<font style="size:14px; color:#000; font-weight:bolder;font-family: "Open Sans";">Register</font></a>
</div>
</div>
<?php
$counter++;
} ?>
</div>
</div>
</div>

What is wrong with my if statement?

I had the below code which worked fine until I added an if statement to restrict the loop to only run on certain items in the array. I am now only getting a blank page which suggests there is an error somewhere in my code since adding the if statement, but I can't figure out where.
I'd really appreciate any help on solving this, as well as suggestions on how I could have solved myself (I'm still new to PHP and not sure how to effectively debug this type of issue).
Nb. There is an opening <?php tag not shown in the below snippet.
foreach ($portfolioProjects as $portfolio) {
if ($portfolio['featureContent'] == "Yes") {
?>
<div class="row featurette">
<?php
//for each odd number, change the layout so it looks nice :)
if ($loopCount % 2 == 0) {
echo '<div class="col-md-7">';
} else {
echo '<div class="col-md-7 col-md-push-5">';
}
?>
<h2 class="featurette-heading"><?php echo $portfolio[title]; ?> <span class="text-muted"><?php echo $portfolio[languages]; ?></span>
<?php
//Check array for newTag which will be added to show a tag to the user
if ($portfolio[newTag] == "Yes") {
echo '<span class="label label-success test pull-right"> New!</span>';
}
?></h2>
<p class="lead"><?php echo $portfolio[blurb]; ?></p>
</div><!--end of column1-->
<?php
if ($loopCount % 2 == 0) {
echo '<div class="col-md-5">';
} else {
echo '<div class="col-md-5 col-md-pull-7">';
}
?>
<img class="featurette-image img-responsive center-block" data-src="holder.js/200x200/auto" alt="200x200" src="assetts/200x200.gif" data-holder-rendered="true">
</div>
</div>
<?php
//if statement to stop divider being added if last item in array
$loopCount = $loopCount + 1;
if ($loopCount != $itemsCount) {
echo '<hr class="featurette-divider">';
}
}
}
?>
The easiest way to find out what the problem is, to check your webserver's log file, or turn on error_reporting and display_errors in your php.ini file.
Are newTag and blurb constants or keys in the $portfolio array? If they are keys, you should use apostrophes.
if ($portfolio['newTag'] == "Yes") {
and
<p class="lead"><?php echo $portfolio['blurb']; ?></p>
You forgot to wrap array keys in quotes
`$portfolio['title']
$portfolio['languages']
$portfolio['newTag']
$portfolio['blurb']`

PHP Script Loading Forever

This is not a duplicate of Maximum execution time in phpMyadmin; this has nothing to do with phpmyadmin.
On my site, there is a form which sends POST data to a PHP script and loads a new page. When you submit the form, the page loads forever and then results in:
The XXX.XXX page isn’t working XXX.XXX is currently unable to handle
this request. HTTP ERROR 500
I thought it may be a traffic issue so I upgraded my hosting SSD and made the website only available to me to test it, but the problem still persisted. Here is my script:
<?php
$used_file = 'used.txt';
$codes_file = 'codes.txt';
# Generates a random unused code from the code file
function genCode() {
global $used_file, $codes_file;
$codes = file_get_contents($codes_file);
$codes = explode("\n", $codes);
$used = file_get_contents($used_file);
$used = explode("\n", $used);
foreach($codes as $code) {
if(!in_array($code, $used))
return $code;
}
}
# Generate error string from error code
function getError($err) {
switch($err) {
case 1: return 'No submit';
case 2: return 'Wrong password';
case 3: return 'No password';
}
}
# Adds generated code to the 'used' codes file
function append_used($code) {
global $used_file, $codes_file;
$str = $code . '\n';
file_put_contents($used_file, $str, FILE_APPEND);
}
# Get user's IP (for cookie handling)
function getIP() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
# Cookie handling
# Set a cookie for how many times the form has been submitted by user
$used = 0;
if(isset($_COOKIE['used_twice'])) {
$used = 3;
}
if(isset($_COOKIE['used_once']) && !isset($_COOKIE['used_twice'])) {
setcookie('used_twice', getIP(), time()+18000);
$used = 2;
}
if(!isset($_COOKIE['used_once'])) {
setcookie('used_once', getIP());
$used = 1;
}
# Check if all the POST data is correct
$password = $_POST['inputPassword'];
$submit = $_POST['submit'];
if(isset($password)) {
if($password == 'test123') {
if(isset($submit)) {
$code = genCode();
}
else
$err = 1;
} else
$err = 2;
} else
$err = 3;
# Now generate the new page
include 'web_functions.php';
getHead('Generated', 'Generated code');
getBody('Generated code');
?>
<img src="goback.png"></img>
<h2>Code Generated</h2>
<br/>
<?php
if(!isset($err) && isset($thecode) && $used == 1) {
?>
<center>
<div class="bs-component">
<div class="alert alert-dismissible alert-success">
<p>Your code is: </p> <strong> <?php echo $thecode; append_used($thecode); ?> </strong>
</div>
</div>
</div>
</center>
<?php
} elseif(isset($err)) {
?>
<center>
<div class="bs-component">
<div class="alert alert-dismissible alert-danger">
<p>There was an error:</p> <strong><?php echo getError($err); ?></strong>
</div>
</div>
</div>
</center>
<?php
} elseif(!isset($err) && $used != 1){
?>
<center>
<div class="bs-component">
<div class="alert alert-dismissable alert-danger">
<p>You can only use the code generator once every 5 hours. Please try again later.</p>
</div>
</div>
</div>
</center>
<?php } else { ?>
<div class="bs-component">
<div class="alert alert-dismissable alert-danger">
<p>There was an unexpected error. Please try again.</p>
</div>
</div>
</div>
<?php } ?>
<br/>
<br/>
<br/>
<?php closeTags();
getFooter(); ?>
</div>
</div>
</div>
</div>
What could be causing this issue?
Edit: The error log says:
PHP Fatal error: Maximum execution time of 60 seconds exceeded on line 13
Line 13 is within the foreach loop.

May i know what is wrong with my phpcode?

This is what i have for headers.php anyway it is suppose to be my navigation bar. Here's the problem, when I login with a user as Member the whole header does not come out. But when I login with admin the navigations will "magically" come out!
<?php
if(!isset($_SESSION['sRole'])){
?>
<div id="header">
<div id="fb-root"></div>
<div id ="inthebox">
<b>LOGIN</b>|
<b>REGISTER</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
ABOUT|
</div>
</div>
<?php
}
else{
if($_SESSION['sRole'] == "member"){
?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
PROFILE
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}else{
if($_SESSION['sRole']=="admin"){
?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
Manage Account|
Manage Books|
Manage Orders|
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}
}
}
?>
This is my doLogin.php page , maybe it might help anyone here to solve this. I store the id, username, firstname and last name into the session. Inside have alr . The website hor when I go in is no error one . no html code error or whatsoever. Just that it does not appear. However the words below the nav links will still come out.
<?php
//connect to database
include ('dbfunction.php');
if (!isset($_POST['Login'])) {
if (isset($_POST['username'])) {
//retrieve form data
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='" . $username . "'AND password = '" . $password . "'";
$result = mysql_query($query) or die('The error :' . mysql_error());
$num_rows =mysql_num_rows($result);
if($num_rows == 0){
header('Location:login.php');
exit();
}
//if record is found, store id and username into session
else{
$row = mysql_fetch_array($result);
$_SESSION['sUsername'] = $row['username'];
$_SESSION['sRole'] = $row['role'];
$_SESSION['sFirst_name'] = $row['first_name'];
$_SESSION['sLast_name'] = $row['last_name'];
header('location:successful_login.php');//redirect to this page
exit();
}
}
else {
}
} else {
header('Location:successful_login.php');
exit();
}
mysql_close();
?>
I think the problem here is you are using } else { conditions, but then nesting an if statement inside of them. In fact it looks like you had some broken closing braces. Here is the revised code:
<?php if(!isset($_SESSION['sRole'])){ ?>
<div id="header">
<div id="fb-root"></div>
<div id ="inthebox">
<b>LOGIN</b>|
<b>REGISTER</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
ABOUT|
</div>
</div>
<?php } else if($_SESSION['sRole'] == "member") { ?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
PROFILE
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php }else if($_SESSION['sRole']=="admin"){ ?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
Manage Account|
Manage Books|
Manage Orders|
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}
try this:
<?php if( (!isset($_SESSION['sRole'])) || (empty($_SESSION['sRole'])) || (is_null($_SESSION['sRole'])) ): ?>
<html>your code</html>
<?php else: ?>
<?php switch($_SESSION['sRole']) {
case 'admin': { // admin code } break;
case 'member': { // member code } break;
default: { // something happened } break;
}
?>
<?php endif; ?>
check and diagnose the issue

Categories