But What If I Don’t Want to CURL?

The times they are a-changin’.

This post seems to be older than 14 years—a long time on the internet. It might be outdated.

It seemed too easy. It was too easy. I made an assumption about the initial configuration of a users PHP installation and didn’t think about the consequences. cURL needs to be included during compilation of PHP and if it’s not, then you can’t use the magic that is cURL. One of my goals as a programmer is to make my software as compatible as possible. This is good for many reasons, but in the end I do it because it keeps everyone happy. So I tweaked the Akismet class I’ve been using to use fsockopen. It’s literally the exact same code that Akismet uses in their documentation:

function call($meth, $post_args, $host, $port = 80) {
	
	$post_args['blog'] = $this->blog;

	foreach($post_args as $key => $value){
		$http_content .= $key."=".urlencode($value)."&";
	}

	$http_content = rtrim($http_content, "&");
		
	$http_request  = "POST $meth HTTP/1.0\r\n";
	$http_request .= "Host: $host\r\n";
	$http_request .= "Content-Type: application/x-www-form-urlencoded; charset=" . get_settings('blog_charset') . "\r\n";
	$http_request .= "Content-Length: " . strlen($http_content) . "\r\n";
	$http_request .= "User-Agent: WordPress/".get_bloginfo('version')." | afdn_errorPage/1.2\r\n";
	$http_request .= "\r\n";
	$http_request .= $http_content;

	$response = '';
	if( false !== ( $fs = fsockopen($host, $port, $errno, $errstr, 3) ) ) {
		fwrite($fs, $http_request);
		while ( !feof($fs) )
			$response .= fgets($fs, 1160); // One TCP-IP packet
		fclose($fs);
		$response = explode("\r\n\r\n", $response, 2);
	}

	return $response[1];
	
}

Note that the array has to be built into a string so that it can be passed properly. You also probably want to build the string before you start building the request because you’ll need to specify the length of your content which I found out the server actually pays attention to.

The only other changes that when using the call function, $meth needs to be preceded by /1.1/ and you need to drop the /1.1/ from the end of $host. Thus a call to check a comment would now look like:

$this->call('/1.1/comment-check', $post_args, "{$this->api_key}.rest.akismet.com");

[tags]akisment, api, curl, fsockopen, php[/tags]

0