/ Gists / PHP

Gists - PHP

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);

On gists

Human Readable File Size with PHP

PHP Helpers-Filters-Plugins

gistfile1.php #

<?php
# http://jeffreysambells.com/2012/10/25/human-readable-filesize-php
function human_filesize($bytes, $decimals = 2) {
    $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}

echo human_filesize(filesize('example.zip'));

On gists

PHP Curl to check if url is alive

PHP

curl_example.php #

<?php

function check_alive($url, $timeout = 10, $successOn = array(200, 301)) {
  $ch = curl_init($url);

  // Set request options
  curl_setopt_array($ch, array(
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_NOBODY => true,
    CURLOPT_TIMEOUT => $timeout,
    CURLOPT_USERAGENT => "page-check/1.0"
  ));

  // Execute request
  curl_exec($ch);

  // Check if an error occurred
  if(curl_errno($ch)) {
    curl_close($ch);
    return false;
  }

  // Get HTTP response code
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  // Page is alive if 200 OK is received
  //return $code;
  return in_array( $code, $successOn );
}

$checks = array(
	'http://www.google.co.uk',
	'http://www.facebook.com',
	'http://www.bbc.co.uk',
	'http://photogabble.co.uk',
	'http://youtube.com'
	);

foreach($checks as $check)
{
	echo $check . ' is ' . ( (check_alive($check) ) ? 'Alive' : 'Dead' ) . "\n";
}

On gists

České řazení / Czech sorting

PHP Helpers-Filters-Plugins

cs-sort.php #

<? 
setlocale(LC_ALL, 'cs_CZ.UTF-8');
header("content-type: text/html; charset=UTF-8");

$arr = explode(",", "č, d, b, a, š, ř, o, x, z, ž, á, s, m");

uasort($arr, "strcoll");
echo "<pre>" . print_r($arr, 1) . "</pre>";

?>

On gists

Recolor image From http://stackoverflow.com/questions/12178874/replace-a-color-with-another-in-an-image-with-php

PHP

recolor-image.php #

<?php
$imgname = "1.gif";
$im = imagecreatefromgif ($imgname);
$index = imagecolorexact ($im,0,128,0);
imagecolorset($im,$index,240,255,0);
$imgname = "result.gif";
imagegif($im,$imgname);
?>
<img src="result.gif">

On gists

Serverová ochrana PHP AUTH

PHP

PHP AUTH.php #

<?

$LoginSuccessful = false;
$login = $password = 'xxx';
 
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
 
    $Username = $_SERVER['PHP_AUTH_USER'];
    $Password = $_SERVER['PHP_AUTH_PW'];
 
    if ($Username == $login && $Password == $password){
        $LoginSuccessful = true;
    }
}

if (!$LoginSuccessful)
{

    header('WWW-Authenticate: Basic realm="Secret page"');
    header('HTTP/1.0 401 Unauthorized');
 
    print "Login failed!\n";
    exit(0);
 
}