Save $ _POST with var_export then generate Variable again

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 as follows:

$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 your 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 content that was saved in posttemp.txt and then transform it back into a variable so that I can send it again via POST.

    
asked by anonymous 28.11.2017 / 00:20

1 answer

1

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

A very simple example would be this:

Save:

<?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 usage you want, since config.php will load the data in the%% wrapper% by the $arr .

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

record.php

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

ler.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:

     
  • unserialize reads the contents of the file
  •   
  • file_get_contents writes the contents to the file
  •   
    
28.11.2017 / 01:29