Latest 100 public snipts »
robertbanh's
snipts » php
showing 1-20 of 25 snipts for php
-
∞ PHP States Array
<?php $optionArray = array("AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE","FL","GA","GU","HI","IA","ID", "IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY", "OH","OK","OR","PA","PR","PW","RI","SC","SD","TN","TX","UT","VA","VI","VT","WA","WI","WV","WY"); ?>
-
∞ PHP enable error reporting
<?php ini_set('error_reporting', E_ALL); ini_set('display_errors',1); ?>
-
∞ PHP session
<?php ini_set('session.use_cookies', 1); ini_set('session.use_only_cookies', 1); session_start(); $_SESSION['name'] = test; // This is required!! Else the session won't save for php 5.3 session_write_close(); header('location: index.php'); ?>
-
∞ Cron template file
<?php // =================== // Cron script: // // Author: Robert Banh // Date: // =================== set_time_limit(0); $currTime = date("F j, Y, g:i:sa"); echo "========================\r\n"; echo "Cron: \r\n"; echo "Job started: $currTime\r\n"; echo "========================\r\n"; // =================== // libs // =================== $path = '/home/user/'; require_once($path . 'db.php'); require_once($path . 'dbFacade.php'); // =================== // mysql init // =================== $dbFacade = new dbFacade(); $x= $dbFacade->blah(); echo "-- Total items: " . count($x) . "\r\n\r\n"; // ======================================= $currTime = date("F j, Y, g:i:sa"); echo "\r\n========================\r\n"; echo "Job finished: $currTime\r\n"; ?>
-
∞ PHP XML Expat method
<?php $current_tag = ''; function startTag($parser, $name, $attr) { global $current_tag; $current_tag = strtolower($name); } function endTag($parser, $name) { global $current_tag; $current_tag = null; } //Function to use when finding character data function expatEngine($parser,$data) { global $current_tag; if ($current_tag == 'name') { echo "name = $data <br/>"; } } //Specify data handler $xml_parser = xml_parser_create(); xml_set_element_handler($xml_parser, "startTag", "endTag"); xml_set_character_data_handler($xml_parser, "expatEngine"); //Open XML file $fp=fopen("local-greatschools-feed-TX.xml","r"); //Read data while ($data=fread($fp,8192)) { xml_parse($xml_parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } //Free the XML parser xml_parser_free($xml_parser); fclose($fp); ?>
-
∞ Fetch filename of URL
<?php // rbanh dynamic add $x = $_SERVER['PHP_SELF']; $x = preg_split('[/]', $x); $x = end($x); $x = substr($x, 0, strrpos($x, '.')); if ($x == 'iqnvr4') echo "i match iqnvr4"; else echo "i don't match iqnvr4"; // end of rbanh dynamic add ?>
-
∞ Truncate Strings
<?php // truncate with smart check for spaces function truncate($string, $limit = 75, $break = " ", $pad = "...") { if (strlen($string) <= $limit) return $string; $string = substr($string, 0, $limit); if (false !== ($breakpoint = strrpos($string, $break))) { $string = substr($string, 0, $breakpoint); } return $string . $pad; }
-
∞ PHP Array to XML (with attributes)
<?php // /* Example usage: =============== $xml = " <library id='123' test='456'> <book> <authorFirst>Mark</authorFirst> <authorLast>Twain</authorLast> <title>The Innocents Abroad</title> </book> <book> <authorFirst>Charles</authorFirst> <authorLast>Dickens</authorLast> <title>Oliver Twist</title> </book> </library>"; echo "<pre>"; var_export(ArrayToXML::xml2array($xml)); =============== $library = array( 'library' => array( '_a' => array( 'id'=>'1234', 'test'=>'456' ), '_c' => array( 'book' => array( '_c' => array( 'authorFirst' => array( '_v' => 'Mark' ), 'authorLast' => array( '_v' => 'Twain' ), 'title' => array( '_v' => 'The Innocents Abroad' ) ), '_c' => array( 'authorFirst' => array( '_v' => 'Charles' ), 'authorLast' => array( '_v' => 'Dickens' ), 'title' => array( '_v' => 'Oliver Twist' ) ), ) ) ) ); header('Content-Type: application/xml'); echo ArrayToXML::array2xml($library); */ class ArrayToXML { // Array to XML public static function array2xml($cary, $d=0, $forcetag='') { $res=array(); foreach ($cary as $tag=>$r) { if (isset($r[0])) { $res[]=ArrayToXML::array2xml($r, $d, $tag); } else { if ($forcetag) $tag=$forcetag; $sp=str_repeat("\t", $d); $res[]="$sp<$tag"; if (isset($r['_a'])) {foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";} $res[]=">".((isset($r['_c'])) ? "\n" : ''); if (isset($r['_c'])) $res[]=ArrayToXML::array2xml($r['_c'], $d+1); elseif (isset($r['_v'])) $res[]=$r['_v']; $res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n"; } } return implode('', $res); } // XML to Array public static function xml2array(&$string) { $parser = xml_parser_create(); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); xml_parse_into_struct($parser, $string, $vals, $index); xml_parser_free($parser); $mnary=array(); $ary=&$mnary; foreach ($vals as $r) { $t=$r['tag']; if ($r['type']=='open') { if (isset($ary[$t])) { if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array()); $cv=&$ary[$t][count($ary[$t])-1]; } else $cv=&$ary[$t]; if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;} $cv['_c']=array(); $cv['_c']['_p']=&$ary; $ary=&$cv['_c']; } elseif ($r['type']=='complete') { if (isset($ary[$t])) { // same as open if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array()); $cv=&$ary[$t][count($ary[$t])-1]; } else $cv=&$ary[$t]; if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;} $cv['_v']=(isset($r['value']) ? $r['value'] : ''); } elseif ($r['type']=='close') { $ary=&$ary['_p']; } } ArrayToXML::_del_p($mnary); return $mnary; } // _Internal: Remove recursion in result array public static function _del_p(&$ary) { foreach ($ary as $k=>$v) { if ($k==='_p') unset($ary[$k]); elseif (is_array($ary[$k])) ArrayToXML::_del_p($ary[$k]); } } // Insert element into array public static function ins2ary(&$ary, $element, $pos) { $ar1=array_slice($ary, 0, $pos); $ar1[]=$element; $ary=array_merge($ar1, array_slice($ary, $pos)); } } }
-
∞ PHP Array to XML
<?php // // /* Example usage: =============== <library> <book> <authorFirst>Mark</authorFirst> <authorLast>Twain</authorLast> <title>The Innocents Abroad</title> </book> <book> <authorFirst>Charles</authorFirst> <authorLast>Dickens</authorLast> <title>Oliver Twist</title> </book> </library> ================= $library = array( 'book' => array( array( 'authorFirst' => 'Mark', 'authorLast' => 'Twain', 'title' => 'The Innocents Abroad' ), array( 'authorFirst' => 'Charles', 'authorLast' => 'Dickens', 'title' => 'Oliver Twist' ) ) ); header('Content-Type: application/xml'); echo ArrayToXML::toXML($library, 'library'); */ class ArrayToXML { /** * The main function for converting to an XML document. * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document. * * @param array $data * @param string $rootNodeName - what you want the root node to be - defaultsto data. * @param SimpleXMLElement $xml - should only be used recursively * @return string XML */ public static function toXML( $data, $rootNodeName = 'ResultSet', &$xml=null ) { // turn off compatibility mode as simple xml throws a wobbly if you don't. if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 ); if ( is_null( $xml ) ) //$xml = simplexml_load_string( "" ); $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />"); // loop through the data passed in. foreach( $data as $key => $value ) { $numeric = false; // no numeric keys in our xml please! if ( is_numeric( $key ) ) { $numeric = 1; $key = $rootNodeName; } // delete any char not allowed in XML element names $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key); // if there is another array found recrusively call this function if ( is_array( $value ) ) { $node = ArrayToXML::isAssoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml; // recrusive call. if ( $numeric ) $key = 'anon'; ArrayToXML::toXml( $value, $key, $node ); } else { // add single node. $value = htmlentities( $value ); $xml->addChild( $key, $value ); } } // pass back as XML return $xml->asXML(); // if you want the XML to be formatted, use the below instead to return the XML //$doc = new DOMDocument('1.0'); //$doc->preserveWhiteSpace = false; //$doc->loadXML( $xml->asXML() ); //$doc->formatOutput = true; //return $doc->saveXML(); } /** * Convert an XML document to a multi dimensional array * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array * * @param string $xml - XML document - can optionally be a SimpleXMLElement object * @return array ARRAY */ public static function toArray( $xml ) { if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml ); $children = $xml->children(); if ( !$children ) return (string) $xml; $arr = array(); foreach ( $children as $key => $node ) { $node = ArrayToXML::toArray( $node ); // support for 'anon' non-associative arrays if ( $key == 'anon' ) $key = count( $arr ); // if the node is already set, put it into an array if ( isset( $arr[$key] ) ) { if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] ); $arr[$key][] = $node; } else { $arr[$key] = $node; } } return $arr; } // determine if a variable is an associative array public static function isAssoc( $array ) { return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array))))); } }
-
∞ Enable SOAP on Media Temple DV server
# Navigate to a relatively unimportant directory. I chose /home/ cd /home/ # Download PHP (http://www.php.net/releases/) wget http://museum.php.net/php5/php-5.2.6.tar.gz # Unpack the PHP file tar -zxf php-5.2.6.tar.gz # Configure the new PHP to enable SOAP (will take a few minutes) (before enable is two dashes) cd php-5.2.6 ./configure --enable-soap=shared # Rebuild PHP (this will also take a while) make # Copy just the SOAP module into your existing installation of PHP cp modules/soap.so /usr/lib/php/modules/ # Add the new SOAP configuration to your existing configuration echo "extension=soap.so" > /etc/php.d/soap.ini # Restart Apache /etc/init.d/httpd restart # Optional: You can now delete /home/php-5.2.6/ if you’d like, as you won’t need it any longer. rm -rf /home/php-5.2.6/ # Check phpinfo() to confirm that SOAP is now enabled.
-
∞ Dates Samples
<?php $currDate = date('Y-m-d h:i:s'); // convert timestamp from mysql $nextReviewDt = date('F d, Y',strtotime($nextReviewDt)); // Add 30 days $CommentStartDt = date('m/d/Y'); $CommentEndDt = date('m/d/Y', mktime(0,0,0,date("m"),date("d")+30,date("Y"))); // add 30 days // convert year to 4 digits if ($y > 60) $y = '19'.$y; else $y = '20'.$y; // split if there are slash or dash list($m, $d, $y) = split('[/|-]', $iDate); if (preg_match("/-/", $iDate)) list($m, $d, $y) = split('-', $iDate); else if (preg_match("/\//", $iDate)) list($m, $d, $y) = split('/', $iDate); $specDate = mktime(0, 0, 0, $m, $d, $y); $numOfDays = (time() - $specDate) / (24 * 60 * 60); // convert date from mysql db if (preg_match("/(.*)Dt$/", $dbDate)) $dbDate = date("M d, Y h:ia", strtotime($dbDate)); // output dates - walk the days $startDt = '2009-01-04'; $endDt = date('Y-m-d'); while ($startDt != $endDt) { echo "$startDt <br/>"; // increment the day $startDt = strtotime(date("Y-m-d", strtotime($startDt)) . " +1 day"); // convert back to readable format $startDt = date("Y-m-d",$startDt); } function count_days( $a, $b ) { // First we need to break these dates into their constituent parts: $gd_a = getdate( $a ); $gd_b = getdate( $b ); // Now recreate these timestamps, based upon noon on each day // The specific time doesn't matter but it must be the same each day $a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] ); $b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] ); // Subtract these two numbers and divide by the number of seconds in a // day. Round the result since crossing over a daylight savings time // barrier will cause this time to be off by an hour or two. return round( abs( $a_new - $b_new ) / 86400 ); }
-
∞ Pagination for PHP
<div id='pagination'> <span class='curr'>Page <?php echo $page; ?> of <?php echo $totalPages; ?></span> <?php $range = 3; // build previous page if ($page > 1) echo "<span><a href='{$_SERVER['PHP_SELF']}?page=".($page-1)."'>Previous</a></span> "; // build range pages $stop = ($page + $range) + 1; for ($x=($page-$range); $x<$stop; $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalPages)) { if ($x == $page) echo "<span class='curr'>$x</span> "; else echo "<span><a href='{$_SERVER['PHP_SELF']}?page=$x'>$x</a></span> "; } } // build last page if ($stop <= $totalPages) echo "... <span><a href='{$_SERVER['PHP_SELF']}?page=$totalPages'>$totalPages</a></span> "; // build next page if ($page != $totalPages) echo "<span><a href='{$_SERVER['PHP_SELF']}?page=".($page+1)."'>Next</a></span>"; ?> </div>
-
∞ PHP Recursive Sort
<?php // Notice the & symbol in the args and in the FOREACH. // Omitting the & in the FOREACH will not save the sorts! private function recursSort(&$tree) { asort($tree); foreach ($tree as &$t) { if ($t['children'] != '') { $t['children'] = $this->recursSort($t['children']); } } return $tree; }
-
∞ Correct way to do Pagination in Zend
<? //In other words, instead of this: $select= $this->db->select()->from( 'runz_miles', 'EMPL_NO')->where('empl_no = ?', 31713); $this->view->result = $this->db->fetchAll($sql); $paginator = Zend_Paginator::factory($this->view->result); //Do this: $select= $this->db->select()->from( 'runz_miles', 'EMPL_NO')->where('empl_no = ?', 31713); $paginator = Zend_Paginator::factory($select);
-
∞ Command line PHP with args
<?php // processing php arguments if (count($argv) < 2) die("Error 1: arg1 should be filename"); $filename = $argv[1]; // allow only letters and dot if (preg_match("/[^A-Za-z0-9.]/", $filename) || preg_match("/[.]{2,}/", $filename)) die('Error 2'); // Example usage: // /usr/bin/php -f <phpscript.php> file.txt
-
∞ Regex: Date format
<? // Date must match format: mm/dd/yyyy if (!preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $due_date)) echo "Error !";
-
∞ Read CSV File
<? $fp = fopen($csv_file,'r'); while (($data = fgetcsv($fp, 1000, ",")) !== false) { // make sure we all 6 columns and it isn't the header if (count($data) == 6 && $data[0] != 'Name') { // extract the data $name = $data[0]; } } fclose($fp);
-
∞ XML (Simple XML) parse
<? ============================== XML stuff (simple parse) // simple xml way // set the XML file name as a PHP string $myGroceryList = "output.xml" ; // load the XML file $xml = @simplexml_load_file($myGroceryList) or die ("no file loaded"); // or load the string $xml = @simplexml_load_string($blah_string) or die ("error loading"); echo var_export($xml); foreach ($xml->foodGroup as $foodGroup) { echo "<h2>Food group name is " . $foodGroup->groupName . "</h2>" ; foreach ($foodGroup->item as $foodItem) { echo "<br /> Item: " . $foodItem->name ; echo "<br /> Quantity: " . $foodItem->howMuch ; echo "<br />" ; } echo "<br />" ; }
-
∞ XML (SAX Parse) for PHP
<? ============================== XML stuff (sax parse) // parse xml and store into array $xml_parser = xml_parser_create(); xml_set_element_handler($xml_parser, "startTag", "endTag"); xml_set_character_data_handler($xml_parser, "xmlEngine"); $fp = fopen('xml/'.$xmlFile, "r") or die("Could not open file"); // rbanh comment: apparently, for large sets of data the sax xml parser // tend to truncate data. So I'll have to create my own buffer to // increase the size. $bufferCounter = 0; $bufferStorage = ''; while( $data = fread( $fp, 8192 ) ) { if ($bufferCounter % 2) { $bufferStorage .= $data; xml_parse( $xml_parser, $bufferStorage ); $bufferStorage = ''; } else $bufferStorage = $data; $bufferCounter++; } // make sure there isn't any more in the buffer if ($bufferStorage != '') xml_parse( $xml_parser, $bufferStorage ); xml_parser_free($xml_parser); fclose($fp);
-
∞ php error checking
<? // ============== // error checking // ============== if ($xmlFile === false) die('1'); // max char length if (isset($xmlFile{201})) die('File name too long'); // regex check for chars, numbers, periods, dash, and underscores only // also make sure there isn't 2 or more period next to each other. if (preg_match("/[^A-Za-z0-9_.\-]/", $xmlFile) || preg_match("/[.]{2,}/", $xmlFile)) die('2'); // check if extension is xml if (!preg_match("/[.]xml$/", $xmlFile)) die('3'); // check if file exist if (!file_exists($_SERVER['DOCUMENT_ROOT']."/blah/$xmlFile")) die('File does not exist.');


