Page 1 of 1

Dev API

Posted: Sun Jan 29, 2012 6:03 pm
by RealTuty
Ok so now i have a problem with the dev api tut here is my code
<?php

class url_shortener {
		
	const API_URL = 'http://localhost:8888/r2/api/a.php';
	
	private static function send_post_data($data) {
		
		$url 		= parse_url(self::API_URL);
		$boundary 	= md5(microtime(true));
		
		$post = '';
		
		foreach ($data as $name => $value) {
			$post .= "--{$boundary}\r\n";
			$post .= "Content-Disposition: form-data; name=\"{$name}\"\r\n\r\n";
			$post .= $value . "\r\n";
		}
		
		$post .= "--{$boundary}--\r\n";
		
		if (isset($url['query'])) {
			$head = "POST = {$url['path']}?{$url['query']} HTTP/1.0\r\n";
		} else {
			$head = "POST = {$url['path']} HTTP/1.0\r\n";
		}
		
		$head .= "Host: {$url['host']}\r\n";
		$head .= "Content-Type: multipart/form-data; boundary=\"{$boundary}\"\r\n";
		$head .= "Content-Length: " . strlen($post) . "\r\n";
		$head .= "Connection: close\r\n\r\n";
		
		$socket = fsockopen($url['host'], ((isset($url['port'])) ? $url['port'] : 80));
		
		fwrite($socket, "{$head}{$post}");
		
		echo end(explode("\r\n\r\n", stream_get_contents($socket)));
	}
	
	// gets the url for the key
	public static function lookup($key) {
		self::send_post_data(array(
			'lookup'	=> $key,
		));
	}
	
	// shortens a new url
	public static function shorten($url) {
		
	}
		
}

?>
the error im getting is

and error code 400
Bad Request

Your browser sent a request that this server could not understand.
:mad:

Re: Dev API

Posted: Tue Jan 31, 2012 6:08 pm
by jacek
You must have made a mess of the HTTP request somehow, I cant see it right away but try putting
echo "{$head}{$post}";
above the fwrite() line, that might show up what is wrong. If it's not obvious from that can you post the result of that here for me to take a look :)

Re: Dev API

Posted: Fri Feb 03, 2012 4:13 pm
by RealTuty
Ok so i put
echo "{$head}{$post}";
above the frwite()

and got this
POST = /r2/api/a.php HTTP/1.0 Host: localhost Content-Type: multipart/form-data; boundary="8376698c1a6bf3046e88ba60fbb2cff0" Content-Length: 126 Connection: close --8376698c1a6bf3046e88ba60fbb2cff0 Content-Disposition: form-data; name="lookup" d --8376698c1a6bf3046e88ba60fbb2cff0--

Re: Dev API

Posted: Sat Feb 04, 2012 12:33 am
by jacek
Ah, can you view the page source in your browser and post that with the line breaks intact ?