How to pass a parameter via curl_exec to another url with PHP?

0

I have a PHP that after performing an operation it calls an external URL and returns the value of this external URL, using curl_exec.

However, I need to pass a parameter to this new url, preferably as a session. How can I pass this parameter which in this case is:

$transactionReference

Follow my code:

 echo 'codigo da transação: '.$transactionReference;      


        // chama a url de geração da nota fiscal

        // create a new cURL resource
        $ch = curl_init();

        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_URL, "http://nhaac.com/envianfe.php");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $transactionReference); 

        // grab URL and pass it to the browser
        curl_exec($ch);

        // close cURL resource, and free up system resources
        curl_close($ch);

Just to illustrate the other PHP that this call does is like this:

<?php


 session_start();
    require 'conexao.php';

    if($transactionReference):
         echo 'codigo do fornecedor já no nfe: '.$transactionReference;
    endif;

require_once ('client-php/lib/init.php');

echo 'codigo do fornecedor já no nfe: '.$transactionReference;
..
..
..
..
..

Maybe this is where I'm not sure how to get the variable.

    
asked by anonymous 02.07.2017 / 21:04

1 answer

1

The answer from the @Daniel Omine says about the POST method and in the meantime if it is GET it could simply do: / p>

$parametro = http_build_query($transactionReference, '', '&', PHP_QUERY_RFC3986);

curl_setopt($ch, CURLOPT_URL, 'http://minha_url/envianfe.php?' . $parametro);

In this case assuming that $transactionReference is:

$transactionReference = ['ref' => '1', 'conteudo' => 'x'];

It will send the request as:

http://minha_url/envianfe.php?ref=1&conteudo=x

On the other page you will use:

$_GET['ref'];
$_GET['conteudo'];

For example.

I do not understand the "preferably session", if it refers to the session cookie and if both are equal you could use CURLOPT_HTTPHEADER or CURLOPT_COOKIE :

$cookies = http_build_query($_COOKIE, '', '; ', PHP_QUERY_RFC3986)  . ';';

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Cookie: ' . $cookies
]); 

This would cause if the user accesses the page from A, the curl would connect to page B using the cookies that the user sent in A.

If you just wanted to send some information you could use:

curl_setopt($ch, CURLOPT_POSTFIELDS, $transactionReference);

That would be exactly the explained in this answer . On the other page (which will receive the information) use php://input :

$transactionReference = file_get_contents('php://input');
    
02.07.2017 / 21:38