PHP Rest with cURL

request.php

function request($request_type) {
 
	$ch = curl_init();
 
	curl_setopt ($ch, CURLOPT_URL, "http://localhost/server.php");
 
	switch (true) {
 
		case $request_type == 'get':
 
			curl_setopt ($ch, CURLOPT_HEADER, 0);
 
			break;
 
		case $request_type == 'post':
 
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, array('foo' => 'bar'));
 
			break;
 
		case $request_type == 'put' :
 
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
 
			break;
 
		case $request_type == 'delete':
 
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
 
			break;
 
	}
 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
	return curl_exec($ch);
}
 
var_dump(request('get'));
 
var_dump(request('post'));
 
var_dump(request('put'));
 
var_dump(request('delete'));

server.php

echo 'REQUESTED: ' . $_SERVER['REQUEST_METHOD'];

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">