Search code examples
phprestcurlput

Passing PHP array through CURL PUT generates notice undefined index


I am working on a basic REST application in PHP and I have the following code. Client side code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch , CURLOPT_HEADER,false);
curl_setopt($ch ,  CURLOPT_FOLLOWLOCATION , true);
curl_setopt($ch , CURLOPT_URL , "http://localhost/Hello/Rest");
curl_setopt($ch , CURLOPT_POSTFIELDS,     
                  http_build_query(array("username"     => "test")));
$output = curl_exec($ch);
print_r($output);
curl_close($ch);

Server side code:

$username = $_REQUEST['username'];
echo "This is a PUT request";
echo "<br>";
echo $username;
echo "<br>";

For some reason $_REQUEST['username'] is not recognized.Generates undefined index.

Not really sure what was missing that causes this error.


Solution

  • As @NaijaProgrammer pointed out, $_REQUEST does not contain PUT values. If you want to stick with PUT, you will need to modify your server code. See this link for more information.

    // for put requests
    parse_str(file_get_contents("php://input"),$post_vars);
    $username = $post_vars['username'];
    echo "This is a PUT request";
    echo "<br>";
    echo $username;
    echo "<br>";