Category Archives: PHP Functions

PHP Scalar / Basic Typehints

For those who have been asking about scalar/basic typehints… Here is a drop in class that that will enable typehints through the use of a custom error handler.
    <?php

define('TYPEHINT_PCRE'              ,'/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/');

class Typehint
{

    private static $Typehints = array(
        'boolean'   => 'is_bool',
        'integer'   => 'is_int',
        'float'     => 'is_float',
        'string'    => 'is_string',
        'resrouce'  => 'is_resource'
    );

    private function __Constrct() {}

    public static function initializeHandler()
    {

        set_error_handler('Typehint::handleTypehint');

        return TRUE;
    }

    private static function getTypehintedArgument($ThBackTrace, $ThFunction, $ThArgIndex, &amp;$ThArgValue)
    {

        foreach ($ThBackTrace as $ThTrace)
        {

            // Match the function; Note we could do more defensive error checking.
            if (isset($ThTrace['function']) &amp;&amp; $ThTrace['function'] == $ThFunction)
            {

                $ThArgValue = $ThTrace['args'][$ThArgIndex - 1];

                return TRUE;
            }
        }

        return FALSE;
    }

    public static function handleTypehint($ErrLevel, $ErrMessage)
    {

        if ($ErrLevel == E_RECOVERABLE_ERROR)
        {

            if (preg_match(TYPEHINT_PCRE, $ErrMessage, $ErrMatches))
            {

                list($ErrMatch, $ThArgIndex, $ThClass, $ThFunction, $ThHint, $ThType) = $ErrMatches;

                if (isset(self::$Typehints[$ThHint]))
                {

                    $ThBacktrace = debug_backtrace();
                    $ThArgValue  = NULL;

                    if (self::getTypehintedArgument($ThBacktrace, $ThFunction, $ThArgIndex, $ThArgValue))
                    {

                        if (call_user_func(self::$Typehints[$ThHint], $ThArgValue))
                        {

                            return TRUE;
                        }
                    }
                }
            }
        }

        return FALSE;
    }
}

Typehint::initializeHandler();

?>

Some examples of the class in use:

<?php

function teststring(string $string) { echo $string; }
function testinteger(integer $integer) { echo $integer; }
function testfloat(float $float) { echo $float; }

// This will work for class methods as well.

?>

Note: You should include this code above all other code in your include headers and if you are the using

set_error_handler()

function you should be aware that this uses it as well. You may need to chain your

set_error_handlers()

.

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Protect a PDF File

This is the solution I found for on the fly protecting a PDF file in PHP.

E.G cpanel setup: You will have first put your files outside of your public HTML directory

user/public_html
    /public_html/download.php

user/documents/
    /documents/file.doc
    /documents/file.pdf

This is an extension to have the correct mime type as to the best way to 1 force download of file, and 2 allow different file types…

download.php

    //check users is loged in and valid for download if not redirect them out
// YOU NEED TO ADD CODE HERE FOR THAT CHECK
// array of support file types for download script and there mimetype
$mimeTypes = array(
    'doc' => 'application/msword',
    'pdf' => 'application/pdf',
);
// set the file here (best of using a $_GET[])
$file = "../documents/file.doc";

// gets the extension of the file to be loaded for searching array above
$ext = explode('.', $file);
$ext = end($ext);

// gets the file name to send to the browser to force download of file
$fileName = explode("/", $file);
$fileName = end($fileName);

// opens the file for reading and sends headers to browser
$fp = fopen($file,"r") ;
header("Content-Type: ".$mimeTypes[$ext]);
header('Content-Disposition: attachment; filename="'.$fileName.'"');

// reads file and send the raw code to browser    
while (! feof($fp)) {
    $buff = fread($fp,4096);
    echo $buff;
}
// closes file after whe have finished reading it
fclose($fp);

Here’s a list of MIME TYPES if you want to add support for other files..

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP jQuery Class

This is a very interesting code snippets to construct a class that gives you access to all the power of jQuery
{code type=php}<?php

