security - How to secure php scripts? -


if have ajax call php script, (using jquery)

$.ajax(url: "../myscript.php"); 

and myscript looks this:

<?php     //code db  ?> 

i want know how prevent user going example.com/myscript.php execute script.

some answers here give overview of concepts behind question, let me give more pragmatic approach (you should @ least read , understand others matter though!).

you need ask yourself: do app must enforce requests myscript.php should controlled?

if so need use sort of token: create token , send client (browser), browser must send token , check if matches before doing action:

<?php // somefile.php (this file serves page contains ajax call) session_start(); //... $_session['token'] = createnewtoken(); // creates unique tokens  //add token js variable , send in ajax call // you'll have similar this: <script>   var token = <?php echo $_session['token'] ?>;   $.ajax({     url: "myscript.php",     data: form_data, // include token here!     //...   }) 

and in script:

<?php // myscript.php session_start();  // can check if it's ajax call, if user logged , token:     if (!isset($_session['token')) {   header("http/1.0 403 forbidden");   die("direct access not allowed!"); }  // assuming ajax post though didn't tell if (!isset($_post['token'] || $_post['token'] != $_session['token']) {   header("http/1.0 400 bad request");   die("you didn't provide valid token!"); }  // db 

otherwise need check if user logged rest of scripts:

<?php // myscript.php session_start(); // check if logged in user if (!isset($_session['loggedin']) || !$_session['loggedin']) {   header("http/1.0 403 forbidden");   die("you need logged in!"); }  // db 

to sum up

using first method allows more controlled access force user send secret (the token, different in every request) normal user won't have (if other user gets token, have bigger problems session hijacking). notice method prevents user opening on multiple tabs / different browsers last token saved. in order avoid have this fantastic answer on so

on other hand, second approach allows (logged) users request directly myscript.php, maybe don't need prevent (if need, use first method). notice here won't have issue of multiple tabs / different browsers you'll check if user logged in.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -