Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, February 28, 2012

Get the dynamically rendered file contents

/**
 * Get the dynamic rendered contents of given file
 * without exposing a bit of char.
 *
 * @author Junaid Atari <mj.atari@gmail.com>
 * @version 1.0
 * @param string $filename Absolute path of the file.
 * @param array $vars List of variables pass to file.
 * @return mixed Rendered output of file.
 */
function getIncludedFileContents $filename, array $vars = array () )
{
    
//** make sure that given path is the real file.
    
if ( is_file ( (string) $filename ) )
    {
        
//** Start Output Buffer
        
ob_start ();
        
ob_implicit_flush false );
     
        
//** Extract named variables and assign thier values.
        
extract $varsEXTR_PREFIX_SAME'vars' );
     
        
//** Include the file and execute the code.
        
require_once ( $filename );
     
        
//** Return the rendered output.
        
return ob_get_clean ();
    }

    
//** If nothing, return.
    
return NULL;
}
/*
 +-----------+
 |  Example  |
 +-----------+
*/
/*

welcome.php
-------------------
Salam <strong><?php echo $fullname; ?></strong>!

*/

/*
# The file contain variable $fullname
# and will replaced with the value.
echo getIncludedFileContents (
    "welcome.php",
    array ( "fullname"=>'Junaid Atari' )
);
*/

/*
 +-----------+
 |  Output   |
 +-----------+
*/
/*
Salam <strong>Junaid Atari</strong>!
*/

Friday, February 24, 2012

Beautify an XML string in PHP (PCRE)

/*
 * Beautify an XML string.
 *
 * @param    string    Compressed/Unformatted XML string
 * @return   string    Formatted XML string
 */
function beautifyXmlString $xml )
{
    
// add marker linefeeds to aid the pretty-tokeniser
    // (adds a linefeed between all tag-end boundaries)
    
$xml preg_replace '/(>)(<)(\/*)/'"$1\n$2$3"$xml );

    
// now indent the tags
    
$token strtok $xml"\n" );
  
    
// holds formatted version as it is built
    
$result '';
  
    
// initial indent
    
$pad 0;
  
    
// returns from preg_matches()
    
$matches = array();

    
// scan each line and adjust indent based on opening/closing tags
    
while ( $token !== false )
    {  
        
// test for the various tag states

        // 1. open and closing tags on same line - no change
        
if ( preg_match '/.+<\/\w[^>]*>$/'$token$matches ) ) :
            
$indent 0;

        
// 2. closing tag - outdent now
        
elseif ( preg_match '/^<\/\w/'$token$matches ) ) :
            
$pad--;

        
// 3. opening tag - don't pad this one, only subsequent tags
        
elseif ( preg_match '/^<\w[^>]*[^\/]>.*$/',
                 
$token$matches ) ) :
            
$indent=1;

        
// 4. no indentation needed
        
else :
            
$indent 0;

        endif;

        
// pad the line with the required number of leading spaces
        
$line str_pad $tokenstrlen $token ) +
                
$pad"\t"STR_PAD_LEFT );
                 
        
// add to the cumulative result, with linefeed
        
$result .= $line "\n";
      
        
// get the next token
        
$token strtok "\n" );
      
        
// update the pad size for subsequent lines
        
$pad += $indent;
    }
    return 
$result;
}

/*
 +-----------+
 |  Example  |
 +-----------+
*/
echo beautifyXmlString '<response><post><title>Damn in the World'.
                         
'</title></post></response>' );
/*
 +-----------+
 |  Output   |
 +-----------+
*/
/*
<response>
    <post>
        <title>Damn in the World</title>
    </post>
</response>
*/

Validate an IP Address ( PCRE )

/*
 Validation footprint:
 - First part must be > 0.

 - All parts will be <= 255.
 - No 0.0.0.0 match
 - 00, 000 are not allowed in pairs if
   first digit starts with 0. allowed for
   > 0 first digit.

 
Valid examples:
 - 12.255.99.2
 
- 115.92.255.66
 - 127.2.1.66:2082
 ...
*/

