Memento Mori
Memento Mori

Reputation: 3402

Beginner php curl using post, prints contents of other script instead of response

I'm attempting to learn how to use curl in php from a tutorial. I have one php script communicating with another. The first script is:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"http://localhost/some_directories/testing.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "Hello=World&Foo=Bar&Baz=Wombat");

curl_exec ($curl);
curl_close ($curl)

And a second 'testing.php' script contains only the php tags and: var_dump($_POST);

When I run the first script I get the output: var_dump($_POST); instead of the posted values. I'm sure this is something obvious, but I'm not sure why it's happening.

Upvotes: 1

Views: 129

Answers (2)

ehime
ehime

Reputation: 8405

You forgot to set a true flag for CURLOPT_RETURNTRANSFER

Try this instead, its a lot cleaner, and breaks your parameters up a bit

$url = 'http://localhost/some_directories/testing.php';

$ch = curl_init($url);
curl_setopt_array($ch, array(
    CURLOPT_POST            => 1,
    CURLOPT_RETURNTRANSFER  => 1,
    CURLOPT_POSTFIELDS      => http_build_query(array(
                                'Hello' => 'World',
                                'Foo'   => 'Bar',
                                'Baz'   => 'Womabt',
                            )),
));

// error
if (FALSE === ($data = curl_exec($ch)))
{
    print_r(curl_error($ch));
}

curl_close($ch);

print_r($data);

Upvotes: 0

E. S.
E. S.

Reputation: 2919

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"http://localhost/some_directories/testing.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "Hello=World&Foo=Bar&Baz=Wombat");

$response = curl_exec ($curl);
curl_close ($curl);

echo $response;
?>

testing.php

<?php 
var_dump($_REQUEST);

Check this too... if none of your PHP code is running - https://stackoverflow.com/a/5121589/781251

Upvotes: 1

Related Questions