Save $_POST with var_export after generating Variable again

Asked

Viewed 295 times

0

I needed to generate some data by taking the contents of a $_POST and saving it to a file to process it later.

I did it this way:

$dados = $_POST;
$dados = var_export($dados, true);
$handle = fopen('posttemp.txt', 'a');
fwrite($handle, $dados);
fclose($handle);

So far so good, if I open the file posttemp.txt this is its content.

array (
  'id' => '1832007',
  'post' => 
  array (
    'codigo' => '39063',
    'autor' => 'Christiano',
  ),
  'conteudo' => 
  array (
    'id' => '2526167',
    'dataInicio' => '2017-08-03 21:30:43',
    'dataFinalizada' => '2017-08-03 21:30:47',
    'status' => 'Publicado',
  ),
  'autor' => 
  array (
    'codigo' => '37276',
    'email' => '[email protected]',
    'nome' => '1 Lift Gold',
    'quantidade' => '1',
  )
)

Now I need to get the contents that were saved in posttemp.txt and turn it back into a variable so it can send again via POST.

  • 1

    Why don’t you use the serialize and unserialize?

1 answer

1

The var_export does not have a reverse path, its purpose is to create a array valid for PHP, for example if you want to edit files .php dynamically configurative.

A very simple example would be this:

Sage:

<?php
$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

$str = var_export($arr, true);
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';

file_put_contents('config.php', $str);

It will generate the following content:

 <?php
 return array (
   'a' => 1,
   'b' => 2,
   'c' => 3,
 );

Use the data later:

<?php

$arr = include 'config.php'; //O return em includes retorna o valor

print_r($arr);

This can be an example of use you want, because the config.php will load the data into the várivel $arr for include.

However if you really want to use a file .txt and whether the data are not sensitive (such as passwords or secret codes), you can use functions such as serialize and unserialize, for example:

write php.

file_put_contents('posttemp.txt', serialize($_POST));

read php.

$dados = file_get_contents('posttemp.txt'); // Lê o arquivo

$post_recuperado = unserialize($dados); //recria os valores

var_dump($post_recuperado); //Exibe com var_dump

Note:

  • file_get_contents reads the contents of the archive
  • file_put_contents save the contents to the file
  • Wouldn’t it be better to use json_decode and json_encode? According to the documentation of the unserialize: "Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes.".

Browser other questions tagged

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