#native_company# #native_desc#
#native_cta#

POST METHOD

By aji jaya
on February 6, 2004

Version: 4.0

Type: Function

Category: HTTP

License: Other

Description: Simple script to use post method for sending data to webserver.

<?php
/*
###################### MY HEADER (Aji Jaya) ([email protected]) ########################
This Post lib can work with 3 different type connection
 - using CURL Extensions
 - using fSockopen
 - using fOpen

 by default this lib will use CURL ext if available 
 if not it will use fOpen for PHP 4.3 and up
 and fSockOpen for PHP 5 AND the rest of PHP Version.

 CURL ext and fOpen can work with HTTPS and fSock can't ( i don't know how to use it with fSock )
 fOpen in PHP 5 can't send file i guees there is a bug in it. test with PHP 5.0.0b3 in WIN Platform
 And PHP 4.3 work great in all conection. test with PHP 4.3.5RC2 in WIN Platform
 i havent test it in  other PHP Version.

#########################################################################################
this lib based on 
simple post method version 1.0 by Andrus ([email protected])

###################### Release of 4.0 06/02/2004
HTTPRequester
A cookie-aware object in PHP for retrieving HTTP Web Pages.
The license for this is LGPL, post changes to PHPBUILDER.COM at 
https://phpbuilder.com/snippet/detail.php?type=snippet&id=352

Features:
        1) Cookie aware
        2) Cookies file format same as Netscape Mozilla's cookies.txt
        3) Method get or method post
        4) Can post file
        5) Can Work with all available conection
        6) Can Work PHP 5
        7) Can follow moved location
        8) Able to work with HTTP_AUTH passwords.

- Aji Jaya ([email protected])

*/
Class HTTPRequester
{
	var $follow=false;
	Var $devmode=true;
	Var $method='GET';
	Var $cookiefile='';
	var $removeCacheWhenClose = true;
	Var $cookiemap=array(
        'domain'        =>0,
        'flag'          =>1,
        'path'          =>2,
        'secure'        =>3,
        'expires'       =>4,
        'name'          =>5,
        'value'         =>6
        );

	/*
	FORMAT of cookies array:
	$cookies[www.yahoo.com][name]=array
        (
        0=>domain,
        1=>flag,
        2=>path,
        3=>secure,
        4=>expires,
        5=>name,
        6=>value
        );
        |  domain - The domain that created AND that can read the variable.
        |  flag - A TRUE/FALSE value indicating if all machines within a given
        |         domain can access the variable.
        |  path - The path within the domain that the variable is valid for.
        |  secure - A TRUE/FALSE value indicating if a secure connection with
        |         the domain is needed to access the variable.
        |  expiration - The UNIX time that the variable will expire on.
        |  name - The name of the variable.
        |  value - The value of the variable.
	*/

	Var $cookies=array();
	Var $site='';
	Var $request=array();

	Function Error($text=-1)
    {
        if ($text=="-1")
            return $this->error;
        else
			$this->error.= $text."n";

		if($this->cUrlLog)
			fwrite($this->cUrlLog, 'Error: '.$text."n");
    }

	Function Report($text = -1)
	{
		if ($text == -1)
			return $this->report;
		else if($this->devmode)
			$this->report .= $text."n";

		if($this->cUrlLog)
			fwrite($this->cUrlLog, 'Report: '.$text."n");
	}

	function createLog($path){
		$this->cUrlLog = fopen($path, "a");
		if(!$this->cUrlLog)return "Can't Open or Create Log";
		
		fwrite($this->cUrlLog, "<<<<<START LOG FILE>>>>>n");
		if($this->useExt == 'cUrl')
			curl_setopt($this->cUrl, CURLOPT_STDERR, $this->cUrlLog);
	}
	
	function getFile($path)
	{
		$this->Report("getFile: $path");
		if(!file_exists($path))
		{
			$this->Error("No such file : $path");
			return;
		}

		if(function_exists("file_get_contents"))
			return file_get_contents($path);

		$fp = fopen($path, "rb");
		$buf = fread($fp, filesize($path));
		fclose($fp);
		return $buf;
	}

	function setAuth($user,$pass)
	{
		$this->auth = $user.':'.$pass;
	}

	function setCachePath($path)
	{
		if(!ereg("/$", $path))$path.='/';
		if(is_dir($path)) $this->cachePath = $path;
	}

	function setRemoveCache($str = true){
		$this->removeCacheWhenClose = $str;
	}
	
	function setForm($fieldName, $data)
	{
		$num = count($this->request);
		$this->request[$num]=array(
			"name"=>$fieldName,
			"val"=>$data
		);
	}

	function setFormFile($fieldName, $path, $data = '')
	{
		if ($data) 
		{
			$num = count($this->request);
			$this->request[$num]=array(
				"name"=>$fieldName,
				"val"=>array(
					basename($path),
					$data,
					''
				)
			);
		}
		else if(file_exists($path))
		{
			$num = count($this->request);
			$this->request[$num]=array(
				"name"=>$fieldName,
				"val"=>array(
					basename($path),
					$this->getFile($path),
					function_exists("mime_content_type") ? mime_content_type($path) : ''
				)
			);
		}
		else 
			return false;

		$this->postFiles = true;
	}

	Function SetRequest($array)
	{
		if(!is_array($array))return;
		
		foreach($array AS $k => $v)
		{
			$num = count($this->request);

			if(is_array($v))
			{
				if($v[name] || $v[0])
				{
					$this->request[$num][name]=$v[name]?$v[name]:$v[0];
					$val =  $v[val]?$v[val]:$v[1];
					$this->request[$num][val]=$val;
					if(is_array($val))
						$this->postFiles = true;
				}
				
			}
			else
			{
				$this->request[$num][name] = $k;
				$this->request[$num][val] = $v;
			}
		}
		$this->method='POST';
	}

	function ClearRequest()
	{
		$this->request = array();
		return true;
	}
	
	function SetMethod($method)
	{
		if(!$this->postFiles && ($method == 'GET' || $method == 'POST'))
			$this->method=$method;
	}

	function Follow()
	{
		$this->follow = true;
		/* fOpen will always follow redirected URL */
	}

	Function SetReferer($string)
	{
		$this->referer=$string;
	}

	Function SetUserAgent($string)
	{
		$this->useragent=$string;
	}

	Function SetCookie($host, $line)
	{
		$this->Report("SetCookie($host, $line)");

		$elements=explode(";", $line);
		reset($elements);
		while(list($k, $v)=each($elements))
			if ($v=trim($v))
			{
				if ($kv=explode("=", $v ,2))
				{
					$a=trim($kv[0]);
					$b=trim($kv[1]);

					if ($k==0)
					{
						$ref[$this->cookiemap[name]]=$a;
						$ref[$this->cookiemap[value]]=$b;
					}
					else
					{
						if ($a=='expires')$b=strtotime($b);
						$ref[$this->cookiemap[$a]]=$b;
					}
				}
			}

		ksort($ref);
		
		if(!$ref[0])$ref[0]=$host;

		$this->cookies[$ref[0]][$ref[5]]=$ref;
		unset($ref);
	}

	function getReply()
	{
		return $this->pageHeader.$this->getFile($this->cacheFileName);
	}

	function getBody()
	{
		return $this->getFile($this->cacheFileName);
	}

	function getStatus($code = 1)
	{
		if($code == 1)return $this->responseStatusCode;
		return $this->responseStatus;
	}

	function getHeader()
	{
		return $this->pageHeader;
	}

	function getMime()
	{
		return $this->mimeType;
	}

	function getContentHeader()
	{
		if(!is_array($this->conHeader))
			return array();

		return $this->conHeader;
	}

	function getPageInfo($key='')
	{
		$url = parse_url($this->page);
		$path = preg_replace("'[^/]*$'", '', $url[path]);
		$uri=$url[scheme].'://'.(($this->user&&$this->pass)?$this->user.':'.$this->pass.'@':'').$url[host].($this->port?':'.$this->port:'').($path?$path:'/');

		$ret[uri]=$this->page;
		if($this->pageUrl)$ret[url]=$this->pageUrl;
		$ret[host]=$this->host;
		if($this->user)$ret[user]=$this->user;
		if($this->pass)$ret[pass]=$this->pass;
		$ret[path]=$this->path;
		$ret[mimetype]=$this->mimeType;
		$ret[basehref]=$uri;
		$ret[filename]=$this->fileName ? $this->fileName : basename($url[path]);
		$ret[size]=file_exists($this->cacheFileName)? filesize($this->cacheFileName) : 0;
		$ret[cacheFileName]=file_exists($this->cacheFileName) ? $this->cacheFileName : '';
		
		if($key)return $ret[$key];
		return $ret;
	}

	Function GetCookies($host)
	{
		$this->Report("GetCookies: $host");
		if (!is_file($this->cookiefile))
			return $this->error('Cookiefile not found');

		$in=file($this->cookiefile);
		$return=array();

		while (list($linenum, $line)=each($in))
			if ($line=trim($line))
			{
				$elements=explode("t", $line);

				foreach($elements as $a => $b)
					$elements[$a]=trim($b);

				$this->cookies[$elements[0]][$elements[5]]=$elements;
			}

		foreach($this->cookies AS $cookieHost => $cookie)
			if(ereg($cookieHost, $host))$return=array_merge($return, $cookie);
		
		return $return;
	}

	Function SaveCookies()
	{
		$this->Report('SaveCookies()');

		IF (!strlen($this->cookiefile))
			return $this->error('Cookie file undefined');

		if (!$fp=fopen($this->cookiefile, 'w'))
			return $this->error('Unable to write to cookie file to save cookies');

		reset($this->cookies);

		$cookiemap=array_flip($this->cookiemap);
		while (list($site, $sitecookies)=each($this->cookies))
		{
			while (list($ckey, $carr)=each($sitecookies))
			{
				// LOOP THRU THE COOKIEMAP, WRITE VALUES AS RELEVANT.
				reset($cookiemap);
				while(list($cookiekey, $cookietitle)=each($cookiemap))
				{
					if ($carr[$cookiekey])
						$write.=$carr[$cookiekey];
					elseif ($cookiemap[$cookiekey+1])
						$write.='false';

					if ($cookiemap[$cookiekey+1])
						$write.="t";
				}
				$write.="n";
			}
		}
		fwrite($fp, $write);
		fclose($fp);
	}

	function removeCache()
	{
		if(is_array($this->cacheFile))
			foreach($this->cacheFile AS $file)
				if(file_exists($file))
				{
					unlink($file);
					$this->Report("Cache file: $file deleted");
				}

		unset($this->cacheFile);
		return true;
	}

	Function Close()
	{
		$this->SaveCookies();

		if($this->removeCacheWhenClose)
			$this->removeCache();

		$this->Report("Close");

		if($this->cUrlLog)
		{
			fwrite($this->cUrlLog, "<<<<<END LOG FILE>>>>>nn");
			fclose($this->cUrlLog);
		}
		
		if($this->headerFileName)
		{
			fclose($this->headerFile);
			unlink($this->headerFileName);
		}
	}

	Function HTTPRequester($cookiefile)
	{
		$this->Report("HTTPRequester: $cookiefile");

		if (!strlen($cookiefile))
			return $this->error('You must specify the cookie file!');

		if (!is_File($cookiefile))
			if (!$fp=fopen($cookiefile, 'w'))
				return $this->error('Cookie file doesn't exist and cannot be created');
		if ($fp)
			fclose($fp);
		$this->cookiefile=$cookiefile;
		
		if(function_exists("curl_init"))
			$this->useExt = 'cUrl';
		else if(version_compare(PHP_VERSION,"5",'>'))
			$this->useExt = 'fSock';
		else if(version_compare(PHP_VERSION,"4.3",'>'))
			$this->useExt = 'fOpen';
		else
			$this->useExt = 'fSock';

		if($this->useExt == 'cUrl')
		{
			$this->cUrl = curl_init();
			curl_setopt($this->cUrl, CURLOPT_VERBOSE, 1);
			curl_setopt($this->cUrl, CURLOPT_FAILONERROR, 1);
			curl_setopt($this->cUrl, CURLOPT_TIMEOUT, 10); 
			curl_setopt($this->cUrl, CURLOPT_RETURNTRANSFER,1); 
			curl_setopt($this->cUrl, CURLOPT_HEADER, 0);

			$this->headerFileName = "header.cache.tmp";
			$this->headerFile = fopen($this->headerFileName, "w+");
			curl_setopt($this->cUrl, CURLOPT_WRITEHEADER, $this->headerFile);
		}
	}

	function buildRequest()
	{
		$this->Report("Build Request");

		if ($this->postFiles) 
		{
			foreach($this->request as $v)
			{
				if(is_array($v[val]))
				{
					if(!$v[val][2])
						$v[val][2] = "application/octet-stream";

					$out.="-----------------------------7d12442eab4rn";
					$out.="Content-Disposition: form-data; name="".$v[name].""; filename="".$v[val][0].""rn";
					$out.="Content-Type: ".$v[val][2]."rn";
					$out.="rn";
					$out.=$v[val][1]."rn";
				}
				else
				{
					$out.="-----------------------------7d12442eab4rn";
					$out.="Content-Disposition: form-data; name="".$v[name].""rn";
					$out.="rn";
					$out.=$v[val]."rn";
				}
			}

			if($out)$out.="-----------------------------7d12442eab4--rn";
		}
		else
		{
			foreach($this->request as $v)
			{
				if(strlen($out) != 0) $out .= "&";
				$out .= urlencode($v[name]). "=" .urlencode($v[val]);
			}
			$out=trim($out);
		}
		return $out;
	}

	function buildHeader()
	{
		$this->Report("Build Header");

		if ($cookies=$this->GetCookies($this->host))
			while (list($key, $v)=each($cookies))
			{
				if ($cookieline) $cookieline.='; ';
				$cookieline.=urlencode($key).'='.urlencode(trim($v[6]));
			}

		if($this->useExt == 'cUrl')
		{
			if($this->postFiles)
			{
				$header.= "$this->method $this->page HTTP/1.1rn";
				$header.= "Content-Type: multipart/form-data; boundary=---------------------------7d12442eab4rn";
				$header.= "Spy: ";
			}

			if($this->auth)
				curl_setopt($this->cUrl, CURLOPT_USERPWD, $this->auth);
			if($this->referer)
				curl_setopt($this->cUrl, CURLOPT_REFERER, $this->referer);
			if($this->useragent)
				curl_setopt($this->cUrl, CURLOPT_USERAGENT, $this->useragent);
			if($this->cookieline)
				curl_setopt($this->cUrl, CURLOPT_COOKIE, $this->cookieline);
		}
		else
		{
			if($this->useExt == 'fSock')
			{
				$header.= "$this->method $this->page HTTP/1.0rn";
				$header.= "Host: $this->hostrn";
			}

			$header.= "Accept: */*rn";
			$header.= "Proxy-Connection: Keep-Alivern";
			$header.= "Pragma: no-cachern";

			if($this->useragent)
				$header.= "User-Agent: $this->useragentrn";

			if ($this->postFiles)
				$header.= "Content-Type: multipart/form-data; boundary=---------------------------7d12442eab4rn";
			else if($this->method == 'POST')
				$header.= "Content-type: application/x-www-form-urlencodedrn";
		
			if($this->auth)
				$header.= "Authorization: Basic ".base64_encode($this->auth)."rn";

			if($this->referer)
				$header.= "Referer: ".$this->referer."rn";

			if($this->outLength)
				$header.= "Content-Length: $this->outLengthrn";

			if(trim($cookieline))
				$header.= "Cookie: $cookielinern";

			$header.= "rn";
		}

		$this->Report(trim($header));
		return $header;
	}

	Function Post($page)
	{
		$this->Report("Post: $page");
		$return='';

		$url = parse_url($page);
		$host = $url[host];
		$port = $url[port]?$url[port]:80;
		$user = $url[user];
		$pass = $url[pass];

		if($url[port] && $this->useExt == 'fSock')
		{
			$page = str_replace(":".$url[port], '', $page);
			$this->port = $url[port];
		}

		if($user && $pass)
		{
			$this->setAuth($user, $pass);
			$page = str_replace("$user:$pass@", '', $page);
			$this->user = $user;
			$this->pass = $pass;
		}

		$this->host = $host;
		$this->path = $url[path];

		$this->Report("use Ext $this->useExt ".PHP_VERSION);

		$POST = $this->buildRequest();

		if($this->method == "POST")
			$this->outLength = strlen($POST);
		else
			$this->outLength = 0;

		if($this->method=="GET" && $POST)
			$page = preg_replace("'?.*'", '', $page).'?'.$POST;

		$this->page = $page;
		$this->cFileName = md5($page);

		if($this->useExt == 'fOpen')
		{
			$opts[http]['method']=$this->method;
			$opts[http]['header']=$this->buildHeader();
			$opts[http]['content']=$POST;
			$context = stream_context_create($opts);

			$fp = @fopen($page, 'rb', false, $context);
			if(!$fp)
			{
				$this->Error("Unable to get $page");
				return;
			}
			else $this->Report("Get $page succes");

			$this->headerFile = $http_response_header;
			if(is_array($http_response_header))
				$this->processHeader();

			$this->processBody($fp);
		}

		else if($this->useExt == 'fSock')
		{
			$fp=@fsockopen($host, $port);
			if(!$fp)
			{
				$this->error('Unable to connect to '.$host);
				return;
			}
			$this->Report("Connect to $host succes");

			fwrite($fp, $this->buildHeader());
			$this->Report("Send Header");
			if($POST)
			{
				do{
					$len = fwrite($fp, $POST);
					$POST = substr($POST, $len);
				}while (strlen($POST));
				
				$this->Report("Send Post Data");
			}

			if(function_exists("Stream_Set_Timeout"))Stream_Set_Timeout($fp, 5);

			$this->processHeader($fp);

			if($this->follow && $this->locationMove)
			{
				fclose($fp);
				$this->redirect();
			}
			else
				$this->processBody($fp);
		}

		else if($this->useExt == 'cUrl')
		{
			$this->cacheFileName = $this->cachePath.$this->cFileName;
			$cFile = fopen($this->cacheFileName, "w");
			curl_setopt($this->cUrl, CURLOPT_FILE, $cFile);
			rewind($this->headerFile);

			$header = $this->buildHeader();
			if($this->postFiles)
				curl_setopt($this->cUrl, CURLOPT_CUSTOMREQUEST, $header);
			else
				curl_setopt($this->cUrl, CURLOPT_CUSTOMREQUEST, $this->method );

			if($this->method == "POST")
				curl_setopt($this->cUrl, CURLOPT_POSTFIELDS, $POST);
			else
				curl_setopt($this->cUrl, CURLOPT_POSTFIELDS, '');

			curl_setopt($this->cUrl, CURLOPT_URL,$page);
			curl_exec($this->cUrl);

			fclose($cFile);
			$this->cacheFile[] = $this->cacheFileName;

			$this->processHeader();

			if($this->follow && $this->locationMove)
				$this->redirect();
		}
	}

	function checkLine($line)
	{
		if(!trim($line))return;

		$this->Report("Header: ".trim($line));

		if(preg_match("'^.*filename=(.*)'", $line, $match))
			$this->fileName = trim($match[1]);

		if(preg_match("'^Content'", $line))
			$this->conHeader[] = trim($line);

		if (($cookieline=str_replace('Set-Cookie: ', '', $line))!=$line && $this->cookiefile)
			$this->SetCookie($this->host, trim($cookieline));

		if(preg_match("'^Content-Type: (.*)'", $line, $match))
			$this->mimeType = trim($match[1]);

		if(preg_match("'^HTTP/1.[d] ([d]+)(.*)'", $line, $match))
		{
			$this->responseStatusCode = $match[1];
			$this->responseStatus =trim($match[2]);
		}

		if(preg_match("'^Content-length: ([d]+)'i", $line, $match))
			$this->fileSize = $match[1];

		if(preg_match("'^Location: (.*)'", $line, $match))
			$this->locationMove = trim($match[1]);

		$this->pageHeader.=trim($line)."n";
	}

	function processHeader($fp = false)
	{
		$this->Report("Process Header");
		unset($this->pageHeader);

		if($this->useExt == 'fOpen')
			foreach($this->headerFile AS $line)
				$this->checkLine($line);
		
		else if($this->useExt == 'cUrl')
		{
			rewind($this->headerFile);
			while (!feof($this->headerFile))
			{
				$line=fgets($this->headerFile,1024);
				$this->checkLine($line);
			}
		}

		else if($this->useExt == 'fSock' && $fp)
		{
			while($line=fgets($fp,1024))
			{
				$this->checkLine($line);
				if (!trim($line))break;
			}
		}
	}

	function processBody($fp)
	{
		$this->Report("Process Body");
		if(!$fp)return;
		$fileSize =  $this->fileSize+1;

		$this->cacheFileName = $this->cachePath.$this->cFileName;
		$cFile = fopen($this->cacheFileName, "w");
		while (!feof($fp))
		{
			if($this->fileSize)
			{
				if($fileSize >= 8192)$max = 8192;
				else $max = $fileSize;
			}
			else $max = 1024;
			
			$line=fgets($fp,$max);

			if($this->fileSize)
				$fileSize -= strlen($line);
			
			fwrite($cFile, $line);

			if($this->fileSize && $fileSize <= 1)break;
		}

		fclose($fp);
		fclose($cFile);

		if(!filesize($this->cacheFileName))unlink($this->cacheFileName);
		else $this->cacheFile[] = $this->cacheFileName;
	}

	function redirect()
	{
		$this->SetReferer($this->page);

		if(!ereg("^http(s)?://", $this->locationMove))
			$uri=$this->getPageInfo('basehref').$this->locationMove;
		else 
			$uri = $this->locationMove;
			
		unset($this->locationMove,$this->postFiles);

		$this->SaveCookies();
		$this->report("Redirect to $uri");
		$this->ClearRequest();
		$this->setMethod('GET');
		$this->Post($uri);
	}
}//end of class
?>