/ Gists / PHP

Gists - PHP

On gists

PHP Method Chaining

PHP

PHP Method Chaining.php #

<?php
 
class QueryMaker
{
    $table = '';
$field = '';
 
    // this is a static method, it doesn't
    // run on an object, it only runs on a class
    public static function make()
    {
        // create an instance of class
        // QueryMaker and return it
        return new static();
    }
 
    // this is not static, it doesn't run on
    // a class, only on an object
    public function setTable($name)
    {
        $this->table = $name;
        return $this;
    }
 
    // this is also not static
    public function setField($name)
    {
        $this->field = $name;
        return $this;
    }
 
    // again, not static, just renders
    // the "query"
    public function flush()
    {
        return "select {$this->field} from {$this->table}";
    }
}
 
// Here is the implementation with method chaining
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
 
// Here is the implementation without method chaining
$object = new QueryMaker();
$object->setTable('users');
$object->setField('name');
$query = $object->flush();
// the output is: select name from users
 
// The methods setTable() and setField() return $this.
// In that context $this is the QueryMaker object that was created by make().
 
// Let's go step by step:
 
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
// The static method QueryMaker::make() returns an object instantiation of the QueryMaker class.
 
$query = $object->setTable('users')->setField('name')->flush();
// $object->table is set, setTable() returns the object instance.
 
$query = $object->setField('name')->flush();
// $object->field is set, setField() returns the object instance.
 
$query = $object->flush();
// The flush method is called on the object, returning the string.

On gists

Get Array Values Recursively

PHP

demo.php #

<?php
 
/**
 * Get Array Values PHP Recursively
 *
 * https://davidwalsh.name/get-array-values-with-php-recursively
 *
 * @param array $array The source array.
 * @return array The flattened array values.
 */
function array_values_recursive($array)
{
    $flat = array();
 
    foreach ($array as $value) {
        if (is_array($value)) {
            $flat = array_merge($flat, array_values_recursive($value));
        } else {
            $flat[] = $value;
        }
    }
 
    return $flat;
}

On gists

Sanitize all PHP Super Globals

PHP Protecting

demo.php #

<?php
 
//
// Sanitize all dangerous PHP super globals.
//
// The FILTER_SANITIZE_STRING filter removes tags and remove or encode special
// characters from a string.
//
// Possible options and flags:
//
//   FILTER_FLAG_NO_ENCODE_QUOTES - Do not encode quotes
//   FILTER_FLAG_STRIP_LOW        - Remove characters with ASCII value < 32
//   FILTER_FLAG_STRIP_HIGH       - Remove characters with ASCII value > 127
//   FILTER_FLAG_ENCODE_LOW       - Encode characters with ASCII value < 32
//   FILTER_FLAG_ENCODE_HIGH      - Encode characters with ASCII value > 127
//   FILTER_FLAG_ENCODE_AMP       - Encode the "&" character to &amp;
//
//
// <?php
//
// // Variable to check
// $str = "<h1>Hello WorldÆØÅ!</h1>";
//
// // Remove HTML tags and all characters with ASCII value > 127
// $newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// echo $newstr;
//  -> Hello World!
//
// ?>
//
 
