简体   繁体   中英

How can I post a form field through CURL in PHP?

I am trying to integrate an API on my website and it requires me to post an authorization field which is encoded in base64. However, it is saying that I am not doing it correctly. I wonder if it is because I am not posting the field correctly. This is what I have done so far.

$pro = '00000000000';

$host = 'http://www.saiasecure.com/irsec/getimginfo1.aspx?refNumber='.$pro; 

$authorization = 'username : password';

$authorization = base64_encode($authorization);

$post = array(

    'Authorization' => $authorization

    );

$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
curl_close($ch);

$xml = new SimpleXMLElement($return);

try
{

    print_r($xml);

} catch(SoapFault $ex){

    $ex->getMessage();
    echo $ex;

}

These are the API instructions provided by the developer.

在此处输入图片说明

This is the response I get from the API:

在此处输入图片说明

Does anybody know what I'm doing wrong? It is driving me crazy!

The documentation says the value is the concatenation of user id, ':', and password. This might be confusing wording. You should remove those spaces, making your code:

$authorization = 'username:password';

The C# example of the code shows it needs a base64 encode:

$authorization = base64_encode($authorization);

And based on Xorifelse's input it's simpler to just let curl set the headers for you:

curl_setopt($ch, CURLOPT_USERPWD, $authorization);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM