Home | About | Web Stories | View All Posts

22 Aug 2014

Reusable custom or user defined PHP functions

User defined functions are created to fulfill specific need of PHP application. These functions output depends on many usable built-in PHP functions also.

These user defined functions(udf) have been prepared and written on the basis of daily uses of PHP functionality in different PHP oriented applications. Each function has been commented well for easy understanding with uses example. One can use it as inclusion in the application as example below which have been written to test excerpt or intro text output -
<?php
ob_start();//It suppress "Header already sent" error.
require('udf.php');
$art = "<img src='http://www.google.com' />Test for parsing html code in excerpt<strong>test</strong> simply dummy text";
echo udf_excerpt($art, 20, '...');
ob_end_flush();//It suppress "Header already sent" error.
?>

Short explanation of each functions has been written below:

udf_connect_db_server()
It is used to get database server connection status. It returns connection boolean parameter as 1 or 0.

udf_connect_n_show_table_data()
It is used to display data output rows of a given table. A sample output of 'node' table of Drupal database has been given below -


udf_tables_of_database()
It produces 'tables name list' of a database with total number of available tables.

udf_fields_detail_of_table()
It produces 'fields list of a table' with detail as name, length, type, and flag

udf_mail()
It produces status of mail sending actitivity.

udf_excerpt()
It produces custom character length of texts only i.e. it will not show HTML tags with word boundary.

udf_redirect()
It redirects to custom page url as given.

udf_clean()
It cleans or removes HTML tags in given texts string.

udf_date()
It outputs custom formatted date as given parameter.

udf_linear_to_assoc_array()
It produces an associative array from a linear array i.e you don't need to write array('one', 'two', 'three') into array('one=>one', 'two=>two', 'three=>three')

udf_active_css_class()
It produces an active class for current page view.

udf_set_error_message()
It produces a javascript alert to show message.

udf_set_message()
It produces a javascript alert to show message and set location target to custom page name.

udf_get_confirmation()
It produces a javascript confirmation alert to show message.

udf_css()
It prints styleshett link HTML tag at page.

udf_jscripts()
It prints javascript script HTML tag at page.

udf_popup()
It prints javascript pop up code at page. Popup is displayed at center of the screen.

udf_db_process()
It produces output as per process inputs - SELECT *, UPDATE, DELETE, INSERT INTO

Following are user defined functions code :
<?php
/**
* ********************************************************************************
* Collection of User Defined Functions - udf.php
* @uses - It can be used as included file in application like include('udf.php');
* ********************************************************************************
Functions Name List -
1. udf_connect_db_server()
2. udf_connect_n_show_table_data()
3. udf_tables_of_database()
4. udf_fields_detail_of_table()
5. udf_mail()
6. udf_excerpt()
7. udf_redirect()
8. udf_clean()
9. udf_date()
10.udf_linear_to_assoc_array()
11.udf_active_css_class()
12.udf_set_error_message()
13.udf_set_message()
14.udf_get_confirmation()
15.udf_css()
16.udf_jscripts()
17.udf_popup()
18.udf_db_process()
*/

/**
* Database Connection functions
*
* @param $host
* server host name or ip address like - localhost or 203.124.112.173
* @param $username
* server host username
* @param $password
* server host password
* @param $dbname
* database name
* @result
* produces connection boolean parameter as 1 OR 0 if database name is not provided.
* @uses $getconnection
* udf_connect_db_server("localhost","root","adminadmin");
*/
function udf_connect_db_server($host, $username, $password, $dbname=''){
$con = mysql_connect($host, $username, $password) or die('ERROR: ' . mysql_error());
if($dbname)
{
mysql_select_db($dbname, $con) or die('ERROR: '.mysql_error());
}else {
return $con;
}
}// end of function udf_connect_db_server()

/**
* Function for showing Data List of a Table in a Database
* @param $host
* server host name or ip address like - localhost or 203.124.112.73
* @param $username
* server host username
* @param $password
* server host password
* @param $dbname
* database name
* @param $tablename
* table name
* @param $limit
* number of rows to show at a page
* @param $additionalquery
* additional sql query can be appeded like - where, oreder by, join etc.
* @result
* produces rows of data of a table
* @uses
* udf_connect_n_show_table_data("localhost","root","adminadmin", "drupal_db", "node", '11', "where type='story'");
*/
function udf_connect_n_show_table_data($host, $username, $password, $dbname, $tablename, $limit='20', $additionalquery =''){
$con = mysql_connect($host, $username, $password);
if (!$con){die('ERROR: ' . mysql_error());}
mysql_select_db($dbname, $con);
$total_rows = mysql_num_rows(mysql_query("SELECT * FROM $tablename $additionalquery"));
$result_row = mysql_query("SELECT * FROM $tablename $additionalquery");
if(!$total_rows){echo "<strong>No Data found</strong>"; exit;}
echo '<table border="1" border-color="#999999" style="border:1px solid #999999;border-collapse:collapse;font-family:Arial, Helvetica, sans-serif; font-size:12px;">';
echo '<tr bgcolor="#eeeeee">';
$row = mysql_fetch_assoc($result_row, MYSQL_ASSOC);
foreach ($row as $col => $value) {
echo "<th>";
echo $col;
echo "</th>";
}
echo '</tr>';
if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$remaining_rows = $total_rows - ($page * $limit);
$result_rows = mysql_query("SELECT * FROM $tablename $additionalquery LIMIT $offset, $limit");
while($rows = mysql_fetch_array($result_rows, MYSQL_ASSOC))
{
echo '<tr>';
foreach($rows as $value){
echo '<td>';
echo $value;
echo '</td>';
}// end of foreach
echo '</tr>';
} // end of while
echo "</table>";
/////////////////////////Pager//////////////////
if($total_rows > $limit){
if(($page > 0) && ($remaining_rows > $limit ))
{
$last = $page - 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Previous</a> | ";
echo "<a href=\"$_PHP_SELF?page=$page\">Next</a>";
}
else if( $page == 0 )
{
echo "<a href=\"$_PHP_SELF?page=$page\">Next</a>";
}
else if( $remaining_rows < $limit )
{
$last = $page - 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Previous</a>";
}// end of ($page > 0) && ($remaining_rows > $limit )
}// end of if ($total_rows > $limit)statement
/////////////////////////Pager//////////////////
mysql_close($con);
}// end of function udf_connect_n_show_table_data()

/**
* Function to show tables name list of a database
* @param $host
* server host name or ip address like - localhost or 203.124.112.73
* @param $username
* server host username
* @param $password
* server host password
* @param $dbname
* database name
* @result
* produces tables name list of a database
* @uses
* udf_tables_of_database("localhost","root","adminadmin","drupalcontentslider");
*/
function udf_tables_of_database($host, $username, $password, $dbname){
$con = mysql_connect($host, $username, $password);
if (!$con){die('ERROR: ' . mysql_error());}
mysql_select_db($dbname, $con);
if (!mysql_select_db($dbname, $con)) { die ('ERROR : ' . mysql_error());}
$result = mysql_query("SHOW TABLES FROM $dbname");
if (!$result) {die('DB Error, could not list tables: ' .mysql_error());}
echo "<strong>Total No. of Tables : </strong>".mysql_num_rows($result);
echo "<br />";
echo "---------------------------";
echo "<br />";
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($rows as $value){
echo "<strong>Table Name: </strong>". $value;
echo "<br />";
}// end of foreach
}// end of while
mysql_close($con);
}// end of function udf_tables_of_database