/**
 * Validate the MySQL Timestamp
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @see      http://codesnap.blogspot.com/
 * @param    string  $ip   IP to validate
 * @return   bool    TRUE on valid | FALSE
 */

function isValidIp $ip )
{
    
/* PCRE Pattern written by Junaid Atari */
    
return !preg_match '/^([1-9]\d|1\d{0,2}|2[0-5]{2})\.('.
                         
'(0|1?\d{0,2}|2[0-5]{2})\.){2}(0|1?'.
                         
'\d{0,2}|2[0-5]{2})(\:\d{2,4})?$/',
                         (string) 
$ip )
            ? 
false
            
true;
}

/*
 +-----------+
 |  Example  |
 +-----------+
*/

var_dump isValidIp '127.0.0.1:8080' ) );

/*
 +-----------+
 |  Output   |
 +-----------+
*/

# Output: True

Tuesday, November 22, 2011

Validate the MySQL Timestamp in PHP

/*
 * Validate the MySQL Timestamp
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string  $str   MySQL Timestamp to check
 * @return   bool    TRUE on valid | FALSE
*/
function isValidMySqlTimeStamp $str )
{
    
/* PCRE Pattern written by Junaid Atari */
    
if ( !preg_match '/^(?<y>19\d\d|20\d\d)\-(?<m>0[1-9]|1[0-2])\-' .
                       
'(?<d>0\d|[1-2]\d|3[0-1]) (?<h>0\d|1\d|2[0-3]' .
                       ')\:
(?<i>[0-5][0-9])\:(?<s>[0-5][0-9])$/',
                       
$str$date ) )
       return 
false;

    return 
checkdate $date['m'], $date['d'], $date['y'] );
}

/*
 +-----------+
 |  Example  |
 +-----------+
*/
var_dump isValidMySqlTimeStamp '2011-11-26 11:25:26' ) );

/*
 +-----------+
 |  Output  |
 +-----------+
*/
# Output: True 

Validate the MySQL Date in PHP

/*
 * Validate the MySQL Date
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string  $str   MySQL Date to check
 * @return   bool    TRUE on valid | FALSE
*/
function isValidMySqlDate $str )
{
    
/* PCRE Pattern written by Junaid Atari */
    
if ( !preg_match '/^(?<y>19\d\d|20\d\d)\-(?<m>0[1-9]|1[0-2])'.
                       
'\-(?<d>0\d|[1-2]\d|3[0-1])$/'$str$date ) )
        return 
false;

    return 
checkdate $date['m'], $date['d'], $date['y'] );
}


/*
 +-----------+
 |  Example  |
 +-----------+
*/
var_dump isValidMySqlDate '2011-11-22' ) );

/*
 +-----------+
 |  Output  |
 +-----------+
*/
# Output: True 

Validate the MySQL Time in PHP

/*
 * Validate the MySQL Time
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @param    string  $str   MySQL Time to check
 * @return   bool    TRUE on valid | FALSE
*/
function isValidMySQLTime $str )
{
    
/* PCRE Pattern written by Junaid Atari */
    
return !preg_match '/^(?<h>0\d|1\d|2[0-3])\:(?<i>[0-5]\d)\:'.
                         
'(?<s>[0-5]\d)$/'$str )
            ? 
false
            
true;
}


/*
 +-----------+
 |  Example  |
 +-----------+
*/
var_dump isValidMySQLTime '11:25:26' ) );

/*
 +-----------+
 |  Output  |
 +-----------+
*/
# Output: True 

Sunday, November 20, 2011

Get the Directories Name by Given Criteria

/*
 * Get the directories name by given criteria.
 *
 * @author    Junaid Atari <mj.atari@gmail.com>
 * @version   1.0
 * @param     string   $dir              Complete path to directory.
 * @param     array    $skipList         Dirs name to be exclude.
 * @param     string   $strictNameRegex  PCRE pattern to filter names
 * @return    array    List of folders name | empty
*/ 
function getDirectryFolders 
   
