Sending a POST request without form

0

I have the following snippet of code.Rempted from this website . I want to send the values described below to another page through POST (Without using form or AJAX). My question is how do I recover the values on the other page and what exactly this method (file_get_contents) does.

$content = http_build_query(array(
    'field1' => 'Value1',
    'field2' => 'Value2',
    'field3' => 'Value3',
));

$context = stream_context_create(array(
    'http' => array(
        'method'  => 'POST',
        'content' => $content,
    )
));

$result = file_get_contents('http://exemplo/make_action.php', null, $context);

$content = http_build_query(array(
    'field1' => 'Value1',
    'field2' => 'Value2',
    'field3' => 'Value3',
));

$context = stream_context_create(array(
    'http' => array(
        'method'  => 'POST',
        'content' => $content,
    )
));


$result = file_get_contents('http://exemplo/make_action.php', null, $context);
    
asked by anonymous 09.06.2018 / 20:27

2 answers

1

The recovery of the values on the other page will be done in the usual way, as if you were using forms.

<?php
echo 'Valor1: '.$_POST['field1'];
?>

This would be the present code http://exemplo/make_action.php .

You can find the explanation of the file_get_contents method in link , in short, this function reads a file and returns a String. Then in your example, it will read the page http://exemplo/make_action.php passing the parameters to $context and return the processed page by placing it in the $result variable.

    
09.06.2018 / 21:23
2

Just by completing the answer already given above, use this way:     

//Por segurança, para pegar só o desejado, sem tags html
$Antes = "/[><']/";//Html, para retirar
$Depois = " ";

if(isset($_POST['valor'])){
$x_valor = preg_replace($Antes,$Depois,$_POST['valor']);
}else{
$x_valor = "";//Pega vazio se não vier como esperado
}

echo "$x_valor";

?>
    
09.06.2018 / 21:49