Category Archives: Code Snippets

HTML Entity UTF8 Windows 1252 Character Encoding PHP Scripts

HTML Entity UTF8 Windows 1252 Character Encoding PHP Scripts

This is the one WordPress uses.

    private function _seems_utf8($str)
    {
        $length = strlen($str);
        for ($i=0; $i < $length; $i++) {
            $c = ord($str[$i]);
            if ($c < 0x80) $n = 0; # 0bbbbbbb
           elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
           elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
           elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
           elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
           elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
           else return false; # Does not match any model
           for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
               if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
                    return false;
            }
        }
        return true;
    }

    /**
     * Converts all accent characters to ASCII characters.
     *
     * If there are no accent characters, then the string given is just returned.
     *
     * @param string $string Text that might have accent characters
     * @return string Filtered string with replaced "nice" characters.
     */

    private function _remove_accents($string) {
        if ( !preg_match('/[\x80-\xff]/', $string) )
            return $string;

        // echo $this->_seems_utf8($string);

        if ($this->_seems_utf8($string)) {
            $chars = array(
            // Decompositions for Latin-1 Supplement
            chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
            chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
            chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
            chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
            chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
            chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
            chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
            chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
            chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
            chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
            chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
            chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
            chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
            chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
            chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
            chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
            chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
            chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
            chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
            chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
            chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
            chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
            chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
            chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
            chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
            chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
            chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
            chr(195).chr(191) => 'y',
            // Decompositions for Latin Extended-A
            chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
            chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
            chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
            chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
            chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
            chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
            chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
            chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
            chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
            chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
            chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
            chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
            chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
            chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
            chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
            chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
            chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
            chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
            chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
            chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
            chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
            chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
            chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
            chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
            chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
            chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
            chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
            chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
            chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
            chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
            chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
            chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
            chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
            chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
            chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
            chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
            chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
            chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
            chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
            chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
            chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
            chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
            chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
            chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
            chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
            chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
            chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
            chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
            chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
            chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
            chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
            chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
            chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
            chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
            chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
            chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
            chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
            chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
            chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
            chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
            chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
            chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
            chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
            chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
            // Euro Sign
            chr(226).chr(130).chr(172) => 'E',
            // GBP (Pound) Sign
            chr(194).chr(163) => '');

            $string = strtr($string, $chars);
        } else {
            // Assume ISO-8859-1 if not UTF-8
            $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
                .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
                .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
                .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
                .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
                .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
                .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
                .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
                .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
                .chr(252).chr(253).chr(255);

            $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";

            $string = strtr($string, $chars['in'], $chars['out']);
            $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
            $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
            $string = str_replace($double_chars['in'], $double_chars['out'], $string);
        }

        return $string;
    }

This is a custom one.

    // ** convert characters from Word to avoid problems in html dispaly ** //
    private function _convertChars($text){
           // replace UTF-8 characters
           $text = str_replace(
            array("\xE2\x84\xA2", "\xC2\xA9\xa9", "\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93", "\xe2\x80\x94", "\xe2\x80\xa6"),
            array("&trade;", "&copy;", "'", "'", '"', '"', '-', '--', '...'),
            $text);
           // Next, replace their Windows-1252 equivalents.
            $text = str_replace(
            array(chr(153), chr(169), chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
            array("&trade;", "&copy;", "'", "'", '"', '"', '-', '--', '...'),
            $text);
            return $text;
    }

Basic PHP Contact Form Script

Basic PHP Contact Form Script accepts name, email and message as POST vars then strips tags (more security could be added here to prevent attacks, mysqli can be used but requires db connection to escape). It then constructs the message in HTML format with proper encoded and content type and finally sends the email using PHP’s mail() function.

<?php

/*
    Script to send email from website.
    Author: Sam Deering 2012
*/


header('content-type: application/json; charset=utf-8');

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["msg"]))
{
    $recipent = array(
        "name" => strip_tags($_POST["contact_name"]),
        "email" => strip_tags($_POST["contact_email"])
    );

    //specify your own here to override if you want.
    // $recipent = array(
    //     "name" => "Sam Deering",
    //     "email" => "info@jqmbuilder.com"
    // );

    $sender = array(
        "name" => strip_tags($_POST['name']),
        "email" => strip_tags($_POST['email']),
        "message" => strip_tags($_POST['msg'])
    );

    $subject = 'Contact message from website';

    $message = '<html><head><title>'.$title.'</title></head><body>'.$sender["message"].'</body></html>';

    // To send HTML mail, the Content-type header must be set
    $headers = "From: {$sender['name']} <{$sender['email']}>" . "\r\n";
    $headers .= "Reply-To: {$sender['email']}" . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if(mail($recipent["email"], $subject, $message, $headers))
    {
        echo json_encode(true);
    }
    else
    {
        echo json_encode(false);
    }

}
else
{
    echo json_encode(false);
}

