Is there any way to save the input value to a Session?

Asked

Viewed 1,197 times

1

I need to save the value typed by the user in a input unused form. I thought about SESSION, but I don’t know any way to do that. There is a?

The input: <input type="text" name="valor">

I want to save in $_SESSION['valor']

  • I had not seen the "without using form". Maybe the best solution is with javascript.

  • And as saved in SESSION with javascript?

1 answer

2


You will need to make a request via ajax for a PHP code, I believe the best solution is js as Diego commented, so via POST it will be possible to store something in the variable $_SESSION['value'] in a PHP script.

Below is an example with jQuery:

$("input[name=valor]").keypress(function(){
    $.post( "salvaSession.php", { dado: $("input[name=valor]").val() } );
});

That is, every time a key is pressed in the field, it will send a POST request to salvaSession.php, where salvaSession.php would contain something like:

<?php
session_start(); //se ainda não começou a session.
$_SESSION['valor'] = $_POST['dado'];
?>

This is the basic concept, now just improve so there are not so many requests, maybe in the field lostFocus.

  • 1

    Important detail: do not forget to sanitize the data before saving to the session (i.e. check if the data format is ok and the client has not sent a malicious request). Otherwise, you may be vulnerable to an attack of Injection, depending on how you use this saved data (or even an XSS, if you echo the data back to the user).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.