/**
* Function to show fields detail(name, length, type, flag) of a table
* @param $host
* server host name or ip address like - localhost or 203.124.112.73
* @param $username
* server host username
* @param $password
* server host password
* @param $dbname
* database name
* @param $tablename
* table name
* @result
* produces fields list of a table with detail as name, length, type, and flag
* @uses
* udf_tables_of_database("localhost","root","adminadmin","drupal_db", node);
*/
function udf_fields_detail_of_table($host, $username, $password, $dbname, $tablename){
$con = mysql_connect($host, $username, $password);
if (!$con){die('ERROR: ' . mysql_error());}
$result = mysql_list_fields($dbname, $tablename);
for($i =0; $i< mysql_num_fields($result); $i++){
echo mysql_field_name($result, $i);
echo "(". mysql_field_len($result, $i). ")";
echo "-" . mysql_field_type($result, $i);
echo " " . mysql_field_flags($result, $i). "<br/>";
}// end of for loop
mysql_close($con);
}// end of function udf_fields_of_table()

/**
* Function to send mail using PHP built-in mail() function
* @param $to
* reciever email id
* @param $from
* sender email id
* @param $name
* sender name
* @param $subject
* mail subject texts
* @param $message
* mail message texts
* @result
* produces status of mail sending actitivity
* @uses
* $to = "yourname@gmail.com";$from = "admin@localhost.com";$name = "UserDefinedFunction";$subject = "Testing
* for user defined function";$message ="Hi, this is bold <strong>text</strong>";udf_mail($to, $from, $name, $subject, $message);
*/
function udf_mail($to,$from,$name,$subject,$message) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Form Submission <'.$to.'>' . "\r\n";
$headers .= 'From: '.$name.' <'.$from.'>' . "\r\n";
mail($to, $subject, $message, $headers) ? print('Mail has been sent successfully.') : die ("Your Mail could not be sent.");
//if(mail($to, $subject, $message, $headers)){return true;}else{return false;};
}// end of function udf_mail()

/**
* Function to show intro or excerpt texts only with word boundary(word will not be cropped)
* @param $article
* article texts or paragraph
* @param $character_limit
* number of characters(including space) to show for intro or excerpt
* @param $end_suffix
* tail character for intro or excerpt text
* @result
* produces custom length of texts only i.e. it will not show HTML tags.
* @uses
* $art = "<img src='http://www.google.com' />Lorem Ipsum is <strong>galley of type</strong> simply dummy
* text of the printing and typesetting industry.";echo udf_excerpt($art, 20, '>>');
*/
function udf_excerpt($article, $character_limit = 120, $end_suffix="..."){
$clean_article = strip_tags($article);
$output = substr($clean_article,0,strpos($clean_article,' ',$character_limit));
$output .= $end_suffix;
return $output;
}// end of function udf_excerpt()

/**
* Function for redirecting given page url
* @param $url
* target page url
* @result
* redirects to custom page url
* @uses
* $udf_redirect('thankyou.php');
*/
function udf_redirect($url){
if(!headers_sent()){//checks if/where the HTTP headers have been sent
header('Location: http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/'.$url);//show localhost+foldersname
}else{
die('Could not redirect: Headers already sent (output).');
}// end of if-else
}// end of udf_redirect()

/**
* Function for removing HTML tags
* @param $txt
* texts strings or sentences with HTML tags
* @result
* cleans or removes HTML tags in given texts string
* @uses
* $str = "<p>The quick brown fox <strong>jumps</strong> right over the lazy little dogg.</p>"; $udf_clean($str);
*/
function udf_clean($txt) {
$txt = strip_tags($txt);
return $txt;
}// end of udf_clean()

/**
* Functions for date format for a specific timestamp
* @param $type
* format of date like small, large, medium
* @param $timestamp
* time in seconds e.g. - 1407395608 - timestamp in seconds, The time() function returns the current time in the
number of seconds (like 1407395608 )since the Unix Epoch (January 1 1970 00:00:00 GMT).
* @result
* custom formatted date
* @uses
* $tstamp=1407395608;echo udf_date('large', $tstamp);
*/
function udf_date($type, $timestamp){
switch ($type) {
case 'small':
$format = 'm/d/Y - H:i';
break;
case 'large':
$format = 'l, F j, Y - H:i';
break;
case 'medium':
default:
$format = 'D, m/d/Y - H:i';
}// end of switch
return date($format, $timestamp);
}// end of function udf_date

