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 ( Ex: Text, Email , Image, Video ).
Scaling Required single server to host the entire database and Vertical scaling is costly to afford. This is much cheaper to scale compared to relational database.
Usage Cost Licensed and costly. Open-source and ready to use.

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 -y update
Once your system is updated, we will install the latest version of Oracle Java into the server. Run the following command to download the RPM package.
wget --no-cookies --no-check-certificate --header "Cookie:oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm"
If you do not have wget installed, you can run the yum -y install wget to install wget. Now install the downloaded RPM using the following command.
yum -y localinstall jdk-8u131-linux-x64.rpm
You can now check the Java version using the following command.
java -version
You will get the following output.
[root@liptan-pc ~]# java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
You will also need to check if JAVA_HOME environment variable is set. Run the following command for same.
echo $JAVA_HOME
If you get a null or blank output, you will need to manually set the JAVA_HOME variable. Edit the .bash_profile file using your favourite editor. In this tutorial, we will use nano editor. Run the following command to edit .bash_profile using nano.
nano ~/.bash_profile
Now add the following lines at the at the end of the file.
export JAVA_HOME=/usr/java/jdk1.8.0_131/
export JRE_HOME=/usr/java/jdk1.8.0_131/jre
Now source the file using the following command.
source ~/.bash_profile
Now you can run the echo $JAVA_HOME command again to check if the environment variable is set or not.
[root@liptan-pc ~]# echo $JAVA_HOME 
/usr/java/jdk1.8.0_131/

Step 2 - Installing Cassandra

Now add Apache Cassandra repository into your repository list by creating a new repository file.
nano /etc/yum.repos.d/cassandra.repo
Now add the following content into the file.
[cassandra]
name=Apache Cassandra
baseurl=https://www.apache.org/dist/cassandra/redhat/311x/
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://www.apache.org/dist/cassandra/KEYS
You can now install Apache Cassandra by running the following command.
yum -y install cassandra
Reload your system daemons by running:
systemctl daemon-reload
You can now start Cassandra by typing;
systemctl start cassandra
To enable Cassandra to automatically start at boot time, run:
systemctl enable cassandra
You can verify that Cassandra is running by typing the following command.
nodetool status
You should see similar output if Cassandra is running.
[root@ip-172-31-7-136 ~]# nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens       Owns (effective)  Host ID                               Rack
UN  127.0.0.1  136.29 KiB  256          100.0%            b3d26649-9e10-4bee-9b3c-8e81c4394b2e  rack1

Instead of the output shown above, if you get something similar to the output below, then you will need to configure cassandra environment configuration file.
nodetool: Failed to connect to '127.0.0.1:7199' - ConnectException: 'Connection refused (Connection refused)'.
Open the configuration file using following command.
nano /etc/cassandra/default.conf/cassandra-env.sh
Now find the following line in configuration.
# JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=<public name>"
Uncomment the line and change its value form <public_name> to the localhost IP address 127.0.0.1.
The configuration should look like shown below.
JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=127.0.0.1"
Save the file and exit from editor, restart Apache Cassandra by running the following command.
systemctl restart cassandra
You should have the desired output while running the nodetool command.
Cassandra comes with a powerful command line shell cqlsh to run query on Cluster. Query is written in CQL or Cassandra Query language. To access CQL shell, run the following command.
cqlsh
You will see following output.

[root@liptan-pc ~]# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.0 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.

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! For the purpose of this example, we will create two simple database tables. They are not well designed, but will demonstrate the power of foreign keys!
  • employee: a table of company employees where each member is assigned a unique ID
  • borrowed: a table of borrowed books. Every record will reference a borrower’s employee ID.
We will define a foreign key relationship between the employee’s ID in both tables. This provides a couple of advantages:
  1. It is not possible to enter an invalid employee ID in the ‘borrowed’ table.
  2. Employee changes are handled automatically by MySQL.

Creating an Example Database

Our example database is created as follows:
CREATE DATABASE mydb;
USE mydb;
We now define our two tables. Note that InnoDB is specified as the table type and we will also add an index for the employee’s last name.

CREATE TABLE employee (
 id smallint(5) unsigned NOT NULL,
 firstname varchar(30),
 lastname varchar(30),
 birthdate date,
 PRIMARY KEY (id),
 KEY idx_lastname (lastname)
) ENGINE=InnoDB;

CREATE TABLE borrowed (
 ref int(10) unsigned NOT NULL auto_increment,
 employeeid smallint(5) unsigned NOT NULL,
 book varchar(50),
 PRIMARY KEY (ref)
) ENGINE=InnoDB;
We can now specify our foreign key (this could be handled in the CREATE TABLE statement, but it is shown separately here):

ALTER TABLE borrowed 
ADD CONSTRAINT FK_borrowed 
FOREIGN KEY (employeeid) REFERENCES employee(id) 
ON UPDATE CASCADE
ON DELETE CASCADE;
This tells MySQL that we want to alter the borrowed table by adding a constraint called ‘FK_borrowed’. The employeeid column will reference the id column in the employee table – in other words, an employee must exist before they can borrow a book.
The final two lines are perhaps the most interesting. They state that if an employee ID is updated or an employee is deleted, the changes should be applied to the borrowed table.

Adding Table Data

We will now populate the tables with data. Remember that our employees must be added first:
employee:
id firstname lastname birthdate
1 John Smith 1976-01-02
2 Laura Jones 1969-09-05
3 Jane Green 1967-07-15
borrowed:
ref employeeid book
1 1 SitePoint Simply SQL
2 1 SitePoint Ultimate HTML Reference
3 1 SitePoint Ultimate CSS Reference
4 2 SitePoint Art and Science of JavaScript
The table shows that John has borrowed 3 books, Laura has borrowed 1, and Jane has not borrowed any. Standard SQL queries can be run to find useful information such as “which books has John borrowed”:

SELECT book FROM borrowed 
JOIN employee ON employee.id=borrowed.employeeid 
WHERE employee.lastname='Smith';
Result:
SitePoint Simply SQL
SitePoint Ultimate HTML Reference
SitePoint Ultimate CSS Reference

Cascading in Action

The Accounts Department calls us with a problem: Laura’s employee ID must be changed from 2 to 22 owing to a clerical error. With standard MyISAM tables, you would need to change every table that referenced the employee ID. However, our InnoDB constraints ensure that changes are cascaded following a single update:

UPDATE employee SET id=22 WHERE id=2;
If we examine our borrowed table, we will find that the update has occurred without us needing to run additional code:
borrowed:
ref employeeid book
1 1 SitePoint Simply SQL
2 1 SitePoint Ultimate HTML Reference
3 1 SitePoint Ultimate CSS Reference
4 22 SitePoint Art and Science of JavaScript
It is a busy day and we now have the Personnel Department on the phone. John’s learnt so much from the SitePoint books, he’s left the company to set up on his own (he was frisked at the door to ensure he returned them all). Again, we need a single SQL statement:

DELETE FROM employee WHERE id=1;
The deletion is cascaded through to our borrowed table, so all John’s references are removed:
borrowed:
ref employeeid book
4 22 SitePoint Art and Science of JavaScript
Although this is a simple example, it demonstrates the power of foreign keys. It is easy to retain data integrity without additional code or complex series of SQL commands. Note there are other alternatives to ‘CASCADE’ in your UPDATE and DELETE definitions:
  • NO ACTION or RESTRICT: the update/delete is rejected if there are one or more related foreign key values in a referencing table, i.e. you could not delete the employee until their books had been returned.
  • SET NULL: update/delete the parent table row, but set the mis-matching foreign key columns in our child table to NULL (note that the table column must not be defined as NOT NULL).

The same concepts can be applied to large-scale databases containing dozens of tables with inter-linked relationships.

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




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 code.

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

// or include() something here


// Now save all the content from above into
// a variable
$PageContent = ob_get_contents();

// And clear the buffer, so the
// contents will not be submitted to
// the client (we do that later manually)
ob_end_clean();


// Generate unique Hash-ID by using MD5
$HashID = md5($PageContent);

// Specify the time when the page has
// been changed. For example this date
// can come from the database or any
// file. Here we define a fixed date value:
$LastChangeTime = 1144055759;

// Define the proxy or cache expire time
$ExpireTime = 3600; // seconds (= one hour)

// Get request headers:
$headers = apache_request_headers();
// you could also use getallheaders() or $_SERVER
// or HTTP_SERVER_VARS

// Add the content type of your page
header('Content-Type: text/html');

// Content language
header('Content-language: en');

// Set cache/proxy informations:
header('Cache-Control: max-age=' . $ExpireTime); // must-revalidate
header('Expires: '.gmdate('D, d M Y H:i:s', time()+$ExpireTime).' GMT');

// Set last modified (this helps search engines
// and other web tools to determine if a page has
// been updated)
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $LastChangeTime).' GMT');

// Send a "ETag" which represents the content
// (this helps browsers to determine if the page
// has been changed or if it can be loaded from
// the cache - this will speed up the page loading)
header('ETag: ' . $HashID);


// The browser "asks" us if the requested page has
// been changed and sends the last modified date he
// has in it's internal cache. So now we can check
// if the submitted time equals our internal time value.
// If yes then the page did not get updated

$PageWasUpdated = !(isset($headers['If-Modified-Since']) and
    strtotime($headers['If-Modified-Since']) == $LastChangeTime);


// The second possibility is that the browser sends us
// the last Hash-ID he has. If he does we can determine
// if he has the latest version by comparing both IDs.

$DoIDsMatch = (isset($headers['If-None-Match']) and
    ereg($HashID, $headers['If-None-Match']));

// Does one of the two ways apply?
if (!$PageWasUpdated or $DoIDsMatch){

    // Okay, the browser already has the
    // latest version of our page in his
    // cache. So just tell him that
    // the page was not modified and DON'T
    // send the content -> this saves bandwith and
    // speeds up the loading for the visitor

    header('HTTP/1.1 304 Not Modified');

    // That's all, now close the connection:
    header('Connection: close');

    // The magical part:
    // No content here ;-)
    // Just the headers

}
else {

    // Okay, the browser does not have the
    // latest version or does not have any
    // version cached. So we have to send him
    // the full page.

    header('HTTP/1.1 200 OK');

    // Tell the browser which size the content
    header('Content-Length: ' . strlen($PageContent));

    // Send the full content
    print $PageContent;
}

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    array     Formatted string   
 */
function FormatAsKey($string){

    $string = strtolower($string);

    // Fix german special chars
    $string = preg_replace('/[äÄ]/', 'ae', $string);
    $string = preg_replace('/[üÜ]/', 'ue', $string);
    $string = preg_replace('/[öÖ]/', 'oe', $string);
    $string = preg_replace('/[ß]/', 'ss', $string);

    // Replace other special chars
    $specialChars = array(
        'sharp' => '#', 'dot' => '.', 'plus' => '+',
        'and' => '&', 'percent' => '%', 'dollar' => '$',
        'equals' => '=',
    );

    while(list($replacement, $char) = each($specialChars))
        $string = str_replace($char, '-' . $replacement . '-', $string);

    $string = strtr(
        $string,
        "ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ",
        "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn"
    );

    // Remove all remaining other unknown characters     
    $string = preg_replace('/[^a-z0-9\-]/', '-', $string);
    $string = preg_replace('/^[\-]+/', '', $string);
    $string = preg_replace('/[\-]+$/', '', $string);
    $string = preg_replace('/[\-]{2,}/', '-', $string);

    return $string;
}

/**
 * Examples:
 */

print FormatAsKey("** this + that = something **") . "\n";
print FormatAsKey("100% freeware!") . "\n";
print FormatAsKey("Das ist übermäßig öffentlich") . "\n";
print FormatAsKey("Another sentence...") . "\n";

/*
Output:

this-plus-that-equals-something
100-percent-freeware
das-ist-uebermaessig-oeffentlich
another-sentence-dot-dot-dot
*/

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


/* Valid flags:

GLOB_MARK
GLOB_NOSORT
GLOB_NOCHECK
GLOB_NOESCAPE
GLOB_BRACE
GLOB_ONLYDIR
GLOB_ERR

see PHP.net manual for more info
*/



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

    // I reccomend using a normalize_path function here
    // to make sure $DirectoryPath contains an ending slash
    // (-> http://www.jonasjohn.de/snippets/php/normalize-path.htm)

    // To display a good looking size you can use a readable_filesize
    // function.
    // (-> http://www.jonasjohn.de/snippets/php/readable-filesize.htm)

    $Size = 0;

    $Dir = opendir($DirectoryPath);

    if (!$Dir)
        return -1;

    while (($File = readdir($Dir)) !== false) {

        // Skip file pointers
        if ($File[0] == '.') continue;

        // Go recursive down, or add the file size
        if (is_dir($DirectoryPath . $File))         
            $Size += CalcDirectorySize($DirectoryPath . $File . DIRECTORY_SEPARATOR);
        else
            $Size += filesize($DirectoryPath . $File);     
    }

    closedir($Dir);

    return $Size;
}
$SizeInBytes = CalcDirectorySize('data/');


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', '5F3964'

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[] = $file;
            }
        }
        closedir($handle);
        sort($files);
    }

    return $files;

}

/*
** Example:
*/

print_r(get_files_by_ext('data/', 'txt'));

/*
returns:

Array
(
    [0] => readme_1.txt
    [1] => readme_2.txt
)

*/

dir_list('data/', 'txt'); => returns all *.txt files from the data/ folder

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  = $Match[0];
    // --> "\nTitle: Hello world!"

    // Key
    // --> ([a-z0-9]+)
    $Key            = $Match[1];
    // --> "Title"

    // Value
    // --> ([^\n\r]+)
    $Value        = $Match[2];
    // --> "Hello world!"

    // Add some bold (<b>) tags to around the key to
    return '<b>' . $Key . '</b>: ' . $Value;
}

// The regular expression will extract and pass all "key: value" pairs to
// the "RewriteText" function that is definied above
$NewText = preg_replace_callback('/[\r\n]([a-z0-9]+): ([^\n\r]+)/i', "RewriteText", $Text);

// Print the new modified text
print $NewText;

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));
    header('Content-Disposition: filename='.$download_file);

    // flush content
    flush();

    /*
    ** You can also remove the following part and
    ** replace it trough a database command fetching
    ** the download data
    */
    // open file stream
    $file = fopen($local_file, "rb");

    // send the file to the browser
    print fread ($file, filesize($local_file));

    // close file stream
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}

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/>

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 contains 746573742073656e74656e63652e2e2e

print Hex2String($hex);
// outputs: test sentence...

<?php

//By Alexander Rath
// Improvements:
// - Chars under 0x10 now work
// - Cleaner Code
// - Speed Improvements

//Notice that this does not REALLY return a Hex,
//it returns a String containing the Hex...
//(otherwise Strings would have to be pretty short on a 64bit Enviroment :P)

function str2hex($func_string) {
$func_retVal = '';
$func_length = strlen($func_string);
for($func_index = 0; $func_index < $func_length; ++$func_index) $func_retVal .= ((($c = dechex(ord($func_string{$func_index}))) && strlen($c) & 2) ? $c : "0{$c}");

return strtoupper($func_retVal);
}

function hex2str($func_string) {
$func_retVal = '';
$func_length = strlen($func_string);
for($func_index = 0; $func_index < $func_length; ++$func_index) $func_retVal .= chr(hexdec($func_string{$func_index} . $func_string{++$func_index}));

return $func_retVal;
}

//Example:
$hex = str2hex("This is my Test StringnEven Multiline works now!");
echo "{$hex}n"; //Outputs "54686973206973206D79205465737420537472696E670A4576656E204D756C74696C696E6520776F726B73206E6F7721"
echo hex2str($hex) . "n"; //Outputs "This is my Test String
// Even Multiline works now!"

?>

There is a bug:
<?php

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("This isnmultiline :)");
// $hex contains 54686973206973a6d756c74696c696e65203a29
// Notice the a between 54686973206973 and 6d756c74696c696e65203a29
// Hex2String expects that every char was converted to 2 chars, but
// since n equals to dec 10 which is hex a (and not 0a), it returns
// some weird mess

print Hex2String($hex);
// outputs: This is??V?F?Ɩ?R?

?>

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 as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
}


// example:

$array = array('foo' => 'bar', 'one' => 'two', 'three' => 'four');

$obj = array2object($array);

print $obj->one; // output's "two"

$arr = object2array($obj);

print $arr['foo']; // output's bar


I had to modify the object2array so it would go recursive and transform objects inside of an array into array as well, thought I would share

function object2array($object) {
if (is_object($object) || is_array($object)) {
foreach ($object as $key => $value) {
print "$key\r\n";
$array[$key] = $this->object2array($value);
}
}else {
$array = $object;
}
return $array;
}


yes i have,
recursive call of the function array2object for multidimensional arrays

function array2object($arrGiven){
//create empty class
$objResult=new stdClass();

foreach ($arrLinklist as $key => $value){
//recursive call for multidimensional arrays
if(is_array($value)) $value=array2object($value);


$objResult->{$key}=$value;
}
return $objResult;
}

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 should be used for
// all redrictions, because search engines know
// what's going on and can easily update their urls.
header('HTTP/1.1 301 Moved Permanently');

// Server error
header('HTTP/1.1 500 Internal Server Error');

// Redirect to a new location:
header('Location: http://www.example.org/');

// Redriect with a delay:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';

// you can also use the HTML syntax:
// <meta http-equiv="refresh" content="10;http://www.example.org/ />

// override X-Powered-By value
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');

// content language (en = English)
header('Content-language: en');

// last modified (good for caching)
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');

// header for telling the browser that the content
// did not get changed
header('HTTP/1.1 304 Not Modified');

// set content length (good for caching):
header('Content-Length: 1234');

// Headers for an download:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

// Disable caching of the current document:
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');

// set content type:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); // plain text file
header('Content-Type: image/jpeg'); // JPG picture
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/pdf'); // PDF file
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file
header('Content-Type: application/x-shockwave-flash'); // Flash animation

// show sign in box
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';



Sometimes depending on the situation i use to put some html code too. Here is an example in php.

function showForbidden()
{
header('HTTP/1.1 403 Forbidden');

echo("<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>");
}



// Headers for an download:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

sometimes header not work ,but don't show any error message
code follow:
header( "HTTP/1.1 301 Moved Permanently" );
header( "Location:{$url}" );
exit();

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 %love_or_hate %nouns , because it is %adjective %sentence_ending
My %family says you are not %adjective %sentence_ending
These %nouns are %adjective %sentence_ending
';

//
// This is another list of variables:
// (This list can also contain variables (like %something))
//
// Formatting:
// (first-line) = Variablename
// (second-line) = Variables (seperated by semicolon)
//

$r_variables = '
adjective
%adjective_list;very %adjective_list;deadly %adjective_list

adjective_list
big;huge;small;red;blue;cool;yellow;pink;fluffy;stupid;clever;fat;lazy;boring

noun
%noun_list;%adjective %noun_list

noun_list
sentence;beer;cow;monkey;donkey;example;ice cream;dog

nouns
beers;monkeys;donkeys;examples;cars;trees;birds;dogs

love_or_hate
love;hate;like

family
%adjective %family_members;%family_members

family_members
grandpa;brother;sister;mom;dad;grandma

sentence_ending
.;!;!!;!?;*lol*
';

// strip spaces:
$r_sentences = trim($r_sentences);
$r_variables = trim($r_variables);

// fix new lines and split sentences up:
$r_sentences = str_replace("\r\n", "\n", $r_sentences);
$r_sentences = str_replace("\r", "\n", $r_sentences);
$r_sentences = explode("\n", $r_sentences);

$r_variables = str_replace("\r\n", "\n", $r_variables);
$r_variables = str_replace("\r", "\n", $r_variables);
$r_variables = explode("\n\n", $r_variables);

// this array contains all variables:
$r_vars = array();

// go trough all variables:
for($x=0; $x < count($r_variables); $x++){

    $var = explode("\n", trim($r_variables[$x]));

    // lowecase all:
    $key = strtolower(trim($var[0]));

    // split words:
    $words = explode(";", trim($var[1]));

    // add variables to the $r_vars Array
    $r_vars[$key] = $words;

}

// returns a word from the variables array:
function get_word($key){
    global $r_vars;

    if (isset($r_vars[$key])){

        $words = $r_vars[$key];

        // calc max.
        $w_max = count($words)-1;
        $w_rand = rand(0, $w_max);

        // return the word, and check if the word contains
        // another variable:
        return replace_words(trim($words[$w_rand]));

    }
    else {
        // the word was not found :-(
        return "(Error: Word '$key' was not found!)";
    }

}

// this function replaces a variable like %something with
// the proper variable-value:

function replace_words($sentence){

    // if there are no variables in the sentence,
    // return it without doing anything
    if (str_replace('%', '', $sentence) == $sentence)
        return $sentence;

    // split the words up:
    $words = explode(" ", $sentence);

    $new_sentence = array();

    // go trough all words:
    for($w=0; $w < count($words); $w++){

        $word = trim($words[$w]);

        if ($word != ''){

            // is this word a variable?
            if (preg_match('/^%(.*)$/', $word, $m)){

                // --> yes
                $varkey = trim($m[1]);

                // get the proper word from the variable list:
                $new_sentence[] = get_word($varkey);
            }
            else {
                // --> no it is a default word
                $new_sentence[] = $word;
            }

        }

    }

    // join the array to a new sentence:
    return implode(" ", $new_sentence);   
}

// calc. max.
$max_s = count($r_sentences)-1;
$rand_s = rand(0, $max_s);

// get a random sentence:
$sentence = $r_sentences[$rand_s];

// format the resulting sentence, so that I looks nice:
// (delete whitespace infront of punctuation marks)
$sentence = str_replace(' ,', ',', ucfirst(replace_words($sentence)));
$sentence = str_replace(' .', '.', $sentence);
$sentence = str_replace(' !', '!', $sentence);
$sentence = str_replace(' ?', '?', $sentence);
$sentence = trim($sentence);

// finally print the new sentence! :-D
print $sentence;

---------------------------------------------------------
There is a small glitch in the code that makes it unusable in some cases (like mine !), just change this :

$r_variables = str_replace("rn", "n", $r_variables);
$r_variables = str_replace("r", "n", $r_variables);
$r_variables = explode("nn", $r_variables);

Into this :

$r_variables = str_replace("rn", "n", $r_variables);
$r_variables = str_replace("r", "n", $r_variables);
$r_variables = preg_replace("/ns*n/", "nn", $r_variables);
$r_variables = explode("nn", $r_variables);

Just add the preg_replace, this will ensure that the variables newlines are cleanly formatted.

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 :-)
                $narr[$key] = $val;
            }
        }
        else {
            if (trim($val) != ""){
                $narr[$key] = $val;
            }
        }
    }
    unset($arr);
    return $narr;
}
array_remove_empty(array(1,2,3, '', array(), 4)) => returns array(1,2,3,4)

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:\/\/[^ )\r\n!]+)/i",
            "<a href=\"\\1\">\\1</a>", $l);

        $l = preg_replace("/(https:\/\/[^ )\r\n!]+)/i",
            "<a href=\"\\1\">\\1</a>", $l);

        $l = preg_replace("/(ftp:\/\/[^ )\r\n!]+)/i",
            "<a href=\"\\1\">\\1</a>", $l);

        $l = preg_replace(
            "/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/i",
            "<a href=\"mailto:\\1\">\\1</a>", $l);

        $new_text .= $l."\n";
    }

    return $new_text;
}

$text = "Visit https://thiscode4u.blogspot.com/ :-)";

print text2links($text);

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') => returns something like: '2b4d3'

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', array(1,2,3));

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);
    $str2 = str_split($str2, 1);

    // Swap variables if string 1 is larger than string 2
    if (count($str1) >= count($str2))
        list($str1, $str2) = array($str2, $str1);

    // Append the shorter string to the longer string
    for($x=0; $x < count($str1); $x++)
        $str2[$x] .= $str1[$x];

    return implode('', $str2);
}

print MergeBetween('abcdef', '__') . "\n";
print MergeBetween('__', 'abcdef') . "\n";
print MergeBetween('bb', 'aa') . "\n";
print MergeBetween('aa', 'bb') . "\n";
print MergeBetween('a', 'b') . "\n";

/*
Output:

a_b_cdef
a_b_cdef
baba
abab
ab
*/

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, SERVER_URL

// output all:
print_r($_SERVER);

// constants:
if (!defined('SOMETHING')) {
    define(SOMETHING, "foobar");
}
print SOMETHING;


// special syntax for long strings:
// the variable goes till it finds
// the closing word "EOF;" (it can also be renamed)
$test =<<<EOF
This is an example of an <b>long</b> variable.
You can also put {$some_variables} in here :-)
EOF;
// ^ do not use any spaces in the line above (just "EOQ;")


// sprintf usage:
print sprintf("here you see var1: %s and var2: %s", $var1, $var2);


// this function prints it's own name ("test"):
function test(){
    print __FUNCTION__;
}

// more reserved constants at:
// http://de2.php.net/manual/en/reserved.constants.php

The define()-function requires a string as the first parameter.

Instead of:
---------
// constants:
if (!defined('SOMETHING')) {
define(SOMETHING, "foobar");
}
print SOMETHING;
--------

You could simplify it and do the following:

------------
// constants:
defined('SOMETHING') or define(SOMETHING, "foobar");
print SOMETHING;
---------

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;
            $list[$ctime] = $file;
        }
    }
    closedir($dir);
    krsort($list);
    return $list;
}
listdir_by_date('data/');

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') ? '\\' : '/';
    }

    return $path;
}

print add_ending_slash(dirname(__FILE__));
// returns 'c:\my_path\htdocs\codedump\'

print add_ending_slash('/foo/bar/hd');
// returns '/foo/bar/hd/'

print add_ending_slash('/foo/has_a_slash/hd/');
// returns '/foo/has_a_slash/hd/'

print add_ending_slash('c:/files');
// returns 'c:/files/'



check for other options:
1) realpath($path) . DIRECTORY_SEPARATOR
2) function add_ending_slash($path) {
return rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
3) function add_ending_slash( $path )
{
if ( substr( $path, ( 0 - strlen( DIRECTORY_SEPARATOR ) ) ) !== DIRECTORY_SEPARATOR )
{
$path .= DIRECTORY_SEPARATOR;
}
return $path;
}
4) function add_ending_slash( $path )
{
if ( substr( $path, ( 0 - ( int ) strlen( DIRECTORY_SEPARATOR ) ) ) !== DIRECTORY_SEPARATOR )
{
$path .= DIRECTORY_SEPARATOR;
}
return $path;
}

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: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    // flush content
    flush();

    // open file stream
    $file = fopen($local_file, "r");

    while (!feof($file)) {

        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));

        // flush the content to the browser
        flush();

        // sleep one second
        sleep(1);
    }

    // close file stream
    fclose($file);

}
else {
    die('Error: The file '.$local_file.' does not exist!');
}


phpclasses.org: http://www.phpclasses.org/package/6709-PHP-Limit-the-speed-of-files-served-for-download.html (registration required for download)

and

softpedia.com: http://webscripts.softpedia.com/script/PHP-Clases/QoS-Bandwidth-Throttler-66826.html (allows anonymous download of the class)

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)
    or die('A error occured: ' . mysql_error());

// Get result count:
$Count = mssql_num_rows($result);
print "Showing $count rows:<hr/>\n\n";

// Fetch rows:
while ($Row = mssql_fetch_assoc($result)) {

    print $Row['Fieldname'] . "\n";

}

mssql_close($con);

$result = mssql_query($SQL)
or die('A error occured: ' . mysql_error());

.mysql_error is ment to be mssql_get_last_message

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"] = "blue";

// set an raw-header:
$snoopy->rawheaders["Pragma"] = "no-cache";

// set some internal variables:
$snoopy->maxredirs = 2;
$snoopy->offsiteok = false;
$snoopy->expandlinks = false;

// set username and password (optional)
//$snoopy->user = "joe";
//$snoopy->pass = "bloe";

// fetch the text of the website www.google.com:
if($snoopy->fetchtext("http://www.google.com")){
    // other methods: fetch, fetchform, fetchlinks, submittext and submitlinks

    // response code:
    print "response code: ".$snoopy->response_code."<br/>\n";

    // print the headers:

    print "<b>Headers:</b><br/>";
    while(list($key,$val) = each($snoopy->headers)){
        print $key.": ".$val."<br/>\n";
    }

    print "<br/>\n";

    // print the texts of the website:
    print "<pre>".htmlspecialchars($snoopy->results)."</pre>\n";

}
else {
    print "Snoopy: error while fetching document: ".$snoopy->error."\n";
}

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 = 'Hello world!';

if (StartsWith($ExampleText, 'Hello')){
    print 'The text starts with hello!';
}


$ExampleText = 'Evil monkey.';

if (!StartsWith($ExampleText, 'monkey')){
    print 'The text does not start with monkey!';
}

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 . $file . DIRECTORY_SEPARATOR);
        }
        else {
            $file_count++; // increase file count
        }
    }

    closedir($dir_handle);

    return $file_count;
}

count_files('./my_awesome_folder/');

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

// check if DomXML is available:
if (!function_exists('DomDocument')){
    die('DomXML extension is not available :-(');
}

print '<pre>';

// create new DOM object:
$dom = new DomDocument();

// load HTML code:
$dom->loadHtml($html);

// get tags by tagname (all <a> tags / links):
$tags = $dom->getElementsByTagName('a');

// loop trough all links:
foreach ($tags as $a){

    print '<b>' . $a->nodeValue . '</b><br/>';

    // does this tag have attributes:
    if ($a->hasAttributes()){   

        // loop trough all attributes:
        foreach ($a->attributes as $attribute){     
            print '- ' . $attribute->name . ': ' . $attribute->value;
            print "<br/>";               
        }
    }

    print "<hr/>";
}

print '</pre>';

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

    /*
    ** The user gets here if:
    **
    ** 1. The user entered incorrect login data (three times)
    **     --> User will see the error message from below
    **
    ** 2. Or the user requested the page for the first time
    **     --> Then the 401 headers apply and the "login box" will
    **         be shown
    */

    // The text inside the realm section will be visible for the
    // user in the login box
    header('WWW-Authenticate: Basic realm="Secret page"');
    header('HTTP/1.0 401 Unauthorized');

    print "Login failed!\n";

}
else {

    // The user entered the correct login data, put
    // your confidential data in here:

    print 'you reached the secret page!';
}

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>

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 $deny_ips array
    if (($i = array_search($ip, $deny_ips)) !== FALSE){

        // $i = contains the array key of the IP adress.       

        // user is blocked:
        print "Your IP adress ('$ip') was blocked!";
        exit;
    }

    // If we reach this section, the IP adress is valid

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 output will be:

Array
(
    [0] => NEW: php (KEY: 0)<br/>
    [1] => NEW: arrays (KEY: 1)<br/>
    [2] => NEW: are (KEY: 2)<br/>
    [3] => NEW: cool (KEY: 3)<br/>
)
*/

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 --> 100
printf("%01.2f\n", $number); // returns --> 100.86
printf("%01.3f\n", $number); // returns --> 100.860


// parse a string with sscanf #1
list($number) = sscanf("ID/1234567","ID/%d");
print "$number\n";
// returns --> 1234567


// parse a string with sscanf #2
$test = "string 1234 string 5678";
$result = sscanf($test, "%s %d %s %d");

print_r($result);

/*

--> returns:

Array
(
    [0] => string
    [1] => 1234
    [2] => string
    [3] => 5678
)

*/

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: ';
        $ErrorMsg .= 'The given file ' . $Filepath . ' does not exist!';
        die($ErrorMsg);
    }

    return LineStatisticsByString(file_get_contents($Filepath), $IgnoreCase, $NewLine);
}

/**
 * LineStatisticsByString
 * Creates a list with all lines of the given string and their occurrences.
 *
 * @param     string
 * @param     bool
 * @return    string
 */
function LineStatisticsByString($Lines, $IgnoreCase=false, $NewLine="\n"){

    if (is_array($Lines))
        $Lines = implode($NewLine, $Lines);

    $Lines = explode($NewLine, $Lines);

    $LineArray = array();

    // Go trough all lines of the given file
    for ($Line=0; $Line < count($Lines); $Line++){

        // Trim whitespace for the current line
        $CurrentLine = trim($Lines[$Line]);

        // Skip empty lines
        if ($CurrentLine == '')
            continue;

        // Use the line contents as array key
        $LineKey = $CurrentLine;

        if ($IgnoreCase)
            $LineKey = strtolower($LineKey);

        // Check if the array key already exists,
        // and increase the counters
        if (isset($LineArray[$LineKey]))
            $LineArray[$LineKey] += 1;   
        else               
            $LineArray[$LineKey] = 1;       
    }

    // Sort the array
    arsort($LineArray);

    // Create a new readable array for the output file
    $NewLineArray = array();   
    while(list($LineKey, $LineValue) = each($LineArray)){       
        $NewLineArray[] = $LineKey . ': ' . $LineValue;   
    }

    // Return how many lines were counted
    return implode("\n", $NewLineArray);   
}

// Count all lines of the "Testfile.txt" and create a
// statistic
$ResultString = LineStatisticsByFile('Testfile.txt');

/*
The ResultString now contains:

LineA: 3
LineB: 2
LineC: 1
*/

$stat = array_count_values(file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));

or for the case insensitive version,

$stat = array_count_values(array_map('strtolower', file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)));

print_r($stat);

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
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}

print curl_download('http://www.example.org/');

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

restore_hsc(htmlspecialchars('&lt;b&gt;test&lt;/b&gt;'));

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) {
        $block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
        $enc_text .= $block;
        $iv = substr($block . $iv, 0, 512) ^ $password;
        $i += 16;
    }
    return base64_encode($enc_text);
}

function md5_decrypt($enc_text, $password, $iv_len = 16){
    $enc_text = base64_decode($enc_text);
    $n = strlen($enc_text);
    $i = $iv_len;
    $plain_text = '';
    $iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
    while ($i < $n) {
        $block = substr($enc_text, $i, 16);
        $plain_text .= $block ^ pack('H*', md5($iv));
        $iv = substr($block . $iv, 0, 512) ^ $password;
        $i += 16;
    }
    return preg_replace('/\\x13\\x00*$/', '', $plain_text);
}

function get_rnd_iv($iv_len){
    $iv = '';
    while ($iv_len-- > 0) {
        $iv .= chr(mt_rand() & 0xff);
    }
    return $iv;
}

//
// Example
//

$plain_text = 'very secret string';
$password = 'very secret password';

print "plain text is: [${plain_text}]<br />\n";
print "password is: [${password}]<br />\n";

$enc_text = md5_encrypt($plain_text, $password);
print "encrypted text is: [${enc_text}]<br />\n";

$plain_text2 = md5_decrypt($enc_text, $password);
print "decrypted text is: [${plain_text2}]<br />\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);
        $r = rand(0, $max);

        // find a empty key:
        while (isset($a[$r])){
            $r = rand(0, $max);
        }       
        $a[$r] = $e;
    }

    ksort($a);
    $a = array_values($a);

    return $a;
}

/*
** Example:
*/

$test_array = array('why','dont','visit','www','jonas','john','de',':-)');

print implode(", ", $test_array);
print "\n";
print implode(", ", RandomizeArray($test_array));

/*
Example output:

why, dont, visit, www, jonas, john, de, :-)
www, de, jonas, john, visit, why, :-), dont
*/

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:
// Check if a file is bigger than 10 MB

if (filesize('example.zip') > StringSizeToBytes('10 MB')){
    print 'File is to big !';
}
else {
    print 'File is okay';
}

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 version (v0.1):

function TrimArray($arr){
    if (!is_array($arr)){ return $arr; }

    while (list($key, $value) = each($arr)){
        if (is_array($value)){
            $arr[$key] = TrimArray($value);
        }
        else {
            $arr[$key] = trim($value);
        }
    }
    return $arr;
}
*/

$DirtyArray = array(
    'Key1' => ' Value 1 ',
    'Key2' => '      Value 2      ',
    'Key3' => array(
        '   Child Array Item 1 ',
        '   Child Array Item 2'
    )
);

$CleanArray = TrimArray($DirtyArray);

var_dump($CleanArray);

/*
Result will be:

array(3) {
  ["Key1"]=>
  string(7) "Value 1"
  ["Key2"]=>
  string(7) "Value 2"
  ["Key3"]=>
  array(2) {
    [0]=>
    string(18) "Child Array Item 1"
    [1]=>
    string(18) "Child Array Item 2"
  }
}

*/

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 of the string

    return $n;
}
$TestString = 'www.jonasjohn.de';

print SimpleHash($TestString);

// returns: 1620

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);         
        print '<span style="color: blue;">' . $key . '</span>: ';
        print var_export($val, true);
        print "<br/>\n";
    }
}


/*example-start*/

// setup the test array
$array = array(
    'php',
    'cool',
    array('foo', 1,2,3, array('mixed' => 'bar')),
    'php' => 'array',
    'yes' => true, 'no' => false
);

// debug the array
debug_val($array);

/*example-end*/

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');
        header('Location: ' . $url);

        // Optional workaround for an IE bug (thanks Olav)
        header("Connection: close");
    }

    // HTML/JS Fallback:
    // If the header redirection did not work, try to use various methods other methods

    print '<html>';
    print '<head><title>Redirecting you...</title>';
    print '<meta http-equiv="Refresh" content="0;url='.$url.'" />';
    print '</head>';
    print '<body onload="location.replace(\''.$url.'\')">';

    // If the javascript and meta redirect did not work,
    // the user can still click this link
    print 'You should be redirected to this URL:<br />';
    print "<a href="$url">$url</a><br /><br />";

    print 'If you are not, please click on the link above.<br />';   

    print '</body>';
    print '</html>';

    // Stop the script here (optional)
    if ($exit) exit;
}
safe_redirect('http://www.example.org/');

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() <---
    $code = preg_replace(
        '/(\s)\b(.*?)((\b|\s)\()/U',
        '$1<span style="color: #0000ff">$2</span>$3',
        $code
    );

    // Match comments (like /* */):
    $code = preg_replace(
        '/(\/\/)(.+)\s/',
        '<span style="color: #660066; background-color: #FFFCB1;"><i>$0</i></span>',
        $code
    );

    $code = preg_replace(
        '/(\/\*.*?\*\/)/s',
        '<span style="color: #660066; background-color: #FFFCB1;"><i>$0</i></span>',
        $code
    );

    // hightlight braces:
    $code = preg_replace('/(\(|\[|\{|\}|\]|\)|\->)/', '<strong>$1</strong>', $code);

    // hightlight variables $foobar
    $code = preg_replace(
        '/(\$[a-zA-Z0-9_]+)/', '<span style="color: #0000B3">$1</span>', $code
    );

    /* The \b in the pattern indicates a word boundary, so only the distinct
    ** word "web" is matched, and not a word partial like "webbing" or "cobweb"
    */

    // special words and functions
    $code = preg_replace(
        '/\b(print|echo|new|function)\b/',
        '<span style="color: #7F007F">$1</span>', $code
    );

    return $code;
}


/*example-start*/

/*
** Create some example PHP code:
*/

$example_php_code = '
// some code comment:
$example = "foobar";

print $_SERVER["REMOTE_ADDR"];

$array = array(1, 2, 3, 4, 5);

function example_function($str) {
    // reverse string
    echo strrev($obj);
}

print example_function("foo");

/*
** A multiple line comment
*/

print "Something: " . $example;';


// output the formatted code:
print '<pre>';
print syntax_highlight($example_php_code);
print '</pre>';

/*example-end*/