on my website I want to show a Logout button when a user is logged in and a logout button when the user is not logged in.
I wrote this code:
if(isset($_SESSION["username"])){ echo "<li class='xy'><button class='x' onclick='location.href = 'index.php';'>Logout</button></li>"; } else { my login button... }
The buttons do appear but unfortunately the are not clickable.
How can I solve this problem?
You are not properly escaping quotations
Replace:
onclick='location.href = 'index.php';'
with:
onclick='location.href = \'index.php\';'
You need to escape the single quotes as they are mixing up with each other.
Corrected Code:
<?php
if (isset($_SESSION["username"])){
echo "<li class='xy'><button class='x' onclick='location.href = \'index.php\';'>Logout</button></li>";
}
else {
//my login button...
}
Another solution can be not to write HTML in PHP. PHP and HTML can be embedded into each other without any restriction. You are embedding HTML into PHP. Embed PHP in HTML:
<?php
if (isset($_SESSION["username"])){
?>
<li class='xy'><button class='x' onclick="location.href = 'index.php'">Logout</button></li>
<?php
}
else {
//my login button...
}
If you just want to send the user to an URL target ( index.php
in your example) use a link, instead of re-inventing a link and simulating it using JS. Style the link to look like a button. (There are plenty CSS examples on the web on how to do that.)
<?php
if( isset( $_SESSION["username"] ) ) {
echo '<li class="xy"><a class="button x" href="index.php">Logout</a></li>';
}
else {
// my login button...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.