Location: PHPKode > scripts > GRA4 Social Network (Micro) > micro/gra4/gra4_functions_web.php
<?php
//called only once, when the client system commects to rga4
if (!defined('IN_GRA4'))//make sure it can be called only from the php, not directly over the web
{
	exit;
}


//fetches data over the web
function GRA4FetchWebData($strUrl,$strHeadersToSend,&$aResultHeaders)
{

//do we have CURL ?		it's ~30% faster than fopen
	if(in_array ('curl', get_loaded_extensions())) //yes, we have cURL ! =)
	{
		return GRA4FetchWebDataCurl($strUrl,$strHeadersToSend,$aResultHeaders);
	}
//do we have fopen wrapper ?  
	if(ini_get(allow_url_fopen) == 1)
	{
		return  GRA4FetchWebDataFopen($strUrl,$strHeadersToSend,$aResultHeaders);
	}
//no, cURL is not available as well. Error out!
	return ("FATAL ERROR: URL-aware fopen wrappers and cUrl are not allowed in your system. GRA4 Does now know how to talk to the server...  =( ");
}

//file_get_contentsmplementetion
function GRA4FetchWebDataFopen($strUrl,$strHeadersToSend,&$aResultHeaders)
{
//ATT! Does not work for all webservers (sometimes headers are not sent out)
	$strContentToSend = GRA4BuildHttpContent();
  $strMethod = $_SERVER['REQUEST_METHOD']; //must use the same  

	$opts = array(
  	'http'=>array(
			'max_redirects' => 0,
    	'method'=> $strMethod,
	    'header'=> $strHeadersToSend,
	    'protocol_version'=>1.0, //so we do not depend on php version
	    'ignore_errors' => true, //
      'content' => $strContentToSend,
	  )
	);
//print_r($opts); die;
	$context = stream_context_create($opts);
	stream_context_set_option ( $context , 'http' , 'header' , 'User-Agent: RRR\r\n' );	
//print_r(stream_context_get_options($context));	die;
	$strResultData = file_get_contents($strUrl, false, $context);
	$aResultHeaders = $http_response_header;
	return $strResultData;
}

//TODO - cURL implementetion
function GRA4FetchWebDataCurl($strUrl,$strHeadersToSend,&$aResultHeaders)
{
	$aFilesToDelete = array();
	$aData = GRA4BuildCurlPostData($aFilesToDelete);
//print_r($aData);die;		
	$aHeadersToSend = explode("\r\n",trim($strHeadersToSend));
//print_r($aHeadersToSend);	
	$options = array(
	CURLOPT_HTTP_VERSION   => 1.0,					//works for any version of php	
	CURLOPT_FAILONERROR    => false,       //no show errors
        CURLOPT_RETURNTRANSFER => true,         // return data
        CURLOPT_HEADER         => true,        // return headers
        CURLOPT_FOLLOWLOCATION => false,         // no follow redirects
        CURLOPT_ENCODING       => "",           // handle all encodings
        CURLOPT_AUTOREFERER    => true,         // set referer on redirect
        CURLOPT_MAXREDIRS      => 0,           // stop after redirects
        CURLOPT_VERBOSE        => false,         //Writes output to STDERR if true
        CURLOPT_POST           => true,  				// i am sending post data
        CURLOPT_POSTFIELDS     => $aData,    // this are my post vars
	CURLOPT_HTTPHEADER     => $aHeadersToSend,
	CURLINFO_HEADER_OUT    => true,
  );

	$ch = curl_init($strUrl);
// set URL and other appropriate options
	curl_setopt_array($ch, $options);
// grab URL and pass it to the browser
	$strResultData = curl_exec($ch); //raw data, contians headers!
	if($strResultData === false)
	{
		$strError =  "cURL failed - please check your PHP settings.";	
		$strError .= "\n<br>".curl_error($ch);
		$strError .= "\n<br>Current Maximum Upload Size is " . ini_get('upload_max_filesize'); 	
		$strError .= "\n<br>Current Maximum POST Size is " . ini_get('post_max_size'); 		 	
		return $strError;
	}
//print_r(curl_getinfo($ch));die("now:".date(DATE_RFC822));
	$aResultHeadersSize  = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
//TROF
//print_r($strResultData);die;
	$strResultHeaders = mb_substr($strResultData,0,$aResultHeadersSize - mb_strlen("\r\n\r\n"));
//print_r("|$strResultHeaders|");die;	
	$aResultHeaders = explode("\r\n",$strResultHeaders);
	$strResultData = mb_substr($strResultData,$aResultHeadersSize);//skip headers
//print_r($strResultData);die;	 	
// close cURL resource, and free up system resources
	curl_close($ch);
//remove files if we had uploads
	for($d = 0; $d < count($aFilesToDelete); $d++)
	{
		if(file_exists($aFilesToDelete[$d]))
		{
			unlink($aFilesToDelete[$d]);
		}
	}
	return $strResultData;
//	return ("NOT IMPLEMENTED: The URL-aware fopen wrappers are off in your configuration, so we have to use cURL, but  function GRA4FetchWebDataCurl() in ".__FILE__." is not written yet =( ");
}

