Useful PHP Functions

Comments 3 Standard

I ask myself why type the same thing over and over again when you can just use one function call? I’ve seen a lot of people do that, so stop it! Save yourself the trouble. Here are some things I use a lot:


<?php

/****
* Purpose: return a formatted error message
* Precondition: the message to display
* Postcondition: formatted message echoed to the screen
****/
function errorMsg($message)
{
return "<span class=\"errorMsg\"><center>Error: " . $message . "</center><br/></span>";
}

/****
* Purpose: gets the value of the given field
* Precondition: value and table are given, already connected to the database
* Postcondition: returns the field value
****/
function getValue($value, $table, $where)
{

if (!$value || !$table)
    return errorMsg("getValue incomplete query!<br/>
    Table: $table <br/>
    Where: $where <br/>
    Value: $value");

$value = htmlentities($value);

$query = "SELECT " . $value . " FROM " . $table . " " . $where;
$result = mysql_query($query) or die ('cannot get ' . $value . ": " . mysql_error());

$row = mysql_fetch_array($result);
return stripslashes($row[$value]);
}

/****
* Purpose: sets the field to the given value
* Precondition: value is given (-1 for no value), already connected to database
* Postcondition: field has been set to value
****/
function setValue($field, $value, $table, $where)
{

if (!$field || !$table)
    return errorMsg("setValue incomplete query!<br/>
    Field: $field <br/>
    Table: $table <br/>
    Where: $where <br/>
    Value: $value");

if ($value == -1)
$value = 0;

if ($value == "null" || $value == "NULL")
    $value = "";

$value = htmlentities($value);

$query = "UPDATE " . $table . " SET " . $field . "='" . $value . "' " . $where;
mysql_query($query) or die ('cannot set ' . $field . " where " . $where . ": " . mysql_error());

return html_entity_decode($value);
}

/****
* Purpose: display all server details
* Precondition: none
* Postcondition: server details displayed on the screen
****/
function serverDetails()
{
echo "Document Root: " . $_SERVER['DOCUMENT_ROOT'];
echo "<br/>";
echo "Gateway Interface: " . $_SERVER['GATEWAY_INTERFACE'];
echo "<br/>";
echo "Http Accept: " . $_SERVER['HTTP_ACCEPT'];
echo "<br/>";
echo "Http Accept Charset: " . $_SERVER['HTTP_ACCEPT_CHARSET'];
echo "<br/>";
echo "Http Accept Encoding: " . $_SERVER['HTTP_ACCEPT_ENCODING'];
echo "<br/>";
echo "Http Accept Language: " . $_SERVER['HTTP_ACCEPT_LANGUAGE'];
echo "<br/>";
echo "Http Connection: " . $_SERVER['HTTP_CONNECTION'];
echo "<br/>";
echo "Http Host: " . $_SERVER['HTTP_HOST'];
echo "<br/>";
echo "Http Referrer: " . $_SERVER['HTTP_REFERER'];
echo "<br/>";
echo "Http User Agent: " . $_SERVER['HTTP_USER_AGENT'];
echo "<br/>";
echo "Path Translated: " . $_SERVER['PATH_TRANSLATED'];
echo "<br/>";
echo "Php Self: " . $_SERVER['PHP_SELF'];
echo "<br/>";
echo "Query String: " . $_SERVER['QUERY_STRING'];
echo "<br/>";
echo "Remote Address: " . $_SERVER['REMOTE_ADDR'];
echo "<br/>";
echo "Remote Port: " . $_SERVER['REMOTE_PORT'];
echo "<br/>";
echo "Request Method: " . $_SERVER['REQUEST_METHOD'];
echo "<br/>";
echo "Request Uri: " . $_SERVER['REQUEST_URI'];
echo "<br/>";
echo "Script Filename: " . $_SERVER['SCRIPT_FILENAME'];
echo "<br/>";
echo "Script Name: " . $_SERVER['SCRIPT_NAME'];
echo "<br/>";
echo "Server Admin: " . $_SERVER['SERVER_ADMIN'];
echo "<br/>";
echo "Server Name: " . $_SERVER['SERVER_NAME'];
echo "<br/>";
echo "Server Port: " . $_SERVER['SERVER_PORT'];
echo "<br/>";
echo "Server Protocol: " . $_SERVER['SERVER_PROTOCOL'];
echo "<br/>";
echo "Server Signature: " . $_SERVER['SERVER_SIGNATURE'];
echo "<br/>";
echo "Server Software: " . $_SERVER['SERVER_SOFTWARE'];
}

/****
* Purpose: get the filename from the path
* Precondition: path i.e. http://domain.com/contacts.php
* Postcondition: returns the filename i.e. contacts.php
****/
function fileName($path)
{
return substr($path, strrpos($path, '/')+1, strlen($path));
}

/****
* Purpose: return a formatted success message
* Precondition: the message to display
* Postcondition: formatted message echoed to the screen
****/
function successMsg($message)
{
return "<span class=\"successMsg\"><center>Success! ". $message . "</center><br/></span>";
}

/****
* Purpose: checks to see if this is a valid email address
* Precondition: email to check
* Postcondition: returns true if email has @ and . in it
****/
function validEmail($email)
{
if (strstr($email, '@') && strstr($email, '.'))
return true;
return false;
}

/****
* Purpose: get the users IP address
* Precondition: none
* Postcondition: ip returned
****/
function getIP()
{
$ip = 0;

if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else
$ip = getenv("REMOTE_ADDR");

return $ip;
}

/****
* Purpose: turn this file into an img src html, scaled down porportionally to defined max
* Precondition: url of file
* Postcondition: file is now in img src form at correct porportions
****/
function thumbnail($file)
{
$max = 84; // Max. thumbnail width and height

$size = getimagesize($file);

if ( $size[0] <= $max && $size[1] <= $max )
$ret = '<img src="'.$file.'" '.$size[3].' border="0" hspace=10>';
else
{
$k = ( $size[0] >= $size[1] ) ? $size[0] / $max : $size[1] / $max;
$ret .= '<img src="'.$file.'" width="'.floor($size[0]/$k).'" height="'.floor($size[1]/$k).'" border="0" hspace=10>';
}

return $ret;
}

/****
* Purpose: remove specific html tags from text
* Precondition: text to remove them from
* Postcondition: non-allowed tags have been stripped
****/
function removeTags($source)
{
$allowedTags='<br><b><h1><h2><h3><h4><i>' .
'<li><ol><p><strong><table>' .
'<tr><td><th><u><ul><center>';
$source = strip_tags($source, $allowedTags); //remove all tags that aren't allowed
return preg_replace('/<(.*?)>/ie', "'<'.removeTags('\\1').'>'", $source);
}

/****************
* Purpose: randomly generates a number
* 11 digits long, and is in the pattern commented below
****************/
function generateKey()
{
$key = rand(100, 999); //random 3 digit number
$key .= chr(rand(65, 90)); //upper case letter
$key .= rand(10, 99); //2 digit number
$key .= chr(rand(97, 122)); //lowercase number
$key .= chr(rand(97, 122)); //lowercase number
$key .= rand(10, 99); //2 digit number
return $key .= chr(rand(65, 90)); //upper case letter
}

/****
* Purpose: delete object from an array
* Precondition: array contains objects of same type, objects have an ID variable,
* id of object to delete is given
* Postcondition: object with specified id is removed from array
****/
function deleteObjectFromArray($array, $objectid)
{
$count = 0;

foreach ($array as $object)
{
    if ($object->id == $objectid)
        break;
$count++;
}

//remove object from array
$top = array_slice($array, 0, $count);
$bottom = array_slice($array, $count+1, sizeof($array));
$array = array_merge($top, $bottom);
return $array;
}

/****
* Purpose: find and return object from an array
* Precondition: array contains object, each object has an ID variable
* Postcondition: object is returned
****/
function findObject($array, $id)

{

foreach ($array as $object)
{
    if ($object->id == $id)
      return $object;
}
}
?>



Advertisements

3 thoughts on “Useful PHP Functions

  1. Nice article!

    I always try to name my functions with a verb, so instead of errorMsg() I say makeErrorMsg(). I see that you do that a lot as well.

    Functions that return a boolean can mostly be named with “is” in the name validEmail –> isValidEmail. This makes your code really readable.

    if(isValidEmail($email))
    {
    sendMail($email,$foo,$bar);
    }
    else
    {
    displayErrorMsg(‘Invalid email’);
    }

    Other examples: isChecked(), isOlderThanLimit(), hasBodyParts(array(‘ears’,’eyes’)). etc..

    I’d also like to stress that function names really and specifically should explain what they do. A function called getValue() is quite vague. I’d have to read the function to see what it does, (imho) a better name would be getValueFromTable(), because that’s more descriptive.

    What I also try to do is abstract my functions as much as possible so I can (more) easily reuse them. Your thumbnail function has a certain value for thumbnails in it. If you’d ever want to have different sizes thumbnails you’d have to change the function, or make a new one. What I would have done is give an argument for the size of the thumbnail. In the configuration file for the application I would have defined the standard size for the thumbnail.

    Also don’t forget the classes and libraries you can find on the web, you can find a lot of excellent code in the PEAR website. pear.php.net
    It gives you a lot of excellent code which you can immediately use on your site, like http://pear.php.net/package/Image_Transform which is ideal for resizing images, like thumbnails.

    What might also be a good idea for displaying code in your blog is the Geshi plugin. http://plugins.trac.wordpress.org/wiki/GeshiSyntaxColorer

    Happy coding!

  2. Thanks for the feedback.

    I try to make my function names as short as possible but as readable as possible. I don’t see a point in writing isValidEmail when ValidEmail() that’s a boolean is pretty obvious to me in terms of what it does.

    I agree with what you’re saying with the getValue/setValue functions. They’re usually a part of a DB class that I’ve created so it’s more along the lines of $db->getValue() and in that case I don’t feel it needs anything more descriptive.

    Abstracting a function, if I never intend to use under any other circumstances just makes it more of a pain to call. Why enter 12 fields when you only really plan on using one?

    PHP libraries… not all servers have those libraries. It’s a good practice to have these basic functions in case you run into a situation with a client where the library is not available. It’s not acceptable to say to someone whose paying you thousands of dollars for a website “I can’t resize this image because you don’t have the PEAR library.”

    Thanks for letting me know about the Geshi plugin. I’ll give it a go.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s