Very fast array_unique

This URL provides a relatively faster array_unique alternative. I have worked a little on this and found the sugested function to be very helpful.

The author worked with the array that had keys integers and values strings. I checked the same scenerio and it was about 40% faster. Then i used integers in values of array and surprised to see performance of the suggested function. Its about 9x faster. If you dont believe me test it yourself.


Try these two tests:


for( $a=1; $a<=50; $a++ )
{
    $ar[]    = mt_rand( 0 , 5 );
}

function fast_unique($input) {
    return array_flip(array_flip(array_reverse($input,true)));
}

$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = fast_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";


$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = array_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";




And the second test:


for( $a=1; $a<=50; $a++ )
{
    $ar[]    = (string) mt_rand( 0 , 5 );
}




function fast_unique($input) {
    return array_flip(array_flip(array_reverse($input,true)));
}

$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = fast_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";


$start = explode(' ', microtime());$start = $start[0] + $start[1];

for( $a=1; $a<=500; $a++ )
{
    $ar2    = array_unique( $ar );
}

$end = explode(' ', microtime());
echo 'Time: '.($end[0] + $end[1] - $start)."\n";



In the first test, the performance is 9x, in the second, it is just 40% faster. A really considerable difference if your application needs a lot of arrays sorting like work.

Freelancing and Copyright — An Uncomfortable Arrangement

When Congress last amended copyright law in 1976, they added a clause that causes problems for freelance artists, writers, and designers. Basically, the law gave copyright ownership to the ”author” of a creative work as long as it was not a ”work made for hire,” in which case the copyright belonged to the organization for whom the project was executed.

Corporations such as publishers of newspapers and magazines went to court to protect their rights to withhold royalties from freelancers under an argument that the work was done “for hire” and not that the author loaned the work for publication; and these battles are still being waged.

In 1989, one of these court battles made it all the way to the Supreme Court who ruled in favor of freelance artists on commission. This is a huge win since it stated that freelance artists in most instances can keep the benefits of copyright, which include licensing and reproduction rights and protection against unauthorized copying. The decision also poses practical problems for businesses that rely heavily on freelance work.

                           What is a Copyright?

When you post the following statement:
Copyright © year Your Company Name. All rights reserved.
… you are stating that you own all the rights and privileges to your work, period. You are protecting yourself from anyone who tries to “make and sell copies of the work, publicly show the work, import or export the work and assign these rights to others.” Notice that you are protecting your work, but not the ideas behind the work.
The following types of work are protected by copyright.
  1. Original literary works (novels, instruction manuals, computer programs, lyrics for songs, articles in newspapers, some types of databases, but not names or titles)
  2. Original dramatic works, including works of dance or mime
  3. Original musical works
  4. Original artistic works, e.g. paintings, engravings, photographs, sculptures, collages, works of architecture, technical drawings, diagrams, maps, logos
  5. Published editions of works, i.e. the typographical arrangement of a publication
  6. Sound recordings, which may be recordings on any medium, e.g. tape or compact disc, and may be recordings of other copyright works, e.g. musical or literary
  7. Films, including videos
  8. Broadcasts.
The moment you commit a creative endeavor to paper or web, CD or computer file, it is copyrighted. The mark shown above is a warning to your viewers that the work is protected.
Copyright law provides a limited use clause called “fair use.” This is a loophole through which free libraries, educators, universities, commentators, bloggers, critics, and journalists may quote with proper attribution, from a copyrighted work. The definition of what exactly constitutes fair use is a murky topic that is still being debated in courts.

source : Freelancer

Creating Variables from Array Keys in PHP (with more control)

This function is a little more enhanced version of my previous post on the same topic. In this function, what extra you can de is define the default value in the variables array in case of non existance of variable in the parent array. Previously the default value was NULL.

function better_array_to_variables( $array = array() , $variable_list = array() )
{
 if( empty( $array ) OR empty( $variable_list ) )
 {
  return false;
 }
 
 if( !is_array( $variable_list ) OR !is_array( $array ) )
 {
  return false;
 }
 
 if( !count( $variable_list ) OR !count( $array ) )
 {
  return false;
 }
 
 foreach( $variable_list as $key => $value )
 {
  if( !ctype_digit( ( string ) $key ) )
  {
   $name  = $key;
   $default = $value;
  }
  else
  {
   $name  = $value;
   $default = NULL;
  }
  
  if( preg_match( "/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/" , $name ) )
  {
   GLOBAL $$name;
   if( isset( $array[$name] ) )
   {
    $$name = $array[$name];
   }
   else
   {
    $$name = $default;
   }
  }
 }
}

better_array_to_variables( array( 'hamdusa' => '1' , 'Adlusa' => '2'  ) , array( 'hamdusa' , 'adlusa' => false , 'mudassar' => 'inexists' ) );

var_dump( $hamdusa );
var_dump( $adlusa );
var_dump( $mudassar );

Creating Variables from Array Keys in PHP

If you want to convert associative arrays in variables automatically, you can use the following script. It requires an array from which to extract the variables, and an array of variable names that you want to extract.

Here is the script:

