Over a million developers have joined DZone.

Request Adapter //PHP Class

·
A simple class providing a cute adapter for get/post requests.

Usage

$r = &new Request(POST_METHOD | GET_METHOD);
#$r = &new Request(POST_METHOD); //just post
#$r = &new Request(GET_METHOD); //just get =b

if($r->has('name'))
  echo $r->get('name'), $r->name;

echo $r->get('year', '2006');

if($r->isPosted())
  echo 'This was a post =b';


if($r->isFile('file'))
  if($r->file->isUploaded()){
    echo 'The file was uploaded';
    if($r->file->hasError())
      echo 'And there was an error when uploading';
    else{
      echo 'Moving ' . $r->file->path;
      $r->file->save('uploads/' . $r->file->name)
    }
  }





file = &$f;
		$this->name = $f['name'];
		$this->type = $f['type'];
		$this->size = $f['size'];
		$this->path = $f['tmp_name'];
		$this->error = $f['error'];
	}

	function hasError(){
		return $this->isUploaded() && $this->error != UPLOAD_ERR_OK;
	}

	function isUploaded(){
		return $this->error != UPLOAD_ERR_NO_FILE;
	}

	function save($path){
		return @move_uploaded_file($this->path, $path);
	}
}

class Request{
	function &Request($method){
		if(GET_METHOD & $method)
			foreach($_GET as $n=>$v)
				$this->$n = $v;
		if(POST_METHOD & $method){
			foreach($_POST as $n=>$v)
				$this->$n = $v;
			foreach($_FILES as $n=>$v)
				$this->$n = &new PostedFile($v);
		}
		return $this;
	}

	function isFile($name){
		return is_a($this->get($name), 'PostedFile');
	}

	function has($name){
		if(is_array($name)){
			foreach($name as $n)
				if(!isset($this->$n))
					return false;
			return true;
		}
		else
			return isset($this->$name);
	}

	function get($name, $default = null){
		if($this->has($name))
			return $this->$name;
		else
			return $default;
	}

	function isPosted(){
		return $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'];
	}
}
?>
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}