简体   繁体   中英

Redirecting to next page with onclick()

<?php
session_start();
?>
<a href="hola.php" onclick="return check();">Take me</a>
<script type="text/javascript">
function check() {
   <?php 
  if(isset($_SESSION['user'])
    return true;
  else
    return false;
  ?>
}
</script>

A user will be able to redirect to next page only if he is logged in, otherwise he is prevented to the same page. I've checked for solutions but don't find what I am looking for. Is php script valid inside javascript script?

You may use php code within your js like so:

<?php
session_start();
?>
<a href="hola.php" onclick="return check();">Take me</a>
<script type="text/javascript">
function check()
{
var user = '<?php echo $_SESSION['user']; ?>';
if(user)
return true;
else
return false;
}
</script>

I think what you are trying to do is:

function check(){
    <?php  if(isset($_SESSION['user'])){ ?>
        return true;
    <?php } ?>
    return false;
}

But without a JS function you can to this:

<?php if(isset($_SESSION['user'])){ ?>
    <a href="hola.php" >Take me</a>
<?php }else { ?>
    <a href="#" >Take me</a>
<?php } ?>

The correct & safe version would be to verify the status of the user directly in hola.php and redirect back / to a login page if the user is not logged in.

The problem with blocking navigation via javascript or directly hiding the link from php ( like suggested in a previous answer ) is that it does not guarantee that users (or bots/crawlers) won't access the hola.php directly, without clicking your link.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM