Reply LinkBack Thread Tools Search this Thread
Old 26-06-2007, 11:31   #1 (permalink)
pgo
Moderator
 
pgo's Avatar
 
Join Date: Jan 2005
Location: Brooklyn, NYC
Posts: 11,869
share your php functions

I thought this would be a good idea. Let's share our PHP functions! Handy bits of code that can improve our work.

Here's some basic ones.

A function for determining the "end of line". Just echo $eol wherever you want a line break in your HTML source.

PHP Code:
if(strtoupper(substr(PHP_OS,0,3)=='WIN')) {
    
$eol="\r\n";
} elseif(
strtoupper(substr(PHP_OS,0,3)=='MAC')) {
    
$eol="\r";
} else {
    
$eol="\n";


Or a function for cleaning post input - stripping tabs, carriage returns, and new lines and such. It also adds escaping slashes if get_magic_quotes_gpc is false.

PHP Code:
function clean_input($variable) {
    if (!
get_magic_quotes_gpc()) {
        
$cleaned addslashes(trim($variable));
    } else {
        
$cleaned trim($variable);
    }
    return 
$cleaned;


And the MySQLi database connection function I usually use is...

PHP Code:
function db_connect($config) {
    
$db_conn = new mysqli($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
    if (
mysqli_connect_errno()) {
        echo 
'Connection to database failed:'.mysqli_connect_error();
        exit();
    } else {
        return 
$db_conn;
    }    

Most of these functions are modified from various sources around the web.
__________________
  Reply With Quote
Old 26-06-2007, 12:09   #2 (permalink)
freelancr
Web Developer
 
freelancr's Avatar
 
Join Date: Oct 2006
Location: Stratford-upon-Avon, Warwickshire, UK
Posts: 1,848
Send a message via MSN to freelancr Send a message via Skype™ to freelancr
For your first one wouldn't it be more efficient to add \r\n every time you want a line break? It is the same amount of typing, and works on any platform.
  Reply With Quote
Old 26-06-2007, 13:17   #3 (permalink)
Bill Posters
trouble free and loverlee
 
Join Date: Mar 2003
Location: YooKay
Posts: 2,854
Simple, but I found it useful when htmlspecialchars() and htmlentities() weren't doing the trick in an entirely utf-8, multi-lingual XML file:

PHP Code:
function xmlspecialchars($str) {

    return 
str_replace(''',''',htmlspecialchars($str,ENT_QUOTES,'UTF-8'));



Probably flawed, but worked for me when I needed it.
  Reply With Quote
Old 26-06-2007, 14:12   #4 (permalink)
pgo
Moderator
 
pgo's Avatar
 
Join Date: Jan 2005
Location: Brooklyn, NYC
Posts: 11,869
Quote:
Originally Posted by freelancr
For your first one wouldn't it be more efficient to add \r\n every time you want a line break? It is the same amount of typing, and works on any platform.
Don't recall. Saw it on PHP.net as part of someone's custom mail function.
__________________
  Reply With Quote
Old 26-06-2007, 19:14   #5 (permalink)
Cborrow
I like code.
 
Join Date: Dec 2004
Location: Chesapeake, VA
Posts: 175
Send a message via AIM to Cborrow
For when you need to convert colors from/to rbg/hex

PHP Code:
function FromHex($color) {
    
$color ereg_replace("#"""$color);

    if(
strlen($color) == 3) {
        
$color  $color $color;
    }

    
$red hexdec(substr($color02));
    
$green hexdec(substr($color22));
    
$blue hexdec(substr($color42));

    return array(
$red$green$blue);
}
        
function 
FromRGB($color) {
    
$red $color['red'] || $color[0];
    
$blue $color['blue'] || $color[1];
    
$green $color['green'] || $color[2];
    
    
$red dechex($red);
    
$green dechex($green);
    
$blue dechex($blue);
    
    return 
"#" $red $green $blue;

  Reply With Quote
Old 28-06-2007, 05:33   #6 (permalink)
Naatan
Web Developer
 
Naatan's Avatar
 
Join Date: Jan 2007
Location: Brussels
Posts: 214
Send a message via MSN to Naatan
Some usefull functions there

Function to get the user IP, since one single technique doesn't always work

PHP Code:
function get_IP() {
    if (empty(
$_SERVER["HTTP_X_FORWARDED_FOR"])) {
        
$ip_address $_SERVER["REMOTE_ADDR"];
    } else {
        
$ip_address $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    if(
strpos($ip_address',') !== false) {
        
$ip_address explode(','$ip_address);
        
$ip_address $ip_address[0];
    }
    return 
$ip_address;


Or this one I got from another site, I don't remember where, it treats a string as if it is included by include();

Only downside is that you can't declare functions since it's already inside a function.

PHP Code:
function phpWrapper($content) {
    global 
$page;
    
ob_start();
    
$content str_replace('<'.'?php','<'.'?',$content);
    eval(
'?'.'>'.trim($content).'<'.'?');
    
$content ob_get_contents();
    
ob_end_clean();
    return 
$content;


Or a function to echo a string and immediatly echo it without delay

PHP Code:
function _echo($echo) {
    echo 
$echo;
    
flush();
    
ob_flush();


This one transforms a filename into a clean string, to be used as a title or whatever (for example, go_go_gadget.exe becomes "Go go gadget"

PHP Code:
function get_filetotitle($title) {
    
$title strip_path($title);
    
$title str_replace('_',' ',$title);
    
$title substr($title0strrpos($title'.'));
    
$bits explode(' ',$title);
    foreach (
$bits AS $bit) {
        
$return .= capitalize_firstchar($bit);
    }
    return 
$return;
}

function 
capitalize_firstchar($string) {
    return 
strtoupper(substr($string,0,1)).substr($string,1);

__________________
Developer of Divia CMS,
More info? Visit my blog.
  Reply With Quote
Old 05-08-2007, 10:22   #7 (permalink)
pgo
Moderator
 
pgo's Avatar
 
Join Date: Jan 2005
Location: Brooklyn, NYC
Posts: 11,869
Something new for you gents. Not a function, but a handy item in a function I'm working on.

An array of (presumably) all the TLDs.

PHP Code:
$tlds = array('.aero','.biz','.cat','.com','.coop','.edu','.gov','.info','.int','.jobs','.mil','.mobi','.museum','.name','.net','.org','.travel','.ac','.ad','.ae','.af','.ag','.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw','.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm','.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc','.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr','.cs','.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz','.ec','.ee','.eg','.eh','.er','.es','.et','.eu','.fi','.fj','.fk','.fm','.fo','.fr','.ga','.gb','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm','.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gw','.gy','.hk','.hm','.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq','.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki','.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li','.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.me','.mg','.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt','.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng','.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf','.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py','.qa','.re','.ro','.rs','.ru','.rw','.sa','.sb','.sc','.sd','.se','.sg','.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.su','.sv','.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tl','.tm','.tn','.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um','.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.wf','.ws','.ye','.yt','.yu','.za','.zm','.zr','.zw'); 
__________________
  Reply With Quote
Old 05-08-2007, 12:34   #8 (permalink)
freelancr
Web Developer
 
freelancr's Avatar
 
Join Date: Oct 2006
Location: Stratford-upon-Avon, Warwickshire, UK
Posts: 1,848
Send a message via MSN to freelancr Send a message via Skype™ to freelancr
Here are a few I use a lot. Not mine, but found them on various websites.

MySQL to PHP datetime converter:
PHP Code:
function datetime($syntax,$datetime)
{
    
$year substr($datetime,0,4);
    
$month substr($datetime,5,2);
    
$day substr($datetime,8,2);
    
$hour substr($datetime,11,2);
    
$min substr($datetime,14,2);
    
$sec substr($datetime,17,2);

    return 
date($syntax,mktime($hour,$min,$sec,$month,$day,$year));


Escape Data:
PHP Code:
function escape_data($data)
{
    global 
$con;
    
    if (
ini_get('magic_quotes_gpc'))
    {
        
$data stripslashes($data);
    }
    
    return 
mysql_real_escape_string(trim($data), $con);


Validate E-Mail Address:
PHP Code:
function validateEmail($email)
{
    
// First, we check that there's one @ symbol, and that the lengths are right
    
if (!ereg("^[^@]{1,64}@[^@]{1,255}$"$email))
    {
        
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        
return false;
    }
    
    
// Split it into sections to make life easier
    
$email_array explode("@"$email);
    
$local_array explode("."$email_array[0]);
    
    for (
$i 0$i sizeof($local_array); $i++)
    {
        if (!
ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$"$local_array[$i]))
        {
            return 
false;
        }
    }
    
    if (!
ereg("^\[?[0-9\.]+\]?$"$email_array[1]))
    {
        
// Check if domain is IP. If not, it should be valid domain name
        
$domain_array explode("."$email_array[1]);
        
        if (
sizeof($domain_array) < 2)
        {
            return 
false// Not enough parts to domain
        
}
        
        for (
$i 0$i sizeof($domain_array); $i++)
        {
            if (!
ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$"$domain_array[$i]))
            {
                return 
false;
            }
        }
    }
    
    return 
true;

__________________
  Reply With Quote
Old 30-08-2007, 17:04   #9 (permalink)
pgo
Moderator
 
pgo's Avatar
 
Join Date: Jan 2005
Location: Brooklyn, NYC
Posts: 11,869
Similar to your datetime function, I wrote one today that takes a datetime ("YYYY-MM-DD HH:MM:SS") and breaks it up into its constituent parts and returns an array:

PHP Code:
function datetime_breakup($datetime)
{
    
$timestamp strtotime($datetime);
    
$date['y'] = date('Y'$timestamp);
    
$date['m'] = date('m'$timestamp);
    
$date['d'] = date('d'$timestamp);
    
$date['h'] = date('H'$timestamp);
    
$date['i'] = date('i'$timestamp);
    
$date['s'] = date('s'$timestamp);
    return 
$date;

__________________

Last edited by pgo : 30-08-2007 at 17:38.
  Reply With Quote
Old 30-08-2007, 23:03   #10 (permalink)
Web Surgeon
Registered User
 
Join Date: Aug 2007
Location: Toronto, Canada
Posts: 16
I like functions that work like this in my class'
PHP Code:
public function loadUserInfo($userid$return='*'){
     global 
$db$config;

  
$get $db->query("SELECT $return FROM $config->table_user WHERE user_id='$userid'");
  
$row $db->fetch($get);

  foreach(
$row as $key => $val){
   
$new_key        substr($key5); //-- strip 'user_' from field names
   
$this->$new_key $val;
  }
 } 

Or in my layout class:
PHP Code:
public function includeCSS($css_files){
  
$css_files explode(","$css_files);

  foreach(
$css_files as $css_file){
   
$this->css_array[] = trim($css_file);
  }
 }

 private function 
writeCSS(){
  foreach(
$this->css_array as $css_file){
   echo 
'  <link type="text/css" rel="stylesheet" href="'.$this->css_folder.'/'.$css_file.'" />'."\n";
  }
 } 


And for testing $_POST, $_SESSION, $user, etc...
PHP Code:
function printReadable($array){
 echo 
"<pre>";
 
print_r($array);
 echo 
"</pre>";

  Reply With Quote
Old 05-09-2007, 16:33   #11 (permalink)
Cl1mh4224rd
Registered User
 
Join Date: Aug 2007
Posts: 2
PHP Code:
/**
 * A callback function to be used with array_walk(). Rather than having multiple
 * callbacks that share the same structure, I use "variable functions" so the
 * function to be applied to the value can be specified when array_walk() is
 * called. This function supports multidimensional arrays.
 *
 * Example: array_walk( $_POST, 'rml_aw_callback', 'htmlentities' );
 *
 * This will apply htmlentities() to EVERY value in the $_POST array.
 *
 * NOTE: If the callback is passed the name of a function that doesn't exist, it
 * will trigger an error and immediately return. This will happen for each
 * top-level value (i.e. subarrays will be passed over).
 */
function rml_aw_callback( &$value$key$function )
{
    
// Just in case someone decides to try and pass something other than a
    // string as the function name.
    
$function = (string)$function;

    
// Make sure the function exists before trying to call it. If it doesn't,
    // trigger an error and return immediately.
    
if( !function_exists$function ) ) {
        
trigger_error"rml_aw_callback(): Function \"{$function}\" does not exist"E_USER_ERROR );
        return;
    }

    if( !empty( 
$value ) ) {
     &