/**
* Functions for array type converter
* @param $array
* a linear array for example array('one', 'two', 'three')
* @result
* produces an associative array from a linear array
* i.e you don't need to write array('one', 'two', 'three') into array('one=>one', 'two=>two', 'three=>three')
* @uses
* $arr=array('one', 'two', 'three'); echo udf_map_assoc($arr);
*/
function udf_linear_to_assoc_array($array) {
$result = array();
foreach ($array as $value) {
$result[$value] = $value;
}
return $result;
}// end of function udf_linear_to_assoc_array()

/**
* Functions for placing active or current class as per page view
* @param $filename
* page name like index.php, aboutus.php etc
* @result
* produces an active class for current page view
* @uses
* <p><a href="index.php" class="<?php echo udf_active('index.php'); ?>" >Home</a> | <a href="aboutus.php"
* class="<?php echo udf_active('aboutus.php'); ?>" >About Us</a> | <a href="contactus.php" class="<?php
* echo udf_active('contactus.php'); ?>" >Contact Us</a></p>
*/
function udf_active_css_class($filename){
$url = array_reverse(explode('/',$_SERVER['PHP_SELF']));
$filename==$url[0] ? print('active') : print('');
}// end of function udf_active_css_class()

/**
* Functions for displaying error message
* @param $message
* message text to show on page error
* @result
* produces a javascript alert to show message
* @uses
* $con = mysql_connect("localhsost","root","adminadmin"); if(!$con){udf_set_error_message(mysql_error());}
*/
function udf_set_error_message($message){
echo "<script>alert(\"ERROR: $message \");history.go(-1);</script>";
exit;
}// end of function udf_set_error_message()

/**
* Functions for displaying error message
* @param $message
* message text to show on page error
* @param $url
* page filename, it is optional value
* @result
* produces a javascript alert to show message and set location target to custom page name
* @uses
* udf_set_message("Your record has been added successfully", 'thankyou.php');
* @uses
* $str = "The quick brown fox 4F jumps right over";$result = ereg("[0-9][A-F]", $str);$result ? udf_set_message("Match
* Found"):udf_set_message("Match not Found");
*/
function udf_set_message($message, $url=''){
empty($url) ? print "<script>alert(\"$message \");history.go(-1)</script>" : print "<script>alert(\"$message \");self.location.href='$url'</script>";
exit;
}// end of function udf_set_message()

/**
* Functions for displaying confirmation message
* @param $message
* message text to show on page functionality event
* @result
* produces a javascript confirmation alert to show message
* @uses
* udf_get_confirmation("WARNING: Are you sure!");
*/
function udf_get_confirmation($message){
echo "<script>result = confirm(\"$message\");if(!result){history.go(-1);}</script>";
}// end of function udf_get_confirmation()

/**
* Functions for printing stylesheet link HTML tag at page
* @param $filename
* one or multiple stylesheet file name in comma separated format like default.css,slider.css etc.
* @param $foldername
* name of folder of stylesheet file
* @param $media
* media attribute for link tag like screen, all, tv, print etc.
* @result
* prints styleshett link HTML tag at page
* @uses
* udf_css('default.css, slider.css, reset.css','styles','screen');udf_css('print.css','print','styles');
*/
function udf_css($filename, $foldername='', $media='all'){
(!$foldername)? $foldernameout = $foldername : $foldernameout = $foldername."/";
$path="http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
$filename_in_array = explode(',', $filename);
$total_no_of_file = count($filename_in_array);
for($i=0; $i<$total_no_of_file; $i++){
echo "<link type=\"text/css\" rel=\"stylesheet\" media=\"$media\" href=\"$path/$foldernameout".trim($filename_in_array[$i])."\" />\n";
}// end of for loop
}// end of function udf_css()

/**
* Functions for printing javascript script HTML tag at page
* @param $filename
* one or multiple javascript file name in comma separated format like jquery.js, slider.js etc.
* @param $foldername
* name of folder of javascript file
* @param $defer
* defer attribute for script tag
* @result
* prints javascript script HTML tag at page
* @uses
* udf_jscripts('default.js, jquery.js', 'js'); udf_jscripts('default.js, jquery.js');
*/
function udf_jscripts($filename, $foldername='', $defer='defer'){
(!$foldername)? $foldernameout = $foldername : $foldernameout = $foldername."/";
$path="http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
$filename_in_array = explode(',', $filename);
$total_no_of_file = count($filename_in_array);
for($i=0; $i<$total_no_of_file; $i++){
echo "<script type=\"text/javascript\" src=\"$path/$foldernameout".trim($filename_in_array[$i])."\" defer=\"$defer\" ></script>\n";
}// end of for loop
}// end of function udf_jscripts()

/**
* Functions for printing javascript popup code at page
* @param $url
* page url for pop up page content
* @result
* prints javascript pop up code at page
* @uses
* udf_popup('search_result.php?q=$_REQUEST['q']');
*/
function udf_popup($url){
echo "<script type='text/javascript'>
var w = 795;
var h = 495;
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
myWindow=window.open('$url','','width='+w+',height='+h+',top='+top+', left='+left);
myWindow.focus();
</script>'";
}


/**
* Functions for database related tasks or processes like showing, updating, deleting and insterting data
* It is used with udf_connect_db_server() function
* @param $process
* task to perform on database like SELECT *, UPDATE, DELETE, INSERT INTO
* @param $table_name
* name of table at which process has to be taken
* @param $additional
* additional query portion like WHERE clause
* @data
* associative array for UPDATE and INSERT process
* @result
* produces output as per process inputs - SELECT *, UPDATE, DELETE, INSERT INTO
* @uses
* udf_db_process('select *', 'items', 'where id = 3');
* udf_db_process('update', 'items', 'where itemid= 5', array('itemname'=>'NoteBook'));
* udf_db_process('delete', 'items', 'where itemid= 7'); udf_db_process('delete', 'items', 'where itemname= \'Mouse\'');
* udf_db_process('insert into', 'items', '', array('itemname'=>'\'TabMone\'', 'eid'=> 13));
*/
function udf_db_process($process, $table_name, $additional='', $data=''){
switch(strtoupper(substr($process,0,6))){
case 'SELECT':
$values = array();
$sql = "$process FROM $table_name $additional";
$result = mysql_query($sql) or die('ERROR: '.mysql_error());
while($rows = mysql_fetch_array($result, MYSQL_ASSOC)){
array_push($values, $rows);
}
return $values;
break;
case 'UPDATE':
//UPDATE tablename SET col1=val1,col2=val2,...WHERE specific_col = specific_value;
//UPDATE items SET itemname='NoteBook' WHERE itemid=7';
foreach($data as $column => $value){
$sql = "$process $table_name set $column = '$value' $additional";
mysql_query($sql) or die('ERROR: '.mysql_error());
}
return true;
break;
case 'DELETE':
//DELETE FROM tablename WHERE specific_col = specific_value;
$sql = "$process FROM $table_name $additional";
mysql_query($sql) or die('ERROR: '.mysql_error());
return true;
break;
case 'INSERT':
//INSERT INTO tablename {col1, col2} values(val1, val2);
$columns = implode(',', array_keys($data));
$values = implode(',', array_values($data));
$sql = "$process $table_name ($columns) values($values)";
//mysql_query($sql) or die('ERROR: '.mysql_error());
return true;
break;
}// end of switch
}// end of function udf_db_process()
?>

Tags : , ,
Aashutosh Kumar Yadav

By Aashutosh Kumar Yadav

He is a PHP-based UI/Web designer and developer by profession and very interested in technical writing and blogging. He has been writing technical content for about 10 years and has proficient in practical knowledge and technical writing.
@www.infotokri.in

0 comments:

Post a Comment