?>

Create Zip Archive of Folder and All Contents

PHP code snippet to Create Zip Archive of Folder and All Contents – without the full directory path being included.

<?php

//function to zip an entire folder to back a backup
//saves to archive/year/month/day/filename.zip
function createZip($zipName,$folderToZip)
{
      // get year digits
      $year = date("Y");
      //create year directory if doesn't exist
      if (!is_dir('archive/'.$year))
      {
          mkdir('archive/'.$year);
      }

      //get month digits
      $month = date("m");
      //create month directory if doesn't exist
      if (!is_dir('archive/'.$year.'/'.$month))
      {
          mkdir('archive/'.$year.'/'.$month);
      }

      //get day digits
      $day = date("d");
      //create day directory if doesn't exist
      if (!is_dir('archive/'.$year.'/'.$month.'/'.$day))
      {
          mkdir('archive/'.$year.'/'.$month.'/'.$day);
      }

      $zipFile = 'archive/'.$year.'/'.$month.'/'.$day.'/'.$zipName.'.zip';

      ini_set("max_execution_time", 300);
      // create object
      $zip = new ZipArchive();
      // open archive
      if ($zip->open($zipFile, ZIPARCHIVE::CREATE) !== TRUE)
      {
            die ("Could not open archive");
      }
      // initialize an iterator
      // pass it the directory to be processed
      $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderToZip."/"));
      // iterate over the directory
      // add each file found to the archive
      foreach ($iterator as $key=>$value)
      {
            $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
      }
      // close and save archive
      $zip->close();
      echo "Archive created successfully.";

      return $zipFile;
}
?>

script to log $_POST vars to a txt file

Just a script code snippet to log $_POST and $_GET vars to text file.

<?php

/* Author: Sam Deering 2012 */

/* script to log $_POST vars to file */

$file = "log.txt";
$date = new DateTime();
$data = $date->format('Y-m-d H:i:s') . "\n";
$data .= "-------------------------------------------------------------" . "\n";
//dynamically set vars from POST vars
foreach($_POST as $n => $v)
{
    $$n = $v;
    $data .= $n . '=' . $v . "\n";
}
//dynamically set vars from GET vars
foreach($_GET as $n => $v)
{
    $$n = $v;
    $data .= $n . '=' . $v . "\n";
}
$data .= "-------------------------------------------------------------" . "\n\n";

echo $data;
$fp = fopen($file, "w") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);


?>

PHP Convert URL string into name value pairs

PHP code snippet to Convert a URL string into name value pairs.

Sample Input:

$url = '?a=_getFunctionTests&format=html';

Sample Output:

array
  'a' => string '_getFunctionTests' (length=17)
  'format' => string 'html' (length=4)

The function:

    /**
     * Convert URL string into name value pairs
     */

    private static function _getNameValuePairsFromUrl($url)
    {
        debug('calling '.__FUNCTION__.'()...');
        //remove ? and &
        $url = str_replace('?','',$url);
        $list = explode('&', $url);
        debug($list);
        $urlParams = array();
        foreach ($list AS $i => $v)
        {
            $param = explode('=', $v);
            $urlParams[ $param[0] ] = $param[1];
        }
        return $urlParams;
    }

