Ben
Ben

Reputation: 25817

(PHP - Session) How can user restrict to access direcly to controller.php , only allow access from view.php?

I am a beginner in PHP.

How can I restrict user access to controller.php and allow access to it only via view.php?


My proposal:

I don't know if this is proper, or how to avoid robots accessing it directly.


view.php:

  <?php
    session_start();
    $_SESSION['isFromView'] = true;
    ?>

  <html>
   <body>
    <form action="controller.php">
    <input type="submit"/>
    </form>
   </body>
  </html>

controller.php

<?php
   session_start();
   if(!isset($_SESSION['isFromView'])||!$_SESSION['isFromView']){exit();}
   else{

   //code here

   $_SESSION['isFromView']=false;
   }
?>

Please write what do I miss and in which way my controller can be access directly or other security problem (if you can examples please).


Edit:

In case that I dont have user login it can be secured by killing the session it controller.php after code executed, then when the user return to view.php new session ID will be created.

In most cases, though, we cannot kill the session because of other components of the site.

Thanks

Upvotes: 1

Views: 1506

Answers (2)

symcbean
symcbean

Reputation: 48367

First thing of note is that it appears your usage of 'Controller' and 'view' seems to be radically different from mine - I would have interpreted this as being part of an MVC pattern - in which case the browser would never request 'view.php' it should be an include file invoked via include/require from the controller file. Also, as an include file, it should not contain any inline code - so even if it were directly accessible from a browser - it would not do anything when called from a browser.

If you simply mean that you have two scripts, and the second should only ever be called by the first, then the issue is one of Cross-site request forgery - there's lots and lots of discussions about how to avoid this on the internet, most of which will explain why using $_SERVER['HTTP_REFERER'] is a complete waste of time.

Passing transaction-related data via the session should be avoided at all costs - not least because of the problem of session aliasing.

C.

Upvotes: 1

Narcis Radu
Narcis Radu

Reputation: 2547

The solution proposed is fine. Alternative solutions:

  1. use some hash in some hidden field in view.php form (in view.php create some md5('secret') and then check that in controller.php). This solution is the most secure approach.
  2. check the referral url (I strongly disagree because it's security issues) - $_SERVER['HTTP_REFERER']. This variable can easily be spoofed (changed by the client) so it's a security risk to rely on it.

Upvotes: 1

Related Questions