skip to content

PHP: Ajax script for making cURL HEAD requests

This article presents a simple PHP script that executes a cURL HEAD request for the supplied URL, and then uses our AjaxResponseXML PHP class to return the output to the calling page.

PHP Source Code

The code presented below accepts a single 'url' parameter and checks that it starts with a HTTP or HTTPS protocol. The path to cURL is hard-coded, and all user-supplied arguments are escaped.

Still, you may want to add extra filters and checks to improve security, and to restrict which URLs can be requested.

curl-head.xml.php:

<?PHP if(!isset($_POST['url']) || !preg_match("@^https?://\S+$@", $url)) { die("Invalid URL supplied: {$url}") } $CURL = "/usr/bin/curl --silent --user-agent " . escapeshellarg($_SERVER['HTTP_USER_AGENT']); $cmd = "{$CURL} --location --head " . escapeshellarg($url); exec($cmd, $out, $ret); $response = []; $http_code = NULL; foreach($out as $line) { if(preg_match("@^HTTP/\S+ (\d{3})@", $line, $regs)) { // new set of headers, starting with response three-digit code if($response) { $responses[] = $response; } $http_code = $regs[1]; $response = [ $http_code, ]; } if($http_code) { // include only matching headers in payload if(preg_match("/^(Server|Location|Content-(Type|Length)): /i", $line)) { $response[] = $line; } } } if($response) { $responses[] = $response; } $xml = new \Chirp\AjaxResponseXML(); $xml->start(); $xml->command('callback', [ 'params' => [ $url, json_encode($responses) ], ]); $xml->end(); exit;

Sample Output

As previously discussed, the output is an XML document containing parameters to be returned to the AjaxRequestXML JavaScript class from where the Ajax request was initiated:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <response> <command method="callback"> <params>https://www.the-art-of-web.com/javascript/curl-head-ajax/</params> <params>[["200","Server: Apache\/2.4","Content-Type: text\/html; charset=UTF-8"]]</params> </command> </response>

Each response, because there will be multiple where redirects are followed, is encoded as a JSON array starting with the response code, follwed by selected headers.

For more details, and a demonstration, refer to the accompanying article containing the HTML and JavaScript components that tie this all together.

< PHP

Post your comment or question
top