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