Daniel Abbadelli García Daniel Abbadelli García - 2 months ago 11
PHP Question

I can not pass a PHP SESSION and write it to text

I'm trying to pass

$_POST
info as
$_SESSION
but when it doesn't work, I don't know what is wrong in my code.

<?php
session_start();

$_SESSION['nombre'] = $_POST['nombre'];
$_SESSION['edad'] = $_POST['edad'];

?>
<html>
<form action="accion.php" method="post">
<p>Name: <input type="text" name="nombre" /></p>
<p>Age: <input type="text" name="edad" /></p>
<p><input type="submit" /></p>
</form>
</html>


Second file

<?php
session_start();
if(isset($_SESSION['nombre']) && isset($_SESSION['edad'])) {
$data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>

Answer Source

The following code will solve your problem:

File1.php

<html>
<form action="File2.php" method="post">
 <p>Name: <input type="text" name="nombre" /></p>
 <p>Age: <input type="text" name="edad" /></p>
 <p><input type="submit" /></p>
</form>
</html>
<?php
echo $_GET['msg'];
?>

File2.php

<?php
    session_start();
    if(isset($_POST['nombre']) && isset($_POST['edad'])) {
        $_SESSION['nombre'] = $_POST['nombre'];
        $_SESSION['edad']   = $_POST['edad'];
        $data = $_SESSION['nombre'] . '-' . $_POST['edad'] . "\n";
        $ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
        if($ret === false) {
            header("Location:File1.php?msg=There was an error writing this file");
        }
        else {
            header("Location:File1.php?msg=$ret bytes written to file";
        }
    }
    else {
       header("Location:File1.php?msg=no post data to process");
    }
?>

When the form is submitted, it is submitted to File2.php

So, your first session being set and taking values as POST from it in File1.php won't work.

The best option is to set the session in the second file and then give back a message to the File1.php as shown above.