PHP MD5 Encryption

Through MD5, we can easily encrypt a string. Below code snippet example take and encrypts a string, take note though that you could not decrypt any data after encryption.
     <?php
$encryptText = "Hello world '";
$encryptedText = md5($encryptText );

echo "Clear Text : $encryptText <br /> Encrypted text:  $encryptedText";
?>

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 Pagination

As a developer you’ll soon find a need to paginate data when displaying contents from the database, and rather than use JavaScript which could require all the data to be loaded into the page on load, we can use PHP to ensure that we’re only requesting the data that we need from the database.
require_once 'Pager/Pager.php';
/* We will bypass the database connection code ... */
$sqlQuery = "SOME SQL QUERY";
$result = mysql_query($sqlQuery);
$totalRows = mysql_num_rows($result);
 
$pager_options = array(
'mode'       => 'Sliding',
'perPage'    => 10,
'delta'      => 4,
'totalItems' => $totalRows,
);
$pager = Pager::factory($pager_options);
echo $pager->links;

The above code will output:

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 » [10]

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 Create Read-Only Properties for your Class

To create read-only properties for your class, you will have to use the

__get()

and

__set()

functions. You just have to create the framework and code to implement this functionality.

Here’s a quick example: (This code doesn’t take advantage of the “type” attribute in the properties array, but is there for ideas)

    <?php

class Test {
   
    private $p_arrPublicProperties = array(
            "id" => array("value" => 4,
                    "type" => "int",
                    "readonly" => true),
            "datetime" => array("value" => "Tue 02/21/2006 20:49:23",
                    "type" => "string",
                    "readonly" => true),
            "data" => array("value" => "foo",
                    "type" => "string",
                    "readonly" => false)
            );

    private function __get($strProperty) {
        //Get a property:
        if (isset($this->p_arrPublicProperties[$strProperty])) {
            return $this->p_arrPublicProperties[$strProperty]["value"];
        } else {
            throw new Exception("Property not defined");
            return false;
        }
    }
   
    private function __set($strProperty, $varValue) {
        //Set a property to a value:
        if (isset($this->p_arrPublicProperties[$strProperty])) {
            //Check if property is read-only:
            if ($this->p_arrPublicProperties[$strProperty]["readonly"]) {
                throw new Exception("Property is read-only");
                return false;
            } else {
                $this->p_arrPublicProperties[$strProperty]["value"] = $varValue;
                return true;
            }
        } else {
            throw new Exception("Property not defined");
            return false;
        }
    }
   
    private function __isset($strProperty) {
        //Determine if property is set:
        return isset($this->p_arrPublicProperties[$strProperty]);
    }
   
    private function __unset($strProperty) {
        //Unset (remove) a property:
        unset($this->p_arrPublicProperties[$strProperty]);
    }  
           
}

$objTest = new Test();

print $objTest->data . "\n";

$objTest->data = "bar"; //Works.
print $objTest->data;

$objTest->id = 5; //Error: Property is read-only.

?>

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 Delete Temporary Files

The code snippet below shows how to delete specific files after a given time span. If you are cleaning cached files, this works really good!
// Define the folder to clean
// (keep trailing slashes)
$captchaFolder  = 'temp/';
 
// Filetypes to check (you can also use *.*)
$fileTypes      = '*.jpg';
 
// Here you can define after how many
// minutes the files should get deleted
$expire_time    = 20;
 
// Find all files of the given file type
foreach (glob($captchaFolder . $fileTypes) as $Filename) {
 
    // Read file creation time
    $FileCreationTime = filectime($Filename);
 
    // Calculate file age in seconds
    $FileAge = time() - $FileCreationTime;
 
    // Is the file older than the given time span?
    if ($FileAge > ($expire_time * 60)){
 
        // Now do something with the olders files...
 
        print "The file $Filename is older than $expire_time minutes\n";
 
        // For example deleting files:
        //unlink($Filename);
    }
 
}

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