function GRA4BuildCurlPostData(&$aFilesToDelete)
{
	$aFileRet = array();
	$aFieldNames = array_keys($_FILES);
	for($i = 0; $i < count($_FILES); $i++)
	{
		$vFileName = $_FILES[$aFieldNames[$i]]['name'];
		if(is_array($vFileName))
		{
			for($j=0; $j < count($vFileName); $j++)
			{
				$strFileName = $_FILES[$aFieldNames[$i]]['name'][$j];
				if(mb_strlen($strFileName) > 0)
				{
					$strRealFileName = sys_get_temp_dir().'/'.$strFileName;
					array_push($aFilesToDelete,$strRealFileName);
					$strTempFileName = $_FILES[$aFieldNames[$i]]['tmp_name'][$j];
					$strFileType = $_FILES[$aFieldNames[$i]]['type'][$j];

					if(file_exists($strRealFileName))
					{
						unlink($strRealFileName);
					}
					
					move_uploaded_file($strTempFileName,$strRealFileName);
					$bRet = file_exists($strRealFileName); 
				
					$aFileRet[$aFieldNames[$i].'['.$j.']'] = '@'.$strRealFileName.';type='.$strFileType;

//all error handling suppose to be done on GRA4 server,
// but you may want to uncomment it for the troubleshooting
/* 
					if($bRet !== TRUE)
					{
						die("Multiple files - can't move '" . $strTempFileName . "' to '". $strRealFileName."'\n<br>Please adjust upload settings for this server.");		
					}
*/					
				}							
			}
		}
		else
		{
			if(mb_strlen($vFileName) > 0)
			{
				$strRealFileName = sys_get_temp_dir().'/'.$vFileName;
				array_push($aFilesToDelete,$strRealFileName);
				$strTempFileName = $_FILES[$aFieldNames[$i]]['tmp_name'];
				$strFileType = $_FILES[$aFieldNames[$i]]['type'];

				if(file_exists($strRealFileName))
				{
					unlink($strRealFileName);

				}
				move_uploaded_file($strTempFileName,$strRealFileName);
				$bRet = file_exists($strRealFileName); 
				
				$aFileRet[$aFieldNames[$i]] = '@'.$strRealFileName.';type='.$strFileType;

//all error handling suppose to be done on GRA4 server,
// but you may want to uncomment it for the troubleshooting
/* 
				if($bRet === TRUE)
				{
					die("Singe file - can't move '" . $strTempFileName . "' to '". $strRealFileName."'\n<br>Please adjust upload settings for this server.");		
				}
*/				
			}
		}
	}	
	
	$aT = explode('&',http_build_query($_POST));
//quick fix for POST fields containing '@' we add "\r" before '@', it's gonna be trimmed out
	$aT = str_replace('=%40','=%0D%40',$aT);


	unset($_POST);
	for($i = 0; $i < count($aT); $i++)
	{
		$aT2 = explode('=',$aT[$i]);
		if(get_magic_quotes_gpc() == 1)	
		{
			$_POST[urldecode($aT2[0])] = stripslashes(urldecode($aT2[1]));
		}		
		else
		{
			$_POST[urldecode($aT2[0])] = urldecode($aT2[1]);		
		}	
	}
	$aRet = array_merge($_POST,$aFileRet);

	return($aRet);
}

function GRA4BuildHttpContent()
{
	$strPost = http_build_query($_POST); 
	
	if( (count($_FILES) === 0) ) 
	{
		return $strPost; //we done
	}
	
	$strRet = '';	
	$strContentType = $_SERVER['CONTENT_TYPE'];
	$boundary = mb_substr($strContentType,mb_strpos($strContentType,'boundary=') + mb_strlen('boundary='));

	$aPost = explode('&',urldecode($strPost));
	for($i = 0; $i < count($aPost); $i++)
	{
		$aKeyValue = explode('=',$aPost[$i]);
		$strRet .= "--$boundary\n";
		$strRet .= "Content-Disposition: form-data; name=\"".$aKeyValue[0]."\"\n\n".$aKeyValue[1]."\n";
	}
	
	$strRet .= "--$boundary\n";
//Collect Filedata
	foreach($_FILES as $key => $file)
	{
		if(mb_strlen($file['tmp_name']) == 0)
		{
			continue;
		}
		$fileContents = file_get_contents($file['tmp_name']);
		if(!unlink($file['tmp_name']))
		{
//			GRA4Log("Can't delete",$file['tmp_name']);
		}
 
		$strRet .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\n";
		$strRet .= "Content-Type: ".$file['type']."\n";
		$strRet .= "Content-Transfer-Encoding: binary\n\n";
		$strRet .= $fileContents."\n";
		$strRet .= "--$boundary--\n";
	}

/*
echo("FILES:\n");print_r($_FILES); 
echo("POST:\n");print_r($_POST);  
echo("SERVER:\n");print_r($_SERVER); 	
echo("strRet:\n");print_r($strRet); 
die;
*/
	return $strRet; 
} //EOF GRA4BuildHttpContent
//NO EMPTY LINES AFTER '>', or Location header will fail !
?>
Return current item: GRA4 Social Network (Micro)