Public snipts »
robertbanh's
snipts
showing 1-20 of 44 snipts
-
∞ Magento SQL example
<?php // magento sql // public function abc($type) { $type = strtolower($type); $validType = array( 'temp', ); if (in_array($type, $validType)) { $sql = "SELECT * FROM aaa WHERE bbb='$type' and status = '1' ORDER BY aaa_id desc"; $data = Mage::getSingleton('core/resource') ->getConnection('core_read')->fetchAll($sql); if (!empty($data)) return current($data); else return array(); } }
-
∞ .htaccess file to lock down files with db or secure in the prefix
<FilesMatch "^(db|secure).*$"> deny from all </FilesMatch> -
∞ 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.
-
∞ Cron job example
# This will kick off a cron job at 2:07am. which $EDITOR EDITOR=vi export EDITOR crontab -e MAILTO="bbb@bbb.com" 7 2 * * * /usr/local/bin/php -f /home/bbb/cron.php crontab -l
-
∞ Rewrite .cfm files to files with .cfm
RewriteEngine On Options -Indexes # redirect all .cfm files to files without .cfm RedirectMatch 301 ^(.*)\index.cfm$ $1 RedirectMatch 301 ^(.*)\.cfm$ $1
-
∞ Get client IP through jquery
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){ alert( "Your ip: " + data.ip); });
-
∞ config.php for EE
<?php if ( ! defined('EXT')){ exit('Invalid file request'); } $conf['app_version'] = "168"; $conf['license_number'] = ""; $conf['debug'] = "1"; $conf['install_lock'] = "1"; $conf['db_hostname'] = "[mysql server]"; // Note: Must use the super admin since EE will // alter and add/remove columns. $conf['db_username'] = "xxxx"; $conf['db_password'] = "xxxx"; $conf['db_name'] = "xxx"; $conf['db_type'] = "mysql"; $conf['db_prefix'] = "exp"; $conf['db_conntype'] = "0"; $conf['system_folder'] = "[system folder name]"; $conf['cp_url'] = "http://[server]/[system]/index.php"; $conf['doc_url'] = "http://expressionengine.com/docs/"; $conf['cookie_prefix'] = ""; $conf['is_system_on'] = "y"; $conf['allow_extensions'] = "y"; $conf['multiple_sites_enabled'] = "n"; // rbanh: this is for migration: $conf['site_url'] = "http://[server]/"; $conf['tmpl_file_basepath'] = $conf['site_url'] . $conf['system_folder'] . "/templates/"; $conf['theme_folder_url'] = $conf['site_url'] . "themes/"; $conf['theme_folder_path'] = $conf['site_url'] . "themes/"; $conf['captcha_path'] = $conf['site_url'] . "images/captchas/"; $conf['captcha_url'] = $conf['site_url'] . "images/captchas/"; $conf['avatar_path'] = $conf['site_url'] . "images/members/avatars/"; $conf['avatar_url'] = $conf['site_url'] . "images/members/avatars/"; ?>
-
∞ Sum of 2 columns with alias
# remove the group by if you want 1 total row returned. # select *, sum(s1.score+s2.score) total from search_score s1 inner join search_word w1 on s1.word_id = w1.id inner join search_score s2 on s1.sp_id = s2.sp_id and s1.id != s2.id inner join search_word w2 on s2.word_id = w2.id where w1.word = 'zinc' and w2.word = 'soft' group by s1.id order by total desc limit 50 # updated note: if this will span more then 2 and goes nth level, then it's # faster to run each word search separately. unset vars as needed.
-
∞ Rewrite .htaccess to EE's engine if directory conflicts with existing directory
RewriteEngine On RewriteBase / # if the file/dir does not exist, append index.php # which will call EE and pull up it's structured url RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/interact/$1 [L]
-
∞ 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 ); }
-
∞ Count Monthly/Yearly Totals in MySQL
SELECT MONTHNAME(createDt) AS month, YEAR(createDt) AS year, COUNT(*) AS total FROM tracking GROUP BY MONTH(createDt), YEAR(createDt) ORDER BY id
-
∞ Use found_rows() in MySQL
// use found_rows() as a sql function mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name -> WHERE id > 100 LIMIT 10; mysql> SELECT FOUND_ROWS();
-
∞ 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>
-
∞ Set up mail forwarding on linux
# add a .forward file to your home directory touch .forward # add your email address vi .forward <user>@<mail>.com # change permission else it won't work chmod 600 .forward # test mail send, replace 'user' with your login mailx -s 'test from cluster' user < /dev/null
-
∞ My Custom .htaccess file
RewriteEngine On #comment out the options followsymlinks when in prod #Options +ExecCGI +FollowSymLinks RewriteBase /rbanh/blah/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [L,QSA] # prevent directory browsing Options -Indexes <FilesMatch "\.(htaccess|svn|xml|inc|.*sql|cache_|.*~)$"> deny from all </FilesMatch>
-
∞ remove newline chars in vi
:%s/^v<Carriage Return>//g *hit the ctrl key + v then hit the carriage return.
-
∞ linux AT command
// linux at command > at 03:30 -v > nohup php -f /x/x/x.php > /x/x/logs > nohup php -f /rg/repos/trunk/import/importxx-2009.php > ~rbanh/importlogs2009 > (Ctrl+D) > atq // to view queue > atrm 1 // cancel job 1 > at 1am tomorrow -v // tomorrow 1am



MySQL in a Nutshell