foreach ($_GET as $key => $value)
{
    $_GET[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_POST as $key => $value)
{
    $_POST[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_COOKIE as $key => $value)
{
    $_COOKIE[$key] = filter_input(INPUT_COOKIE, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_SERVER as $key => $value)
{
    $_SERVER[$key] = filter_input(INPUT_SERVER, $key, FILTER_SANITIZE_STRING);
}
 
foreach ($_ENV as $key => $value)
{
    $_ENV[$key] = filter_input(INPUT_ENV, $key, FILTER_SANITIZE_STRING);
}
 
$_REQUEST = array_merge($_GET, $_POST);

On gists

ArrayToObject / ObjectToArray

PHP Helpers-Filters-Plugins

object-to-array-vice-versa.php #

<?php

function objectToArray($d) {
		if (is_object($d)) {
			// Gets the properties of the given object
			// with get_object_vars function
			$d = get_object_vars($d);
		}
 
		if (is_array($d)) {
			/*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
			return array_map(__FUNCTION__, $d);
		}
		else {
			// Return array
			return $d;
		}
	}
 
 
 
 	function arrayToObject($d) {
		if (is_array($d)) {
			/*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
			return (object) array_map(__FUNCTION__, $d);
		}
		else {
			// Return object
			return $d;
		}
	}
 

On gists

CURL - functions

PHP Helpers-Filters-Plugins

CURL.php #

function curl_file_get_contents($url) 
{	
	 $c = curl_init(); // iniciuje práci s curl
	 curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	 curl_setopt($c, CURLOPT_URL, $url);
	 $contents = curl_exec($c);
	 curl_close($c); 
 
	 return $contents;
 }


function better_curl($url)
{
	
  $curl = curl_init();
 
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8,utf-16;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.
 
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.1) Gecko/20061223 Firefox/2.0.0.1');
//  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
//  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);
 
  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection
 
  return $html; // and finally, return $html
}

On gists

Recursive dir delete

PHP Helpers-Filters-Plugins

recursive-delete-dir.php #

<?php

 function rrmdir($dir) { 
   if (is_dir($dir)) { 
     $objects = scandir($dir); 
     foreach ($objects as $object) { 
       if ($object != "." && $object != "..") { 
         if (is_dir($dir."/".$object))
           rrmdir($dir."/".$object);
         else
           unlink($dir."/".$object); 
       } 
     }
     rmdir($dir); 
   } 
 }

On gists

Wrap text into paragraphs

PHP Helpers-Filters-Plugins

text-in-para.php #

<?php


$text = <<<TEXT
Morbi nisl tortor, consectetur vitae laoreet eu, lobortis id ipsum. Integer scelerisque blandit pulvinar. Nam tempus mi eget nunc laoreet venenatis. Proin viverra, erat at accumsan tincidunt, ante mi cursus elit, non

congue mauris dolor ac elit. Maecenas mollis nisl a sem semper ornare. Integer nunc purus, dapibus nec dignissim sed, dictum eget leo. Etiam in mi ut erat pretium fringilla sed
TEXT;

$paragraphedText = "<p>" . implode( "</p>\n\n<p>", preg_split( '/\n(?:\s*\n)+/', $text ) ) . "</p>";


echo $paragraphedText;

On gists

Function to recursively flatten multidimensional PHP array.

PHP Helpers-Filters-Plugins

flatten.php #

<?php
// Requires PHP 5.3+
// Found here: http://stackoverflow.com/a/1320156

function flatten_array(array $array) {
    $flattened_array = array();
    array_walk_recursive($array, function($a) use (&$flattened_array) { $flattened_array[] = $a; });
    return $flattened_array;
}

On gists

czech sort in array

PHP Helpers-Filters-Plugins

czech-sort.php #

<?php

function SortCzechChars($a, $b){
    static $czechCharsS = array('Á', 'Č', 'Ď', 'É', 'Ě' , 'Ch' , 'Í', 'Ň', 'Ó', 'Ř', 'Š', 'Ť', 'Ú', 'Ů' , 'Ý', 'Ž', 'á', 'č', 'ď', 'é', 'ě' , 'ch' , 'í', 'ň', 'ó', 'ř', 'š', 'ť', 'ú', 'ů' , 'ý', 'ž');
    static $czechCharsR = array('AZ','CZ','DZ','EZ','EZZ','HZZZ','IZ','NZ','OZ','RZ','SZ','TZ','UZ','UZZ','YZ','ZZ','az','cz','dz','ez','ezz','hzzz','iz','nz','oz','rz','sz','tz','uz','uzz','yz','zz');
 
    $A = str_replace($czechCharsS, $czechCharsR, $a);
    $B = str_replace($czechCharsS, $czechCharsR, $b);
 
    return strnatcasecmp($A, $B);
}

On gists

From http://code.stephenmorley.org/php/creating-downloadable-csv-files/

PHP Helpers-Filters-Plugins

csv-on-the-fly.php #

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);