Posts Tagged ‘php’

PHP smtp authen­ti­ca­tion mail script using the PEAR Mail package

October 14th, 2009
require_once "Mail.php";

$from = "Sandra Sender ";
$to = "Ramona Recipient ";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "mail.example.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'auth' => true,
    'username' => $username,
    'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
  echo("

" . $mail->getMessage() . "

");
 } else {
  echo("

Message successfully sent!

");
 }

PHP — Basic parser func­tion that sup­ports mul­ti­ple deliminators

October 8th, 2009

function parseIT($file, $delim = "	", $encapsulator = array("\"", "'")) {

	$parsed = array();

	$lines = file($file);

	foreach ($lines as $key => $line) {

		$columns = explode($delim, $line);

		foreach ($columns as $k => $column) {

			$column = str_replace($encapsulator, "", $column);

			$parsed[$key] = array($k => $column);
		}
	}

	return $parsed;

}
//USAGE
parseIT('myfile.csv');

Cre­ate a bet­ter vari­able dump than var_dump() using PHP

October 1st, 2009
/*********************************************************************************************************************\
 * LAST UPDATE
 * ============
 * March 22, 2007
 *
 *
 * AUTHOR
 * =============
 * Kwaku Otchere
 * ospinto@hotmail.com
 *
 * Thanks to Andrew Hewitt (rudebwoy@hotmail.com) for the idea and suggestion
 *
 * All the credit goes to ColdFusion's brilliant cfdump tag
 * Hope the next version of PHP can implement this or have something similar
 * I love PHP, but var_dump BLOWS!!!
 *
 * FOR DOCUMENTATION AND MORE EXAMPLES: VISIT http://dbug.ospinto.com
 *
 *
 * PURPOSE
 * =============
 * Dumps/Displays the contents of a variable in a colored tabular format
 * Based on the idea, javascript and css code of Macromedia's ColdFusion cfdump tag
 * A much better presentation of a variable's contents than PHP's var_dump and print_r functions
 *
 *
 * USAGE
 * =============
 * new dBug ( variable [,forceType] );
 * example:
 * new dBug ( $myVariable );
 *
 *
 * if the optional "forceType" string is given, the variable supplied to the
 * function is forced to have that forceType type.
 * example: new dBug( $myVariable , "array" );
 * will force $myVariable to be treated and dumped as an array type,
 * even though it might originally have been a string type, etc.
 *
 * NOTE!
 * ==============
 * forceType is REQUIRED for dumping an xml string or xml file
 * new dBug ( $strXml, "xml" );
 *
\*********************************************************************************************************************/

class dBug {

	var $xmlDepth=array();
	var $xmlCData;
	var $xmlSData;
	var $xmlDData;
	var $xmlCount=0;
	var $xmlAttrib;
	var $xmlName;
	var $arrType=array("array","object","resource","boolean","NULL");
	var $bInitialized = false;
	var $bCollapsed = false;
	var $arrHistory = array();

	//constructor
	function dBug($var,$forceType="",$bCollapsed=false) {
		//include js and css scripts
		if(!defined('BDBUGINIT')) {
			define("BDBUGINIT", TRUE);
			$this->initJSandCSS();
		}
		$arrAccept=array("array","object","xml"); //array of variable types that can be "forced"
		$this->bCollapsed = $bCollapsed;
		if(in_array($forceType,$arrAccept))
			$this->{"varIs".ucfirst($forceType)}($var);
		else
			$this->checkType($var);
	}

	//get variable name
	function getVariableName() {
		$arrBacktrace = debug_backtrace();

		//possible 'included' functions
		$arrInclude = array("include","include_once","require","require_once");

		//check for any included/required files. if found, get array of the last included file (they contain the right line numbers)
		for($i=count($arrBacktrace)-1; $i>=0; $i--) {
			$arrCurrent = $arrBacktrace[$i];
			if(array_key_exists("function", $arrCurrent) &&
				(in_array($arrCurrent["function"], $arrInclude) || (0 != strcasecmp($arrCurrent["function"], "dbug"))))
				continue;

			$arrFile = $arrCurrent;

			break;
		}

		if(isset($arrFile)) {
			$arrLines = file($arrFile["file"]);
			$code = $arrLines[($arrFile["line"]-1)];

			//find call to dBug class
			preg_match('/\bnew dBug\s*\(\s*(.+)\s*\);/i', $code, $arrMatches);

			return $arrMatches[1];
		}
		return "";
	}

	//create the main table header
	function makeTableHeader($type,$header,$colspan=2) {
		if(!$this->bInitialized) {
			$header = $this->getVariableName() . " (" . $header . ")";
			$this->bInitialized = true;
		}
		$str_i = ($this->bCollapsed) ? "style=\"font-style:italic\" " : ""; 

		echo "


";
	}

	//create the table row header
	function makeTDHeader($type,$header) {
		$str_d = ($this->bCollapsed) ? " style=\"display:none\"" : "";
		echo "


\n";
	}

	//error
	function  error($type) {
		$error="Error: Variable cannot be a";
		// this just checks if the type starts with a vowel or "x" and displays either "a" or "an"
		if(in_array(substr($type,0,1),array("a","e","i","o","u","x")))
			$error.="n";
		return ($error." ".$type." type");
	}

	//check variable type
	function checkType($var) {
		switch(gettype($var)) {
			case "resource":
				$this->varIsResource($var);
				break;
			case "object":
				$this->varIsObject($var);
				break;
			case "array":
				$this->varIsArray($var);
				break;
			case "NULL":
				$this->varIsNULL();
				break;
			case "boolean":
				$this->varIsBoolean($var);
				break;
			default:
				$var=($var=="") ? "[empty string]" : $var;
				echo "
".$header."
".$header." "; } //close table row function closeTDRow() { return "
\n \n \n
".$var."
\n"; break; } } //if variable is a NULL type function varIsNULL() { echo "NULL"; } //if variable is a boolean type function varIsBoolean($var) { $var=($var==1) ? "TRUE" : "FALSE"; echo $var; } //if variable is an array type function varIsArray($var) { $var_ser = serialize($var); array_push($this->arrHistory, $var_ser); $this->makeTableHeader("array","array"); if(is_array($var)) { foreach($var as $key=>$value) { $this->makeTDHeader("array",$key); //check for recursion if(is_array($value)) { $var_ser = serialize($value); if(in_array($var_ser, $this->arrHistory, TRUE)) $value = "*RECURSION*"; } if(in_array(gettype($value),$this->arrType)) $this->checkType($value); else { $value=(trim($value)=="") ? "[empty string]" : $value; echo $value; } echo $this->closeTDRow(); } } else echo " ".$this->error("array").$this->closeTDRow(); array_pop($this->arrHistory); echo " "; } //if variable is an object type function varIsObject($var) { $var_ser = serialize($var); array_push($this->arrHistory, $var_ser); $this->makeTableHeader("object","object"); if(is_object($var)) { $arrObjVars=get_object_vars($var); foreach($arrObjVars as $key=>$value) { $value=(!is_object($value) && !is_array($value) && trim($value)=="") ? "[empty string]" : $value; $this->makeTDHeader("object",$key); //check for recursion if(is_object($value)||is_array($value)) { $var_ser = serialize($value); if(in_array($var_ser, $this->arrHistory, TRUE)) { $value = (is_object($value)) ? "*RECURSION* -> $".get_class($value) : "*RECURSION*"; } } if(in_array(gettype($value),$this->arrType)) $this->checkType($value); else echo $value; echo $this->closeTDRow(); } $arrObjMethods=get_class_methods(get_class($var)); foreach($arrObjMethods as $key=>$value) { $this->makeTDHeader("object",$value); echo "[function]".$this->closeTDRow(); } } else echo " ".$this->error("object").$this->closeTDRow(); array_pop($this->arrHistory); echo " "; } //if variable is a resource type function varIsResource($var) { $this->makeTableHeader("resourceC","resource",1); echo " \n \n"; switch(get_resource_type($var)) { case "fbsql result": case "mssql result": case "msql query": case "pgsql result": case "sybase-db result": case "sybase-ct result": case "mysql result": $db=current(explode(" ",get_resource_type($var))); $this->varIsDBResource($var,$db); break; case "gd": $this->varIsGDResource($var); break; case "xml": $this->varIsXmlResource($var); break; default: echo get_resource_type($var).$this->closeTDRow(); break; } echo $this->closeTDRow()." \n"; } //if variable is a database resource type function varIsDBResource($var,$db="mysql") { if($db == "pgsql") $db = "pg"; if($db == "sybase-db" || $db == "sybase-ct") $db = "sybase"; $arrFields = array("name","type","flags"); $numrows=call_user_func($db."_num_rows",$var); $numfields=call_user_func($db."_num_fields",$var); $this->makeTableHeader("resource",$db." result",$numfields+1); echo " "; for($i=0;$i<$numfields;$i++) { $field_header = ""; for($j=0; $j".$field_name." "; } echo " "; for($i=0;$i<$numrows;$i++) { $row=call_user_func($db."_fetch_array",$var,constant(strtoupper($db)."_ASSOC")); echo " \n"; echo " ".($i+1)." "; for($k=0;$k<$numfields;$k++) { $tempField=$field[$k]->name; $fieldrow=$row[($field[$k]->name)]; $fieldrow=($fieldrow=="") ? "[empty string]" : $fieldrow; echo " ".$fieldrow." \n"; } echo " \n"; } echo " "; if($numrows>0) call_user_func($db."_data_seek",$var,0); } //if variable is an image/gd resource type function varIsGDResource($var) { $this->makeTableHeader("resource","gd",2); $this->makeTDHeader("resource","Width"); echo imagesx($var).$this->closeTDRow(); $this->makeTDHeader("resource","Height"); echo imagesy($var).$this->closeTDRow(); $this->makeTDHeader("resource","Colors"); echo imagecolorstotal($var).$this->closeTDRow(); echo " "; } //if variable is an xml type function varIsXml($var) { $this->varIsXmlResource($var); } //if variable is an xml resource type function varIsXmlResource($var) { $xml_parser=xml_parser_create(); xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0); xml_set_element_handler($xml_parser,array(&$this,"xmlStartElement"),array(&$this,"xmlEndElement")); xml_set_character_data_handler($xml_parser,array(&$this,"xmlCharacterData")); xml_set_default_handler($xml_parser,array(&$this,"xmlDefaultHandler")); $this->makeTableHeader("xml","xml document",2); $this->makeTDHeader("xml","xmlRoot"); //attempt to open xml file $bFile=(!($fp=@fopen($var,"r"))) ? false : true; //read xml file if($bFile) { while($data=str_replace("\n","",fread($fp,4096))) $this->xmlParse($xml_parser,$data,feof($fp)); } //if xml is not a file, attempt to read it as a string else { if(!is_string($var)) { echo $this->error("xml").$this->closeTDRow()." \n"; return; } $data=$var; $this->xmlParse($xml_parser,$data,1); } echo $this->closeTDRow()." \n"; } //parse xml function xmlParse($xml_parser,$data,$bFinal) { if (!xml_parse($xml_parser,$data,$bFinal)) { die(sprintf("XML error: %s at line %d\n", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } //xml: inititiated when a start tag is encountered function xmlStartElement($parser,$name,$attribs) { $this->xmlAttrib[$this->xmlCount]=$attribs; $this->xmlName[$this->xmlCount]=$name; $this->xmlSData[$this->xmlCount]='$this->makeTableHeader("xml","xml element",2);'; $this->xmlSData[$this->xmlCount].='$this->makeTDHeader("xml","xmlName");'; $this->xmlSData[$this->xmlCount].='echo "'.$this->xmlName[$this->xmlCount].'".$this->closeTDRow();'; $this->xmlSData[$this->xmlCount].='$this->makeTDHeader("xml","xmlAttributes");'; if(count($attribs)>0) $this->xmlSData[$this->xmlCount].='$this->varIsArray($this->xmlAttrib['.$this->xmlCount.']);'; else $this->xmlSData[$this->xmlCount].='echo " ";'; $this->xmlSData[$this->xmlCount].='echo $this->closeTDRow();'; $this->xmlCount++; } //xml: initiated when an end tag is encountered function xmlEndElement($parser,$name) { for($i=0;$i<$this->xmlCount;$i++) { eval($this->xmlSData[$i]); $this->makeTDHeader("xml","xmlText"); echo (!empty($this->xmlCData[$i])) ? $this->xmlCData[$i] : " "; echo $this->closeTDRow(); $this->makeTDHeader("xml","xmlComment"); echo (!empty($this->xmlDData[$i])) ? $this->xmlDData[$i] : " "; echo $this->closeTDRow(); $this->makeTDHeader("xml","xmlChildren"); unset($this->xmlCData[$i],$this->xmlDData[$i]); } echo $this->closeTDRow(); echo " "; $this->xmlCount=0; } //xml: initiated when text between tags is encountered function xmlCharacterData($parser,$data) { $count=$this->xmlCount-1; if(!empty($this->xmlCData[$count])) $this->xmlCData[$count].=$data; else $this->xmlCData[$count]=$data; } //xml: initiated when a comment or other miscellaneous texts is encountered function xmlDefaultHandler($parser,$data) { //strip '' off comments $data=str_replace(array("<!--","-->"),"",htmlspecialchars($data)); $count=$this->xmlCount-1; if(!empty($this->xmlDData[$count])) $this->xmlDData[$count].=$data; else $this->xmlDData[$count]=$data; } function initJSandCSS() { echo << SCRIPTS; } }

An alter­na­tive screen scrap­ing func­tion using PHP

September 30th, 2009
function load($url,$options=array()) {

    $default_options = array(
        'method'        => 'get',
        'return_info'    => false,
        'return_body'    => true,
        'cache'            => false,
        'referer'        => '',
        'headers'        => array(),
        'session'        => false,
        'session_close'    => false,
    );

    foreach($default_options as $opt=>$value) {

        if(!isset($options[$opt])) $options[$opt] = $value;
    }

    $url_parts = parse_url($url);

    $ch = false;

    $info = array(

        'http_code'    => 200

    );

    $response = '';

    $send_header = array(
        'Accept' => 'text/*',
        'User-Agent' => 'codeTree/1.00.A (http://www.mycodetree.com)'
    ) + $options['headers'];

    if($options['cache']) {

        $cache_folder = '/tmp/'; //CACHE FOLDER (MUST EXIST)

        if(isset($options['cache_folder'])) $cache_folder = $options['cache_folder'];

        if(!file_exists($cache_folder)) {

            $old_umask = umask(0); 

            mkdir($cache_folder, 0777);

            umask($old_umask);
        }

        $cache_file_name = md5($url) . '.cache';

        $cache_file = joinPath($cache_folder, $cache_file_name); 

        if(file_exists($cache_file)) { 

            $response = file_get_contents($cache_file);

            $separator_position = strpos($response,"\r\n\r\n");

            $header_text = substr($response,0,$separator_position);

            $body = substr($response,$separator_position+4);

            foreach(explode("\n",$header_text) as $line) {

                $parts = explode(": ",$line);

                if(count($parts) == 2) $headers[$parts[0]] = chop($parts[1]);

            }

            $headers['cached'] = true;

            if(!$options['return_info']) return $body;

            else return array('headers' => $headers, 'body' => $body, 'info' => array('cached'=>true));

        }

    }
    ///////////////////////////// Curl /////////////////////////////////////
    if(function_exists("curl_init") and (!(isset($options['use']) and $options['use'] == 'fsocketopen'))) {

        if(isset($options['post_data'])) {

            $page = $url;

            $options['method'] = 'post';

            if(is_array($options['post_data'])) {

                $post_data = array();

                foreach($options['post_data'] as $key=>$value) {

                    $post_data[] = "$key=" . urlencode($value);

                }

                $url_parts['query'] = implode('&', $post_data);

            } else {

                $url_parts['query'] = $options['post_data'];

            }

        } else {

            if(isset($options['method']) and $options['method'] == 'post') {

                $page = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];

            } else {

                $page = $url;

            }

        }

        if($options['session'] and isset($GLOBALS['_binget_curl_session'])) 

        $ch = $GLOBALS['_binget_curl_session'];

        else 

        $ch = curl_init($url_parts['host']);

        curl_setopt($ch, CURLOPT_URL, $page) or die("Invalid cURL Handle Resouce");

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

        curl_setopt($ch, CURLOPT_HEADER, true);

        curl_setopt($ch, CURLOPT_NOBODY, !($options['return_body'])); 

        if(isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {

            curl_setopt($ch, CURLOPT_POST, true);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $url_parts['query']);

        }

        curl_setopt($ch, CURLOPT_USERAGENT, $send_header['User-Agent']);

        $custom_headers = array("Accept: " . $send_header['Accept'] );

        if(isset($options['modified_since']))

            array_push($custom_headers,"If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T',strtotime($options['modified_since'])));

        curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);

        if($options['referer']) curl_setopt($ch, CURLOPT_REFERER, $options['referer']);

        curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/binget-cookie.txt");

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        if(isset($url_parts['user']) and isset($url_parts['pass'])) {

            $custom_headers = array("Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']));

            curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);

        }

        $response = curl_exec($ch);

        $info = curl_getinfo($ch);

        if($options['session'] and !$options['session_close']) $GLOBALS['_binget_curl_session'] = $ch;

        else curl_close($ch);

    //////////////////////////////////////////// FSockOpen //////////////////////////////
    } else {

        if(isset($url_parts['query'])) {

            if(isset($options['method']) and $options['method'] == 'post')

                $page = $url_parts['path'];

            else

                $page = $url_parts['path'] . '?' . $url_parts['query'];

        } else {

            $page = $url_parts['path'];

        }

        if(!isset($url_parts['port'])) $url_parts['port'] = 80;

        $fp = fsockopen($url_parts['host'], $url_parts['port'], $errno, $errstr, 30);

        if ($fp) {

            $out = '';

            if(isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {

                $out .= "POST $page HTTP/1.1\r\n";

            } else {

                $out .= "GET $page HTTP/1.0\r\n";
            }

            $out .= "Host: $url_parts[host]\r\n";

            $out .= "Accept: $send_header[Accept]\r\n";

            $out .= "User-Agent: {$send_header['User-Agent']}\r\n";

            if(isset($options['modified_since']))

                $out .= "If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T',strtotime($options['modified_since'])) ."\r\n";

            $out .= "Connection: Close\r\n";

            if(isset($url_parts['user']) and isset($url_parts['pass'])) {

                $out .= "Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']) . "\r\n";

            }

            if(isset($options['method']) and $options['method'] == 'post' and $url_parts['query']) {

                $out .= "Content-Type: application/x-www-form-urlencoded\r\n";

                $out .= 'Content-Length: ' . strlen($url_parts['query']) . "\r\n";

                $out .= "\r\n" . $url_parts['query'];

            }

            $out .= "\r\n";

            fwrite($fp, $out);

            while (!feof($fp)) {

                $response .= fgets($fp, 128);

            }

            fclose($fp);

        }

    }

    $headers = array();

    if($info['http_code'] == 404) {

        $body = "";

        $headers['Status'] = 404;

    } else {

        $header_text = substr($response, 0, $info['header_size']);

        $body = substr($response, $info['header_size']);

        foreach(explode("\n",$header_text) as $line) {

            $parts = explode(": ",$line);

            if(count($parts) == 2) $headers[$parts[0]] = chop($parts[1]);

        }

    }

    if(isset($cache_file)) {

        file_put_contents($cache_file, $response);

    }

    if($options['return_info']) return array('headers' => $headers, 'body' => $body, 'info' => $info, 'curl_handle'=>$ch);

    return $body;

} 

//USAGE
$contents = load('http://example.com/rss.xml');