使用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?

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 } ?>

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>

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.