Thursday, 25 January 2018

Relational vs NoSQL

NoSQL databases differ from RDBMS technology in four main areas: 1. Data Model 2. Data Structure 3. Scaling 4. Usage Cost RDBMS NoSQL Data Model RDBMS is traditional way storing the structured data in relational way. Without schema we cannot build/connect to an application. NoSQL is latest technology which is designed to handle the BigData. We can build an application without having to define the schema. Data Structure Used to store the data which is structured and defined by relations. Designed to handle the unstructured data...

How to Install Apache Cassandra on CentOS 7

Apache Cassandra is a free and open source distributed NoSQL database management system. It is used to store large data in decentralized highly available clusters. Data is distributed across many servers providing high availability and no single point of failure. NoSQL database servers stores data in other methods than the traditional tabular methods used by RDBMS softwares such as MySQL, PostgreSQL. Step 1 - Install JAVA Before installing any package it is recommended that you update the packages and repository using the following command. yum...

Tuesday, 23 January 2018

How to Use MySQL Foreign Keys for Quicker Database Development

MySQL is a fantastic open source database used by the many thousands of web applications. The default MyISAM table system is one of the simplest and fastest around, but it does not support foreign keys (although it is planned for version 6). Fortunately, the lesser-used InnoDB table type does support foreign keys: this article will show how they could reduce your coding effort and increase data integrity. What are Foreign Keys? A foreign key establishes a relationship, or constraint, between two tables. Disclaimer!...

Create Windows Shortcut in PHP

However, I've modified the code slightly so you can set a 'working folder' so you simply call the function like this: symlink (notepad.exe,newshortcut.lnk,d:\) where the shortcut will be called newshortcut, and the target being notepad.exe and the working directory being D:\ function symlink($target, $link, $workingdir) { $shell = new COM('WScript.Shell'); $shortcut = $shell->createshortcut($link); $shortcut->targetpath = $target; $shortcut->WorkingDirectory = $workingdir; $shortcut->save();...

Using PHPMailer to Send Mail through PHP

Download First, download PHPMailer using the direct link above: After you have downloaded the file, unzip and extract it to your public_html. After unzipping the file we have public_html/PHPMailer_5.2.0. Next you will need to edit your web pages to use the PHPMailer cod...

Caching for dynamic content

I made this snippet to show how to use the Last-Modified and the ETag header to optimize the caching of a website. If used correctly this will speed up your page loads. // Start output buffering, this will // catch all content so that we can // do some calculations ob_start(); // Some example HTML print '<html>'; // put your content in here: print '<h1>Example content</h1>'; print '<ul>'; for ($x=0; $x < 10; $x++)     print "<li>List item $x</li>"; print '</ul>'; print '</html>'; //...

Format string as machine compatible key

This snippet converts a "dirty" string that may contain special characters into a machine compatible nice looking string. That function works fine for creating urls or ID keys. /**  * Converts a "dirty" string that may contain special  * characters into a machine compatible nice looking string.  *  * @param     string    $string         Input string  * @return ...

Glob examples

Shows how to use the glob function to read directory listings as with "opendir" - just easier :-) $dir = './'; foreach(glob($dir.'*.txt') as $file) {     print $file . "\n"; } /* returns: ./dummy.txt ./foo.txt ./ideas.txt ./robots.txt ./scite.txt */ /* ** other examples: */ // also possible: $files = glob('*.*'); sort($files); // This shows how to use the GLOB_BRACE flag: $images = glob("images/{*.jpg,*.gif,*.png}", GLOB_BRACE); print_r($images); /*...

How to calculate the size of a directory

Returns the filesize of a whole folder including all sub folders and files. /**  * Calculate the full size of a directory  *  * @author      Jonas John  * @version     0.2  * @link        http://www.jonasjohn.de/snippets/php/dir-size.htm  * @param       string   $DirectoryPath    Directory path  */ function CalcDirectorySize($DirectoryPath)...

Random color

Generates a random hex color (like FF00FF). function random_color(){     mt_srand((double)microtime()*1000000);     $c = '';     while(strlen($c)<6){         $c .= sprintf("%02X", mt_rand(0, 255));     }     return $c; } random_color() => returns something like: '7C42BA', '5F396...

Array map

Shows how to use the array_map function. function filter_val($val){     $val = str_replace('.', '', $val);     return $val; } $a = array(     'one'   => 'two.',     'three' => 'four.',     'five'  => 'six.' ); $array = array_map('filter_val', $a); print_r($array); /* returns: Array (     [one] => two     [three] => four     [five] => six ) ...

Files by extension

Returns all files from a given folder and filters them by a given extension function get_files_by_ext($path, $ext){     $files = array();     if (is_dir($path)){         $handle = opendir($path);         while ($file = readdir($handle)) {             if ($file[0] == '.'){ continue; }             if (is_file($path.$file) and preg_match('/\.'.$ext.'$/', $file)){                 $files[]...

Preg replace callback example

Regular expressions can be very powerful, this example shows how to use the preg_replace_callback function. // Define a dummy text, for testing... $Text  = "Title: Hello world!\n"; $Text .= "Author: Jonas\n"; $Text .= "This is a example message!\n\n"; $Text .= "Title: Entry 2\n"; $Text .= "Author: Sonja\n"; $Text .= "Hello world, what's up!\n"; // This function will replace specific matches // into a new form function RewriteText($Match){     // Entire matched section:     // --> /.../     $EntireSection ...

File download

Shows how to create a simple file download by using PHP. The content could also be dynamically generated) // local file that should be send to the client $local_file = 'test.zip'; // filename that the user gets as default $download_file = 'your-download-name.zip'; if(file_exists($local_file) && is_file($local_file)) {     // send headers     header('Cache-control: private');     header('Content-Type: application/octet-stream');     header('Content-Length: '.filesize($local_file));    ...

Prefix and suffix

Prefixes or suffixes a string with n times char function str_prefix($str, $n=1, $char=" "){     for ($x=0;$x<$n;$x++){ $str = $char . $str; }     return $str; } function str_suffix($str, $n=1, $char=" "){     for ($x=0;$x<$n;$x++){ $str = $str . $char; }     return $str; } str_prefix('test', 3, '-') => returns '---test'<br/>str_suffix('test', 3, '-') => returns 'test---'<br/&g...

String2Hex and Hex2String

Convert hex to string and vice versa. function String2Hex($string){     $hex='';     for ($i=0; $i < strlen($string); $i++){         $hex .= dechex(ord($string[$i]));     }     return $hex; } function Hex2String($hex){     $string='';     for ($i=0; $i < strlen($hex)-1; $i+=2){         $string .= chr(hexdec($hex[$i].$hex[$i+1]));     }     return $string; } // example: $hex = String2Hex("test sentence..."); // $hex...

Array2object and Object2array

Convert an associative array to an anonymous object and vice versa. function array2object($array) {     if (is_array($array)) {         $obj = new StdClass();         foreach ($array as $key => $val){             $obj->$key = $val;         }     }     else { $obj = $array; }     return $obj; } function object2array($object) {     if (is_object($object)) {         foreach ($object...

Modify HTTP Headers (Examples)

Many examples that show how to use the header() function of PHP Hint: If you want to check your headers, you can use web based tools like: web-sniffer.net, web-browser extensions (e.g. LiveHTTPHeaders, ieHTTPHeaders) or another third-party software tool. // See related links for more status codes // Use this header instruction to fix 404 headers // produced by url rewriting... header('HTTP/1.1 200 OK'); // Page was not found: header('HTTP/1.1 404 Not Found'); // Access forbidden: header('HTTP/1.1 403 Forbidden'); // The page moved permanently...

Random sentence

This example shows how to create random (un-)meaningful sentences :-) Here are some example output sentences: These dogs are yellow. These cars are deadly huge!! This is a deadly cool sentence! This is a fluffy sentence! These monkeys are deadly boring! These examples are very stupid *lol* This is another monkey dog!? BTW: This also works nicely with german sentences :-) // // A list of sentences: // // %something ==> is a variable // $r_sentences = ' This is a %adjective %noun %sentence_ending This is another %noun %noun %sentence_ending I...

Array remove empty entries

Removes empty entries from a array recursivly function array_remove_empty($arr){     $narr = array();     while(list($key, $val) = each($arr)){         if (is_array($val)){             $val = array_remove_empty($val);             // does the result array contain anything?             if (count($val)!=0){                 // yes :-)              ...

Text to links

Converts plain-links into HTML-Links function text2links($str='') {     if($str=='' or !preg_match('/(http|www\.|@)/i', $str)) { return $str; }     $lines = explode("\n", $str); $new_text = '';     while (list($k,$l) = each($lines)) {         // replace links:         $l = preg_replace("/([ \t]|^)www\./i", "\\1http://www.", $l);         $l = preg_replace("/([ \t]|^)ftp\./i", "\\1ftp://ftp.", $l);         $l = preg_replace("/(http:\/\/[^...

Random password

Generates a random password by using given characters. function random_password($length, $characters='abcdefgh1234567890'){     if ($characters == ''){ return ''; }     $chars_length = strlen($characters)-1;     mt_srand((double)microtime()*1000000);     $pwd = '';     while(strlen($pwd) < $length){         $rand_char = mt_rand(0, $chars_length);         $pwd .= $characters[$rand_char];     }     return $pwd; } random_password(5,'abcd1234')...

Load and save a array dump

Loads and saves a compressed dump of an array function load_array_dump($filename) {     $fp = fopen($filename,"r");     $content = fread($fp,filesize($filename));     fclose($fp);     eval('$array='.gzuncompress(stripslashes($content)).';');     return($array); } function save_array_dump($filename, $array) {     $dump = addslashes(gzcompress(var_export($array,true),9));     $fp = fopen($filename, "wb+");     fwrite($fp, $dump);     fclose($fp); } save_array_dump('test.txt',...

Merge two strings

Merges two strings in a way that a pattern like ABABAB will be the result. /**  * Merges two strings in a way that a pattern like ABABAB will be  * the result.  *  * @param     string    $str1   String A  * @param     string    $str2   String B  * @return    string    Merged string  */  function MergeBetween($str1, $str2){     // Split both strings     $str1 = str_split($str1, 1);    ...

Miscellaneous things

Miscellaneous short code snippets // report all errors: error_reporting(E_ALL); // the full path to the current file print __FILE__; // print the current line print __LINE__; // print the current class name print __CLASS__; // print the current method name print __METHOD__; // the current directory print dirname(__FILE__); // directory separator of the current // system (windows = \ and linux = /) print DIRECTORY_SEPARATOR; // server variables: print $_SERVER["HTTP_HOST"]; print $_SERVER["REQUEST_URI"]; // more: HTTP_REFERER, SCRIPT_NAME,...

List directory contents by date

Loads the contens of a dir an sorts them by the date of creation. function listdir_by_date($path){     $dir = opendir($path);     $list = array();     while($file = readdir($dir)){         if ($file != '.' and $file != '..'){             // add the filename, to be sure not to             // overwrite a array key             $ctime = filectime($data_path . $file) . ',' . $file;        ...

Add ending slash

Adds an ending slash to the given path, makes a difference between windows and unix paths (keeps orginal slashes) The normalize_path function is also a good way for doing this... function add_ending_slash($path){     $slash_type = (strpos($path, '\\')===0) ? 'win' : 'unix';     $last_char = substr($path, strlen($path)-1, 1);     if ($last_char != '/' and $last_char != '\\') {         // no slash:         $path .= ($slash_type == 'win') ? '\\' : '/';     }  ...

File download with speed limit

This snippet shows you how to limit the download rate of a file download. // local file that should be send to the client $local_file = 'test-file.zip'; // filename that the user gets as default $download_file = 'your-download-name.zip'; // set the download rate limit (=> 20,5 kb/s) $download_rate = 20.5; if(file_exists($local_file) && is_file($local_file)) {     // send headers     header('Cache-control: private');     header('Content-Type: application/octet-stream');     header('Content-Length:...

Simple MS-SQL example

This is a simple example on how to query a Microsoft SQL Server by using PHP. /* ** Connect to database: */ // Connect to the database (host, username, password) $con = mssql_connect('localhost','admin','foo')     or die('Could not connect to the server!'); // Select a database: mssql_select_db('Northwind')     or die('Could not select a database.'); // Example query: (TOP 10 equal LIMIT 0,10 in MySQL) $SQL = "SELECT TOP 10 * FROM ExampleTable ORDER BY ID ASC"; // Execute query: $result = mssql_query($SQL)    ...

Snoopy example

Shows how an example how you can use the Snoopy class for doing HTTP requests to other websites. /* You need the snoopy.class.php from http://snoopy.sourceforge.net/ */ include("snoopy.class.php"); $snoopy = new Snoopy; // need an proxy?: //$snoopy->proxy_host = "my.proxy.host"; //$snoopy->proxy_port = "8080"; // set browser and referer: $snoopy->agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; $snoopy->referer = "http://www.jonasjohn.de/"; // set some cookies: $snoopy->cookies["SessionID"] = '238472834723489'; $snoopy->cookies["favoriteColor"]...

Starts with

Tests if a text starts with an given string. /**  * StartsWith  * Tests if a text starts with an given string.  *  * @param     string  * @param     string  * @return    bool  */ function StartsWith($Haystack, $Needle){     // Recommended version, using strpos     return strpos($Haystack, $Needle) === 0; } // Another way, using substr function StartsWithOld($Haystack, $Needle){     return substr($Haystack, 0, strlen($Needle)) == $Needle; } $ExampleText...

Count files recursive

Returns the entire number of files including all child directories. function count_files($path) {     // (Ensure that the path contains an ending slash)     $file_count = 0;     $dir_handle = opendir($path);     if (!$dir_handle) return -1;     while ($file = readdir($dir_handle)) {         if ($file == '.' || $file == '..') continue;         if (is_dir($path . $file)){                  $file_count += count_files($path...

DomXML Example

This short example shows how to use the DomXML extension. To try this example you need to have the DomXML extension enabled. // example HTML code: (could also come from an URL) $html = '<html> <head> <title>links</title> </head> <body> <a href="link1.htm" title="Link title 1" target="_blank">Link #1</a><br/> <a href="link2.htm" title="Link title 2" target="_blank">Link #2</a><br/> <a href="link3.htm" title="Link title 3" target="_blank">Link #3</a><br/> </body> </html>'; //...

Simple HTTP authentication example

Shows how to use the WWW-Authenticate header to create simple logins. // Status flag: $LoginSuccessful = false; // Check username and password: if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){     $Username = $_SERVER['PHP_AUTH_USER'];     $Password = $_SERVER['PHP_AUTH_PW'];     if ($Username == 'jonas' && $Password == 'foobar'){         $LoginSuccessful = true;     } } // Login passed successful? if (!$LoginSuccessful){     /*  ...

Datetime Design Pattern Microformat

This example shows how to implement the Microformat Datetime Design Pattern in PHP. <?php     $UnixTimeStamp = time();     $Title      = strftime('%Y-%m-%dT%H:%M:%SZ', $UnixTimeStamp);     $Caption    = strftime('%B %d, %Y at %H:%M', $UnixTimeStamp);     print '<abbr class="date" title="'. $Title .'">'. $Caption .'</abbr>'; ?> <!-- example result --> <abbr class="date" title="2007-07-25T20:15:21Z">July 25, 2007 at 20:15</abbr&g...

How to block multiple IP adresses

Shows how to block multiple IP adresses // Denied IP's.     $deny_ips = array(         '127.0.0.1',         '192.168.100.1',         '192.168.200.1',         '192.168.300.1',         'xxx.xxx.xxx.xxx'     );     // $deny_ips = file('blocked_ips.txt');     // read user ip adress:     $ip = isset($_SERVER['REMOTE_ADDR']) ? trim($_SERVER['REMOTE_ADDR']) : '';     // search current IP in...

array_walk example

Shows how to use the array_walk function to format an array. // the test array $array = array(     'php', 'arrays', 'are', 'cool'    ); // some variable for testing: $some_var = 'NEW'; // the function that get's called for each entry function format_array_values(&$item, $key, $some_var) {     $item = $some_var . ": $item (KEY: $key)<br/>"; } // "walk" trough each array item and call the function: // "format_array_values" array_walk($array, 'format_array_values', $some_var); // print the result: print_r($array); /* The...

Printf and sscanf examples

This example shows how to use the printf() and sscanf() functions. (You can also replace printf() with sprintf() to return a result instead of printing it). More detailed informations: php.net $file = "test.txt"; $lines = 7; printf("The file %s consists of %d lines\n", $file, $lines); // returns --> The file test.txt consists of 7 lines // padding something, prefix a string with "_" $word = 'foobar'; printf("%'_10s\n", $word); // returns --> ____foobar // format a number: $number = 100.85995; printf("%03d\n", $number); // returns -->...

Count lines and their occurrences

These two functions show how to create a list of all lines and their occurrences in a given file or string. /**  * LineStatisticsByFile  * Creates a list with all lines of the given file and their occurrences.  *  * @param     string  * @param     bool  * @return    string  */ function LineStatisticsByFile($Filepath, $IgnoreCase=false, $NewLine="\n"){     if (!file_exists($Filepath)){         $ErrorMsg  = 'LineStatisticsByFile error:...

Simple cURL example

Simple example on how to use the cURL module to download a website or any other file. You can find more cURL options on the related PHP manual page. function curl_download($Url){     // is cURL installed yet?     if (!function_exists('curl_init')){         die('Sorry cURL is not installed!');     }     // OK cool - then let's create a new cURL resource handle     $ch = curl_init();     // Now set some options (most are optional)     // Set URL to download  ...

Restore htmlspecialchars

Restores the characters fixed with the htmlspecialchars() function function restore_hsc($len){     $val = str_replace('&amp;', '&', $val);     $val = str_replace('&ouml;', '�', $val);     $val = str_replace('&auml;', '�', $val);     $val = str_replace('&uuml;', '�', $val);     $val = str_replace('&lt;', '<', $val);     $val = str_replace('&gt;', '>', $val);     $val = str_replace('&quot;', '"', $val);     return $val; } rest...

MD5-based block cipher

Below is a MD5-based block cipher (MDC-like), which works in 128bit CFB mode. It is very useful to encrypt secret data before transfer it over the network. function md5_encrypt($plain_text, $password, $iv_len = 16){     $plain_text .= "\x13";     $n = strlen($plain_text);     if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));     $i = 0;     $enc_text = get_rnd_iv($iv_len);     $iv = substr($password ^ $enc_text, 0, 512);     while ($i < $n) {      ...

Randomize array

This function simply randomizes array values. // I noticed that there is already a built-in function that // does the same - so don't use mine ;-) // // --> shuffle($Array); // // http://de2.php.net/manual/de/function.shuffle.php // function RandomizeArray($array){     // error check:     $array = (!is_array($array)) ? array($array) : $array;     $a = array();     $max = count($array) + 10;     while(count($array) > 0){                $e = array_shift($array);  ...

Remove duplicated values

Removes duplicated entries in a array (only first level) Warning this will remove all keys function remove_duplicated_values($arr){     $_a = array();     while(list($key,$val) = each($arr)){         $_a[$val] = 1;     }     return array_keys($_a); } remove_duplicated_values(array('a', 'b', 'c', 'a')); --> returns array('a','b','c...

A easy way to check the file size

Converts a string like "5 MB", or "400 KB" to the equivalent in Bytes. function StringSizeToBytes($Size){     $Unit = strtolower($Size);     $Unit = preg_replace('/[^a-z]/', '', $Unit);     $Value = intval(preg_replace('/[^0-9]/', '', $Size));     $Units = array('b'=>0, 'kb'=>1, 'mb'=>2, 'gb'=>3, 'tb'=>4);     $Exponent = isset($Units[$Unit]) ? $Units[$Unit] : 0;     return ($Value * pow(1024, $Exponent));            } // Example usage: //...

Trim array (recursive)

Cleans a entire array recursivly. /**  * Trims a entire array recursivly.  *  * @author      Jonas John  * @version     0.2  * @link        http://www.jonasjohn.de/snippets/php/trim-array.htm  * @param       array      $Input      Input array  */ function TrimArray($Input){     if (!is_array($Input))         return trim($Input);     return array_map('TrimArray', $Input); } /* Old...

Simple hand-made hash function

This example shows how to create a one-way encryption method by using a very simplified algorithm. function SimpleHash($str){        $n = 0;     // The magic happens here:     // I just loop trough all letters and add the     // ASCII value to a integer variable.     for ($c=0; $c < strlen($str); $c++)         $n += ord($str[$c]);     // After we went trough all letters     // we have a number that represents the     // content...

String get between

Returns the content between $start and $end function GetBetween($content,$start,$end){     $r = explode($start, $content);     if (isset($r[1])){         $r = explode($end, $r[1]);         return $r[0];     }     return ''; } GetBetween('foo test bar', 'foo', 'bar'); // --> returns ' test ...

array_walk debug example

Shows how to use the array_walk function to debug and print an array in a human readable format. function debug_val($val, $key='', $depth=0) {     if (is_array($val)){         // call this function again with the "sub-array":         array_walk($val, 'debug_val', $depth+5);     }     else {         // if we hit a string or bool, etc. then print it:         print str_repeat('&nbsp;', $depth);           ...

Safe redirect

This little function ensures that visitors are really redirected to a specified URL. At first the function will try to redirect the user by using the header() location method, then by JavaScript and META-Refresh and finally if everything failed there is also a ordinary link to the new URL. function safe_redirect($url, $exit=true) {     // Only use the header redirection if headers are not already sent     if (!headers_sent()){         header('HTTP/1.1 301 Moved Permanently');        ...

Simple Syntax highlighting

Shows how to create a simple syntax highlighting function for PHP code. Warning: This function is very simple and may not handle complicated or obfuscated PHP code ;-) function syntax_highlight($code){     // this matches --> "foobar" <--     $code = preg_replace(         '/"(.*?)"/U',         '&quot;<span style="color: #007F00">$1</span>&quot;', $code     );     // hightlight functions and other structures like --> function foobar()...