<?php
function array_to_variables( $array = null , $variable_list = array() )
{
 if( $array === null )
 {
  $array = $_GET;
 }
 
 if( !is_array( $variable_list ) )
 {
  $variable_list = explode( ',' , $variable_list );
 }
 
 if( !count( $variable_list ) )
 {
  $variable_list = array_keys( $array );
 }
 
 foreach( $variable_list as $variable_name )
 {
  $variable_name = trim( $variable_name );
  if( preg_match( "/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/" , $variable_name ) )
  {
   GLOBAL $$variable_name;
   if( isset( $array[$variable_name] ) )
   {
    $$variable_name = $array[$variable_name];
   }
   else
   {
    $$variable_name = null;
   }
  }
 }
}?>

And here is how to use it;

<?php
//Example 1
array_to_variables( $_GET , array( 'image_id' , 'session_id' ) );
//Example 2
array_to_variables(  );
?>

In the example 1, it will try to create variables $image_id and $session_id and look for the value in the $_GET array. If the array keys in $_GET array exist with the name 'image_id' and 'session_id', same variables are created successfully. In case of failure it creates variables and saves NULL in those variables.

I second Example, the default array $_GET is taken and it tried to create a variable for every valid associative key. Valid here means an associative key that can be used as variable name.

Hope this is helpful function for you all. Sorry for poor documentation.

PHP Constants can make your application insecure

PHP constants work in a strange way to make the language more programmer friendly. When you use a constant inside your script, and by any chance that constant is not defined before its use, php issues a Notice. Example:

<?php
echo MY_CONST;
//MY_CONST is not already defined;
?>

The output is

<br />
<b>Notice</b>: Use of undefined constant MY_CONST - assumed 'MY_CONST' in <b>/path/to/file.ext
</b> on line <b>13</b><br />MY_CONST

Notice the emboldened My_CONST that is not part of the Notice. What php did is first tried to get the value of constant MY_CONST but when it found that no constant of this name was ever defined, it issued a Notice and then used MY_CONST as a string 'MY_CONST'. At next step the same string is outputted to the browser.

When you are running your site on production server with error reporting disabled, php will simply echo the name of constant (as it did in above example) and no error Notice will be displayed to you at all. Here lies vulnerability.

It is common in many applications that when the script successfully determines the status of the user (loggedin/not-loggedin), the status is saved in a constant. See the following example:

<?php

function authentication()
{
     //Some Authentication Stuff
     //IF Successful
     define('USER_LOGGED_IN' , true );
}

function is_login()
{
     return USER_LOGGED_IN;
}

if( is_login() )
{
     include('/private_stuff');
}

authentication();

if( is_login() )
{
     //allow private access
}

if( is_login() )
{
     //SHOW Tools
}

if( is_login() )
{
     //Show username
}

?>


There are two problems in this script. First:
If the authentication is successful and USER_LOGGED_IN is set to true, everything will go fine. Call to function is_login() will happily return true and if( is_login() ) results in success. But when the authentication is failed the authentication() function has not enough explanation of what to do in case of failure. USER_LOGGED_IN constant is not defined in case of failure, and whenever is_login() is called it will behave strangely (as explaned at the top of this post) and will return a string 'USER_LOGGED_IN'. Strings other than empty ("") or "0" are true in php, so the if( is_login() ) results in if( 'USER_LOGGED_IN' ) which still results in a success. So whether or not a user is logged in, it will get access to private contents.

Second: The if condition used before the call to authentication() function, still results in success even the authentication is not yet done (this is because of the same problem as in the first case).

A simple solution to these problems may be:

<?php

authentication();

function authentication()
{
     //Some Authentication Stuff
     //IF Successful
     define('USER_LOGGED_IN' , true );
     
     //IF Not Successful
     define('USER_LOGGED_IN' , false );
}

function is_login()
{
     if( !defined( 'USER_LOGGED_IN' ) )
          authentication();
     //The above call will probabily never happen unless you forgot it elsewhere
     return USER_LOGGED_IN;
}

if( is_login() )
{
     include('/private_stuff');
}

if( is_login() )
{
     //allow private access
}

if( is_login() )
{
     //SHOW Tools
}

if( is_login() )
{
     //Show username
}

?>

No doubt there were bugs in this script, but this problem may also occur in many other cases like misspelling constants, or not defining constant at all when you think it already has been defined in some other included file. When you misspell a constant and you have error reporting disables, you hardly get any clue where the problem lies unless you use a good php editor (like in Notepad++ highlighting a word highlights all instances of the same word. This makes finding spelling mistakes easy).

Also in this case, you have to take extra care to ensure that whenever the function is_login() is called, the authentication process is already completed, or in other words you have to authenticate at the top of your script.

May be no one developing a secure application is this much stupid to make an application where an insecurity exists at such basic level. But errors and oversights do occur. Also the the scenario may be different. You might think that a constant is defined in some other file but may be that file is not included at all or the constant is not be defined as expected or not defined at all.

When you check you application under the development environment, the possibilities are limited. No matter how thoroughly you test your application, it is always possible that something unexpected occur. The parameters that you work with may work fine for you under testing environment, but when your application is open for public, it may start behaving unexpectedly.

I recommend using Variables and Arrays unless you really want/need to use constants, for example: keeping settings in constants that you never want any one else to change through out the running of the script.