How to submit a POST request without form

Asked

Viewed 1,580 times

0

I have the following code snippet. Taken from this website. I want to send the values described below to another page through POST (without using form or AJAX). My doubt 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);

2 answers

2

Just complementing the answer already given above, I 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";

?>

1


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

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

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

You can find the explanation of the file_get_contents method in http://php.net/manual/en/function.file-get-contents.php , in short, this function reads a file and returns a String. So in your example, it will read the page http://exemplo/make_action.php passing the parameters in $context and will return the processed page by putting in the variable $result.

Browser other questions tagged

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