Omar Omar - 27 days ago 11
PHP Question

Converting terminal CURL to PHP CURL?

How would I submit this test.xml file in PHP using this CURL command:

curl -X POST -k -d @test.xml -H "Content-Type: application/xml" --user username:password https://www.url.com


this isn't working for me:

$ch = curl_init();

//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Set the Url
curl_setopt($ch, CURLOPT_URL, 'https://username:password@url.com');

//Create a POST array with the file in it
$postData = array(
'testData' => '@test.xml',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

// Execute the request
$response = curl_exec($ch);


I'm also wondering how I could submit XML written in the code instead of an XML file.

Answer

You should not put username and password in the url. You can use curl_setopt($p, CURLOPT_USERPWD, $username . ":" . $password); for $username and $password. Eg below:

$p = curl_init($url);
curl_setopt($p, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
curl_setopt($p, CURLOPT_HEADER, 1);
curl_setopt($p, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($p, CURLOPT_POSTFIELDS, $postData);
curl_setopt($p, CURLOPT_POST, 1);
curl_setopt($p, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($p);
curl_close($p);