class Jquery {

function animate($trigger, $element, $event, $time) {

echo<script>

$(function() {

$($trigger).$event(function() {

$(#$element’).slideDown($time);

});

});

</script>;

;
}
}

?>

<html>

<head>
<meta http-equiv=”Content-type” content=”text/html; charset=utf-8″>
<title>jquery class</title>

<script type=”text/javascript” charset=”utf-8″ src=”http://code.jquery.com/jquery-1.5.1.js”>

</script>

<style>

#paragraph {display:none;}

</style>

</head>

<body id=”jquery” onload=”">

<?
$trigger=#trigger”;
$element = “paragraph”;
$event = “click”;
$time =500;

$slide = new Jquery();
echo $slide->animate($trigger, $element, $event, $time);
?>

<a id=”trigger” href=”#”>click me</a>
<div id = “paragraph”>my paragraph</div>

</body>

</html>{/code}

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Display Copyright

The code snippet below shows how to simply display Copyright in your webpage…
      <?php
    /*
    |---------------------------
    | Author: Evin Weissenberg
    |---------------------------
    */

    class Copyright_Display {
     
    private $company_name;
    private $utf8;
     
    function __constructor() {
     
    $this->utf8 = ini_set('default_charset', 'UTF-8');
     
    }
     
    function setCompanyName($company_name) {
     
    $this->company_name = (string)$company_name;
    return $this;
    }
     
    function __get($property) {
     
    return $this->$property;
     
    }
     
    function render() {
     
    $copyright = "Copyright © " . date('Y') . " " . $this->company_name;
     
    return $copyright;
     
    }
     
    function __destructor() {
     
    unset($this->utf8);
     
    }
    }
    $c = new Copyright_Display();
    $c->setCompanyName('ACME LLC')->render();

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

Overloading PHP Functions

You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name.

You can, however, declare a “variadic” function that takes in a variable number of arguments. You would use

func_num_args()

and

func_get_arg()

to get the arguments passed, and use them normally.

For instance:

    function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
    }
}

/*
Argument 0: a
Argument 1: 2
Argument 2: 3.5
*/

myFunc('a', 2, 3.5);

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP __autoload() Errors

Some of you may have experienced problems when using

__autoload()

in multiple scripts. So, the better way is to avoid

__autoload()

and use

spl_register_autoload()

instead. If you have written this already, just rename your function to something like

__autoload_my_classes

, and in the next, call

spl_autoload_register

as:

    <?php
function __autoload_my_classes($classname)
{
  # ... your logic to include classes here
}
spl_autoload_register('__autoload_my_classes');
?>

By calling it repeatedly with different function names, you can assign multiple functions to

spl_autoload_register()

. Be sure to limit your every function to include a CLASS file.

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP for Checking isFirst() and isLast()

This is what seems to work for checking

isFirst()

and

isLast()

on a class implementing the Iterator interface – without destroying the internal array pointer:

    <?php
// Let $this->_elements be your internal array with
// array("one", "two", "three")
public function isFirst()
{
    $hasPrevious = prev($this->_elements);
    // now undo
    if ($hasPrevious) {
        next($this->_elements);
    } else {
        reset($this->_elements);
    }
    return !$hasPrevious;
}

public function isLast()
{
    $hasNext = next($this->_elements);
    // now undo
    if ($hasNext) {
        prev($this->_elements);
    } else {
        end($this->_elements);
    }
    return !$hasNext;
}

// usage
foreach ($myInterator as $value) {
  echo $value;
  if ($myInterator->isFirst()) {
    echo " (first)";
  }
  if ($myInterator->isLast()) {
    echo " (last)";
  }
  echo " - value is still the same: ", $value, "<br />";
}

?>

output:

one (first) - value is still the same: one
two - value is still the same: two
three (last) - value is still the same: three
This can be helpful for designing CSS elements where the first or last element must have a different padding/margin than the others.

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Simple MySQL Search Function

Code shown below is just a very simple way to search a MySQL database.

Example:

