Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have been working with PHP sessions and login protected pages for some time, but i want to start using some AJAX for managing some actions inside login protected pages (easy way with Jquery). I am new in world of ajax. Here is what i want to do: user logs in (classic no-ajax method), and wants to submit message. I make request with ajax to other page, where session is checked and message saved. Here is how start page look:

<?php 
    session_name('NEWSESSION');
    session_start();
    session_regenerate_id(true);

    if(!$_SESSION['user_logged']){
            header("location: login.php");
    }

    $sessionTTL = time() - $_SESSION["timeout"];
    if ($sessionTTL > SES_LENGHT) {
            session_destroy();
            header("location: login.php");
    }
?>

<!-- page header and all other html things here -->

<div id="returned_message"></div>
<textarea id="message">TEST</textarea>
<input type="" id="submit" value="Submit message">
<script>
$("#submit").click(function(){
    $.ajax({ 
        type: 'POST',
        data: {
            action: 'submit_message',
            message: $("#message").val();
        },
        url: '/save.php',
        success: function(data) {
            $('#returned_message').html(data);
        }
    });
});
</script>

And this is save.php where i send request (and sends "msg saved" alert):

<?php 
session_name('NEWSESSION');
session_start();
session_regenerate_id(true);

if(!$_SESSION['user_logged']){
    header("location: login.php");
}

$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > SES_LENGHT) {
    session_destroy();
    header("location: login.php");
}

$username = $_SESSION['user_username']; 

if($_POST["action"] == "save_message"){
    /* PHP code for saving message */
    echo "Message saved!";
}
?>

What i want to know, is this right way to do this? And how vulnerabe is this (is it more vulnerabe than to do it with classic PHP methods, with no fancy ajax things)? All suggestions are welcome.

share|improve this question
add comment

1 Answer

Consider adding User Agent check

Adding a User Agent check will add another layer of security. This will slow down Session Hijacking a bit.

AJAX alone is not a security issue

AJAX is no more vulnerable then regular access when it comes to sessions.

SES_LENGHT is not defined

The constant SES_LENGHT is not defined anywhere. Is your code snippet complete?

share|improve this answer
    
Tnx for your answer. Regarding SES_LENGHT, it is defined in included file (just i removed that include to simplify example and make it more clear). –  SomeoneS Nov 14 '12 at 8:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.