WordPress is_user_logged_in failing with HTML Scripting - javascript

Could someone please review why this below added code won't execute correctly? I've escaped the PHP scripting to display the HTML content in WordPress, but I can't get this thing to work!
The results are that, whether the user is logged in or not, the HTML content displays for everything. Strangely, though, I can't get the else { ... } part to render in HTML. I'm not too good with PHP, so please mind if I done something incorrectly.
I've tried debugging via NetBeans, but the IDE failed to detect anything on a fail-safe conditioning.
<?php
if ( is_user_logged_in() ) {
?>
<h2>Welcome to the Portal!</h2>
<p>Here you can manage all information with an authorised account. You can click on the button below to create a new entry.</p>
<button type="button" href="#" onClick="document.location = 'http://www.example.com'">Add Entry</button>
<?php
} else {
echo "<h1>Unauthorised!</h1>";
echo "<javascript>document.location = \'http://example.com\'";
exit;
};
?>

Alright, so I got the coding going. It turned out that, by default, WordPress didn't allow PHP execution in my pages. I installed a plugin named "insert PHP", modified the code to mix html and php and it worked!
[insert_php]
if (is_user_logged_in()){
echo "<h2>Welcome to the Portal!</h2>";
echo "<p>Here you can manage all entries with an authorised account. You can click on the button below to create an entry.</p>";
echo '<button type="button" onClick="document.location = \'http://somesite.com\'">Add Listing</button>';
} else {
echo '<h2>Unauthorized 401</h2>';
echo '<script>document.location = \'http://domain.tld'</script>';
};
[/insert_php]

Related

Submit form and then after the form is processed open a new page

I'am trying to delete an entry/offer from the database and then get back to all the entries/offer overview page. I tried to do it with Javascript but unfortunately it does not open the overview page. It does the deleting but then stays on the page.
Is that the correct way anyways with javascript?
Here the two links Overview and delete Offer
<a id="overview" href="/mbm-kalkulation">Overview</a>
<form method="post" action="/?id='.$_REQUEST["id"].'" name="delOffer"><button type="submit">delete Offer</button>
Here the javascript which should click the overview page after the form got submitted.
((isset($_REQUEST["delOffer"]))?'
setTimeout(function(){
jQuery("a#overview").click();
}, 1000);
':'')
Normally such redirects are done using the header function from php. This is only possible, when the headers weren't already send. In this case you will have to use a JavaScript fallback. The code could look something like this:
if (isset($_REQUEST["delOffer"])) {
if (!headers_sent()) {
header("Content-Type: text/plain");
header("Location: {$url}");
} else {
print "<script>window.location = '" . addslashes($url) . "';</script>";
}
exit;
}

Is it possible to change HTML within PHP code?

What is the easiest way to run Javascript code inside PHP, preferably without using external libraries? Specifically, I need the innerHTML of a div to change depending on some calculations performed using the user's form inputs that were captured earlier with $_POST in a separate form. How can I get the following JS code to run inside the following PHP code? (My most basic attempt was using echo command, but it's throwing up errors)
HTML:
<div id="output">
</div><!--#output -->
PHP (desired JS included):
if (count($valid_locations)<$num_of_locations){
echo '<script>const output = document.querySelector("#output");</script>;';
echo '<script>output.innerHTML = "<div class="alert-danger"> Trip unable to be created. Please adjust the budget/number of travelers/duration etc.</div>;";</script>';
}else{
createTrip($trips);
}
Right now, the IF condition is True and the code does run, but it echos ";" for some reason. I have verified that the condition is met and it runs by adding in a simple echo "this runs";, which did appear upon refresh. I just don't understand why it's outputting to the default echo space and the script isnt running to change the innerHTML of the output div. Is this even possible to do with PHP? If so, what's the best way? (doesn't need to be secure, won't be used publicly). I've heard of a few things such as ajax but it seems so complicated. Any explanations on stuff like that specific to this scenario would be greatly appreciated.
Following up on the comments, you don't need JS to achieve what you want. You could just use PHP
<?php
$output = null;
if (!empty($_POST)) {
//...
//... do stuff
//...
if (count($valid_locations)<$num_of_locations){
$output = 'Error occured - bla bla bla';
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if (isset($output)) {?>
<div id="output"><?= $output; ?></div>
<?php } ?>
</body>
</html>

Redirect certain urls based on location

I have a number of links to Amazon UK on my (Joomla 3.4) website - these are links to buy books. They are basically 'Buy Now' buttons that take the user to the relevant Amazon UK item page (e.g www.amazon.co.uk/myBook) - html code below
<a class="btn btn-primary" href="http://www.amazon.co.uk/myBook...">Buy</a>
What I would like to do is re-direct US visitors to www.amazon.com
<a class="btn btn-primary" href="http://www.amazon.com/myBook...">Buy</a>
I know I could just add another button ('Buy US') but I only want one button per page.
I though I could perhaps either modify the .htaccess file, or add some javascript code so that vititors from the us will be taken to .com and not .co.uk?
I was looking at the geoPlugin and IP2Location - can either or these be used to achieve this?
Perhaps I could modify the IP2Location code (below) somehow?
<?php
require_once 'IP2Location.php';
$loc = new IP2Location('databases/IP-COUNTRY.BIN', IP2Location::FILE_IO);
$record = $loc->lookup($_SERVER['REMOTE_ADDR'], IP2Location::ALL);
if($record == 'US') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://amazon.com');
exit;
}
?>
Not sure how I can user server side includes to achievce this?
Any help or direction is appreciated, I'm keen to learn by myself.
You can edit /index.php in Joomla to as below:
$output = ob_get_clean();
require_once JPATH_LIBRARIES . '/IP2Location.php';
$db = new \IP2Location\Database('./databases/IP-COUNTRY-SAMPLE.BIN');
$records = $db->lookup($_SERVER['REMOTE_ADDR']);
if($records['countryCode'] == 'US'){
echo str_replace('www.amazon.co.uk', 'www.amazon.com', $output);
}
else{
echo $output;
}

Why yii captcha always shows a fixed picture?

Captcha works with no problem, but I have no idea why it's not generating a new code to dislay? I've looked into the documents but could find something that could solve my problem.
Is there something here that I'm missing. thanks.
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
my view file:
<?php echo $form->labelEx($model,'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
<?php echo $form->error($model,'verifyCode'); ?>
This is a known bug, that would most likely be fixed in Yii2.
On the Yii forums, user Black suggests:
My solution was to remove the session key on my controller action on get. Be careful not to remove it in any other place because it will probably fail on server validation.
$session = Yii::app()->session;
$prefixLen = strlen(CCaptchaAction::SESSION_VAR_PREFIX);
foreach($session->keys as $key)
{
if(strncmp(CCaptchaAction::SESSION_VAR_PREFIX, $key, $prefixLen) == 0)
$session->remove($key);
}
Another way to workaround would be to use JavaScript to click on the refresh link on every page load as mentioned by Soph:
$(function() {
$('#yw0_button').click();
});

How would I call a java script function using php if statement with $_SESSION

Hi I am creating a website with a login section this is working I am using HTML and PHP. What I am trying to do is one of my pages has a html button I want this to be disabled for certain users. at the moment this is what I have got.
this is the part that I use for the login details.
<?php
session_start();
$_SESSION["username"];
$_SESSION["password"];
$_SESSION["access"];
?>
I have got if statments that I am currently using which are
if($_SESSION["access"] == "Administrator"){
echo $Admin;
}
what I am trying to do is call a javascript function within a PHP if statement what i have got so far is
<?php
if($_SESSION["access"] == "Consumer")
{
echo '<script type="text/javascript">
Disable();
</script>';
}
if($_SESSION["access"] == "Administrator")
{
echo '<script type="text/javascript">
Enable();
</script>';
}
?>
the javascript functions that i am trying to call are
<script type="text/javascript">
function Enable() {
SubmitButton.disabled = false;
}
function Disable() {
SubmitButton.disabled = true;
}
</script>
I have also tryed
if($_SESSION["access"] == "Consumer")
{
echo "<script> Disable(); </script>";
}
Im just wondering if I have typed something in wrong or if I have forgotten to put something in.
any help would be much appreciated.
Looking at your code you have couple of issues:
Mixing your PHP logic and pure HTML is (usually) not a good idea.
Instead I would suggest you move your access checking logic fully on the server side and display the button accordingly (disabled or enabled) based on the user's access.
Example:
<?php if($_SESSION['access']): // Only show the button for users with access ?>
<button type="submit" value="Submit" <?php echo ($_SESSION['access'] != 'Administrator' ? 'disabled' : ''); // Button disabled for everyone but administrators ?> />
<?php endif; ?>
And let me point out the obvious (as mentioned by the other answers), that's not 100% bulletproof. The user can still manually submit the button even if he is not an administrator by editing the page's HTML on the fly. That's just a UI fix. The real check should be done on the server side once the button is submitted (e.g. is the user logged in, does he have a cookie on his computer that identifies him as an administrator, does he have a session cookie set, etc).
Calling JS in random places, e.g. in the header can have unexpected consequences.
You better wait for the page to be loaded fully before calling any JS functions. You can do that via jQuery easily, but make sure you include the jQuery library before that in your header like so.
Afterwards you can call any JS after the page is loaded by placing them within the following block:
$(function(){
// Place your JS calls here, e.g. call to Enable()
});
String concatenation in PHP is done with a dot . and strings can be multiline
This code which you used is just plain wrong.
echo '<script type="text/javascript">'
, 'Enable();'
, '</script>';
You should use something like:
echo '<script type="text/javascript">'
.'Enable();'
. '</script>';
or better:
echo '<script type="text/javascript">
Enable();
</script>';
PHP doesn't use , sign for joining. Use ..
But otherwise it should work, except that you should define SubmitButton in advance of using it.
<?php
echo "<script type='text/javascript'>";
// if the id of your element is "submitButton"
echo "var submitButton = document.getElementById('submitButton');";
echo " function disable(){ submitButton.disabled=true; }";
echo "</script>";
?>
After that you can use it as you did..
<script type='text/javascript'>
disable();
</script>
Just be advised that denying access to some elements/functionality on your webpage with JavaScript alone is not a good practice - JavaScript is executed locally on the user's computer and therefore the user can modify it to gain an advantage.
Well, the problem may be that you're trying to call the javascript function before the HTML is ready (or finally rendered), so the browser, when executes the function doesn't find the button.
You could solve this placing your javascript code at the end of your page, or using jQuery and doing:
$(document).ready(function() {
<%php if ($_SESSION['access'] == 'xxxxx') {%>
Enable();
<%php } else { %>
Disable();
<%php } %>
});
Anyway, ALWAYS check user permissions on the server side, because someone could enable the button using Firebug or something else...

Categories

Resources