Curl Usage to Get Header

curl usage to get header

You need to add the -i flag to the first command, to include the HTTP header in the output. This is required to print headers.

curl -X HEAD -i http://www.google.com

More here: https://serverfault.com/questions/140149/difference-between-curl-i-and-curl-x-head

How to send a header using a HTTP request through a cURL call?

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1¶m2=value2" http://hostname/resource

For file upload:

curl --form "fileupload=@filename.txt" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

How to read headers from file using cURL?

Let's ask shellcheck:

In yourscript line 3:
headers="$headers -H '$line'"
^-- SC2089: Quotes/backslashes will be treated literally.
Use an array.

Ok, then let's do that:

#!/bin/bash
while read line ; do
headers=("${headers[@]}" -H "$line")
done < public/headers.txt
echo "${headers[@]}"
curl -X PUT \
"${headers[@]}" \
-d @'public/example.json' \
echo.httpkit.com

Result:

{
"method": "PUT",
"uri": "/",
"path": {
"name": "/",
"query": "",
"params": {}
},
"headers": {
"host": "echo.httpkit.com",
"user-agent": "curl/7.35.0",
"accept": "*/*",
"x-paypal-security-userid": "123", // <----- Yay!!
"x-paypal-security-password": "123",
"content-length": "32",
"content-type": "application/x-www-form-urlencoded"
},
"body": "\"This is text from example.json\"",
"ip": "127.0.0.1",
"powered-by": "http://httpkit.com",
"docs": "http://httpkit.com/echo"
}

PHP Using cURL and GET request with a header

According to PHP documentation for CURLOPT_HEADER:

TRUE to include the header in the output.

Your $response will probably look like this:

HTTP/1.1 200 OK
Some: headers
More: header lines

{
"real": "json content"
}

This is because you added the CURLOPT_HEADER option.

You don't need to set any options to let the curl request send your headers. As long as you set the CURLOPT_HTTPHEADER option, the headers will be sent.

If you really want to receive the response headers too, check existing questions like "Can PHP cURL retrieve response headers AND body in a single request?"



Related Topics



Leave a reply



Submit