mysqlsearch('items', 'title tags', isset($GET['q'])?$GET['q']:'', Array('columns'=>'*', 'method'=>'OR', 'extrasql'=>'AND active = "true" ORDER BY id DESC'));
    if (!function_exists('mysql_search')) {
     
    function mysql_search($table, $columns, $query = '', $options = Array()) {
     
    if (empty($query)) { return Array(); }
     
    $sql_query = Array();
     
    $options['columns'] = isset($options['columns'])?$options['columns']:'*';
    $options['method'] = isset($options['method'])?$options['method']:'OR';
    $options['extra_sql'] = isset($options['extra_sql'])?$options['extra_sql']:'';
     
    $query = ereg_replace('[[:<:]](and|or|the)[[:>:]]', '', $query);
    $query = ereg_replace(' +', ' ', trim(stripslashes($query)));
     
    $pattern = '/([[:alpha:]:]+)([[:alpha:] ]+)[[:alpha:]]?+[ ]?/i';
     
    $regs = Array();
     
    preg_match_all($pattern, $query, $regs);
     
    $query = $regs[0];
     
    while (list($key, $value) = @each($query)) {
     
    $column = $columns;
    $keywords = urldecode($value);
     
    if (strpos($value, ':')) {
     
    $column = substr($value, 0, strpos($value, ':'));
    $keywords = trim(substr($keywords, strpos($keywords, ':') + 1));
    $keywords = ereg_replace('\'', '', $keywords);
     
    } else { $keywords = ereg_replace(' +', '|', $keywords); }
     
    $column_list = explode(' ', $column);
     
    $sql = Array();
     
    for ($i = 0; $i < count($column_list); $i++) { $sql[] = '' . $column_list[$i] . ' REGEXP "' . $keywords . '"'; }
     
    $query[$key] = Array('orignal'=>$value, 'sql'=>implode(' ' . $options['method'] . ' ', $sql));
     
    $sql_query = array_merge($sql_query, $sql);
    $sql_query = implode(' ' . $options['method'] . ' ', $sql_query);
     
    }
     
    $results = mysql_fetch_results(mysql_query('SELECT ' . $options['columns'] . ' FROM ' . $table . ' WHERE ' . $sql_query . ' ' . $options['extra_sql']));
     
    return $results;
     
    }
     
    }

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Functions that Returns Specific Files in an Array

Here is a function that returns specific files in an array, with all of the details. Includes some basic garbage checking.

Variables:

$source_folder // the location of your files
$ext // file extension you want to limit to (i.e.: *.txt)
$sec // if you only want files that are at least so old.
$limit // number of files you want to return

The function:

function glob_files($source_folder, $ext, $sec, $limit){
    if( !is_dir( $source_folder ) ) {
        die ( "Invalid directory.\n\n" );
    }
   
    $FILES = glob($source_folder."\*.".$ext);
    $set_limit    = 0;
   
    foreach($FILES as $key => $file) {
   
        if( $set_limit == $limit )    break;
       
        if( filemtime( $file ) > $sec ){
       
            $FILE_LIST[$key]['path']    = substr( $file, 0, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['name']    = substr( $file, ( strrpos( $file, "\\" ) +1 ) );  
            $FILE_LIST[$key]['size']    = filesize( $file );
            $FILE_LIST[$key]['date']    = date('Y-m-d G:i:s', filemtime( $file ) );
            $set_limit++;
       
        }
       
    }
    if(!empty($FILE_LIST)){
        return $FILE_LIST;
    } else {
        die( "No files found!\n\n" );
    }
}

So….

$source_folder = "c:\temp\my_videos";
$ext = "flv"; // flash video files
$sec = "7200"; // files older than 2 hours
$limit = 2; // Only get 2 files

print_r(glob_files($source_folder, $ext, $sec, $limit));

Would return:

Array
(
    [0] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => fluffy_bunnies.flv
            [size] => 21160480
            [date] => 2007-10-30 16:48:05
        )

    [1] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => synergymx.com.flv
            [size] => 14522744
            [date] => 2007-10-25 15:34:45
        )

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

PHP Continue Syntax

This PHP function, using continue syntax, is to print prime numbers between given numbers, x and y.

<?php
function print_primes_between($x,$y)
{
    for($i=$x;$i<=$y;$i++)
   {
        for($j= 2; $j < $i; $j++)  if($i%$j==0) continue 2;
        echo $i.",";
   }
}
?>

For instance,

print_primes_between(10,20)

will output:

11,13,17,19,23,29,

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.