$dir$skipList = array (), $strictNameRegex '' )
{
    
$listDir = array ();
    
    if ( !
preg_match '@(//|\\\)$@', (string) $dir ) )
        
$dir .= DIRECTORY_SEPARATOR;
    
    
$handler = @opendir $dir );
    
    if ( !
$handler )
        return array ();
    
    
$skipList array_merge ( (array) $skipList, array ( '.''..' ) );
    
    while ( ( 
$sub readdir $handler ) ) !== false )
    { 
        if ( !
in_array $sub$skipList ) && is_dir $dir $sub ) )
        {
            if ( 
trim $strictNameRegex ) )
            {
                if ( (bool) @
preg_match $strictNameRegex$sub ) )
                    
$listDir$sub ] = $dir $sub;
            }
            else
                
$listDir$sub ] = $dir $sub;
        }
    } 
    
    
closedir $handler );
    
    return 
$listDir
}

/*
+---------+
| Example |
+---------+
*/ 
print_r (
    
getDirectryFolders (
        
'c:\htdocs\web',
        array ( 
'includes' ),
        
'/^[a-z0-9_]+$/i'
    
)
);

/*
+--------+
| Output |
+--------+

Array
(
    [backups] => c:\htdocs\web\backups
    [libraries] => c:\htdocs\web\libraries
    [images] => c:\htdocs\web\images
    [logs] => c:\htdocs\web\logs
    [components] => c:\htdocs\web\components
)

*/ 

Get the Files of Directory by Given Criteria

/*
 * Get the files of directory by given criteria.
 *
 * @author  Junaid Atari <mj.atari@gmail.com>
 * @version 1.0
 * @param   
string  $dir              Path of directory.
 * @param   string  $pattern          Pattern of file name & extesion
 * @param   array   $excludeList      Files list to exclude (name only)
 * @param   string  $strictNameRegex  PCRE pattern to filter files name
 * @return  array   List of folder's files | empty
*/
function getFolderFiles (
   $dir$pattern NULL, array $excludeList = array (),
   $strictNameRegex '' )
{
    
$pattern = !is_string $pattern )
                ? 
'*.php'
                
$pattern;
      
    if ( !
preg_match '@(//|\\\)$@'$dir ) )
            
$dir .= DIRECTORY_SEPARATOR;
  
    
$_files glob $dir .DIRECTORY_SEPARATOR $pattern );
  
    if ( !
count $_files ) )
        return array ();
  
    
$filesList = array ();
  
    foreach ( 
$_files as $file )
    {
        
$fName pathinfo $filePATHINFO_FILENAME );
      
        if ( !
in_array $fName, (array) $excludeList ) )
            
$filesList$fName ] = $file;
    }
          
    if ( 
trim $strictNameRegex ) )
    {
        
$fiList = array ();
      
        
$list preg_grep (
            $strictNameRegexarray_keys $filesList )
        );
      
        if ( !
count $list ) )
            return array ();
      
        foreach ( 
$list as $name )
        {
            if ( 
array_key_exists $name$filesList ) )
                
$fiList$name ] = $filesList[$name];
        }
      
        
$filesList $fiList;
    }
  
    return 
$filesList;
}

/*
+---------+
| Example |
+---------+
*/ 

print_r 
(
    
getFolderFiles (
        
'C:/path/to',
        
'CF*.php',
        array ( 
'CTag' ),
        
'/^CF[a-zA-Z0-9_]+$/'
    
)
);

/*
+--------+
| Output |
+--------+

Array
(
    [CF_Comment] => C:/path/to/CF_Comment.php
    [CF_BBTags] => C:/path/to/CF_BBTags.php
    [CF_JavaScript] => C:/path/to/CF_JavaScript.php
)

*/ 

Monday, November 14, 2011

Validate the Credit Card Number

/**
 * Check that Credit Card number is valid or not.
 *
 * @author    Junaid Atari <mj.atari@gmail.com>
 * @version   1.1
 * @param     array    $number    Credit Card number
 * @param     string   $cctype    Card Type to check.
 * @return    bool     TRUE on valid | else FALSE
 */

function isCCNumberValid $number$cctype )
{
    if ( !
is_string $number)
         || !
trim $number ) )
             return 
false;
      
    
$ccs = array (

        /* Patterns written by Junaid Atari */

        // Master Card
        
'master' => '/^(5[1-5]{1})(\d{14})$/',

        
// American Express 
        'amex' => '/^3(4|7)\d{13}$/',
        
        // Discover Card 
        'discover' => '/^6(011|22|4|5)(\d{12}|\d{13}|\d{14})$/'
        

        // Visa Card 
        'visa' => '/^4(\d{12}|\d{15})$/',

        
// Dinners Club        
        'dinners' => '/^(305|36|38|54|55)(\d{12}|\d{14})$/',

        // Carte Blanche         
        'carte' => '/^(30[0-5]{1})(\d{11})$/'
        
        // enRoute 
        'enroute' => '/^2(014|149)\d{11}$/'
        

        // Laser
        'laser' => '/^6(304|706|771|709)(\d{12}|\d{13}|\d{14}'.
                   '|d{\15})$/'
        
        // Visa Electron 
        'visaelec' => '/^4(17500|917|913|844|508)(\d{10}|\d{12})$/'
    
);

    if ( !
is_string $cctype )
         || !
array_key_existsstrtolower ($cctype) , $ccs ) )
             return 
false;

    return (bool) 
preg_match $ccs[$cctype], $number );

Remove Tags from String

/**
 * Remove the tags list from given string.
 *
 * @author     Junaid Atari <mj.atari@gmail.com
>
 * @version    1.1
 * @param      array     $tagsList    Url of page
 * @param      string    $contents    Variable which need to be clean.
 * @return     string    Will direct update the variable in memory.
 */

function removeTags ( array $tagsList$contents )
{
    foreach ( 
$tagsList as $tag )
    {
        
$tag trim preg_quote $tag'/' ) );
        $contents (string) $contents;
         
        if ( 
$tag != '' )   
            
//** Pattern copyright 2011 Junaid Atari
            
return preg_replace '/((<'.$tag.'.*(\/>|>.*<\/'.$tag.
                                  '>)))(\s)?/imsU','', $contents );
        return $contents;
    }

Beautify JSON string

/**
 * pretty_json ()
 * beautify the JSON string
 *
 * Use 'indent' option to select indentation string - by default it's a tab
 *
 * @param    string    $json         Original JSON string
 * @param    array    $options     Encoding options
 * @return    string    Beautified JSON string
 */

function pretty_json $json$options = array() )
{
    
$tokens preg_split ('|([\{\}\]\[,])|',
              $json, -1PREG_SPLIT_DELIM_CAPTURE);
    
$result "";
    
$indent 0;

    
$ind "\t";

    if ( isset ( 
$options['indent'] ) )
        $ind $options['indent'];

    foreach ( 
$tokens as $token )
    {
        if ( 
$token == "" ) continue;

        
$prefix str_repeat ($ind$indent); 

        if ( 
$token == "{"
             
|| $token == "[" )
        {
            
$indent++;
            if ( 
$result != ""
                 
&& $result[strlen ($result) - 1] == "\n" )
                    
$result .= $prefix;
              
            
$result .= "$token\n";
        }
        else if ( 
$token == "}"
                  
|| $token == "]" )
        {
            
$indent--;
            
$prefix str_repeat $ind$indent );
            
$result .= "\n$prefix$token";
        }
        else if (
$token == ","$result .= "$token\n";
        else 
$result .= $prefix.$token;
    }
  
    return 
$result;