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

Azima
  • 3,835
  • 15
  • 49
  • 95
  • No its not. You should make only php header("Location: #url"); or only javascript location.href – g9m29 Sep 02 '16 at 14:09
  • I'm not that familiar with PHP, but can't the user just simply _go to the URL_ you specified without clicking the button? You should implement a check on the redirected page for a session, not in this part of your code. – roberrrt-s Sep 02 '16 at 14:10
  • Is easier you check if the user is logged and show the link only when the user can click – cmnardi Sep 02 '16 at 14:10
  • You could do something like `function check() { return ; }`. But this would be very easy to bypass using developer tools so don't rely on this to enforce security. – Phylogenesis Sep 02 '16 at 14:10
  • Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Qirel Sep 02 '16 at 14:11

3 Answers3

0

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>
pavlos
  • 3,001
  • 18
  • 23
  • I hoped.. but it didn't work.. it still redirects to the page ignoring the return value from the function – Azima Sep 02 '16 at 14:20
0

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 } ?>
cmnardi
  • 1,051
  • 1
  • 13
  • 27
0

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.

Community
  • 1
  • 1
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19