Category Archives: PHP

How to get the top most parent ( parent’s parent ) Recursively in php , when to use Recursive Function

My table Structure:

id parent_id menu name
1 0 Home
2 0 Gallery
3 0 Message
4 3 From Principal
5 3 From Guardian
6 2 Events
7 2 Students
8 6 Picnic
9 6 Sports

Major Requirement:

Input : 9 (Sports->Events->Gallery Bottom Up Parent Wise)

output: 2 (Gallery->Events->Sports Top Down )

Our Requirement is to make the function that will return us the top most parent of any menu item. Lets say i need to find the parent of Sports (id=9) menu which is simple i.e. the menu name with id 6 i.e. Events

Simply we will write the simple query: select menu_name from table_name where id=6

But it is not as simple as we have thought to find the top most parent of any menu . Because sometime we don’t know the depth i.e level at which the top most parent  is.

Here we actually don’t know the depth or level of top most parent . If you don’t know the level then use the recursive function it will save your cost of programming . Recursive function will solve your problem with magic:

Here is the Code :

 function get_most_root_of_any_id($id=NULL){

        if($id==NULL){
            return false;
        }

        $this->CI->db->select("parent_id");
        $this->CI->db->where("id",$id);
        $result = $this->CI->db->get("table_name");

        if($result->num_rows()==0){
            return false;
        }

      $record =  $result->first_row();

      if($record->parent_id==0){
            return $id;
      }else{
        return $this->get_most_root_of_any_id($record->parent_id);
      } 

    }

This Example is made on the basis of Codeigniter , So please modify as per your need . More on RECURSION Enjoy…

When and How to use Recursion Function in PHP

Recursion function in php with example:
After reading many blogs and forums about recursion function , and along with the expert advise in recursion function . Not everyone but most expert say not to use the recursion function until necessary . What I mean to say is do not use the recursion function , if the same problem can be solved without using the recursion function . But at the same time performance matters  a lot . When you are iterating through the unknown structures better use the recursion but be confident in using the recursion. I am not 100% sure whether it is the exact answer or not. But the reason behind not using the recursion function as far as you can is:

First the recursion function by itself is difficult to use.

Second debugging becomes quite logical or difficult.

The true fact I faced is , I used the recursion function but later on , it was difficult for me to debug it. Any way does not matter whether you use recursion function in your code or not but the thing is you have to know about the recursion function as well.

What is recursion function?

A recursive function is just a function that calls itself.

Things to take care of Using Recursive Function

  1. Every recursive function must have the terminating condition

2. The function must call the function itself and Each recursive call must be different than the one before

Lets go with the Common practical example of the recursive function for calculating the factorial:

We have using this example since we started programming.. .. Flash back …

Factorial Calculation without using Recursion:

<?php

//iterative factorial function

function factorial($number) {

$result = 1;

while ($number > 0) {

print "result = $result, number = $number\n";

$result *= $number;

$number--;

}

return $result;

}

?>

Lets do the same example using the recursion function :

<?php

//recursive factorial function

function factorial($number) {

if ($number < 2) {

return 1;

} else {

return ($number * factorial($number-1));

}

}

print factorial(6);

?>

You did not find that much intresting … ok lets go with the real practical example:

First I will make the table category with three fields id, parent_id and category_name.

First column is the primary key and parent_id holds the parent key and last  is the name  of the category.

Id Parent_id Category_name
1 0 Jacket
2 0 Mufler
3 1 Wind proof
4 3 Bossini
5 2 Silk
6 1 Water proof
7 5 Kashmiri silk

Fig: table category

From the above table it is clear that there is hierarchy in the category name i.e.

  1. Jacket(id=1)
    1. Wind Proof(id=3)
      1. Bossini(id=4)
  2. Water Proof(id=6)

And similar hierarchy in other category . Why am I explaining all these long story is .. ..

My requirement:  Make the function that will accept the id or the category name as the parameter and return all its child or siblings.

i.e. when id 1 is passed as an parameter , it must return the 3 , 4 and 6 as the ouput. The output can be an array or just in the string format but must be 3, 4 and 6 according to the above table.

i.e when 3 is passed as an parameter the output must be 4

The solution seems to be simple …. Quick solution that has arise to your mind is ..

Select id from category where parent_id=1  ???????? is it the right solution

I don’t think so .. it will give only the first child . But solution is simple you can just make another similar function that returns the child and next and next function till the level of hierarchy if the level of hierarchy is not defined , then you will face the simple problem but its possible . Here where I want to focus is RECURSIVE FUNCTION.

Ok here is the recursion function that will help you to solve the above problem:

function get_all_sub_caseTypeId($parent_id){

$this->CI->db->select("CASE_TYPE_ID,CASE_NAME");

$this->CI->db->where('CASE_TYPE_PID',$parent_id);

$query = $this->CI->db->get('CASE_TYPE');

foreach($query->result() as $rows){

$child_ids[$rows->CASE_TYPE_ID] = ($rows->CASE_TYPE_ID);

if($this->has_child($rows->CASE_TYPE_ID)){

$child_ids[$rows->CASE_TYPE_ID] = $this->get_all_sub_caseTypeId($rows->CASE_TYPE_ID);

}

}

return $child_ids;

}

function has_child($parent_id){

$this->CI->db->select("parent_id");

$this->CI->db->where('id',$parent_id);

$query = $this->CI->db->get('category);

if($query->num_rows()==0){

return false;

}

return true;

}

This example is made on the basis of CODEIGNITER

Conclusion  for appropriate Use of Recursive Function:

Everything that can be done iteratively can be done through recursively and vice versa. However, just because it is possible does not mean it is always appropriate or even easy to implement.

Recursion has a valuable niche in computer science. It provides a more natural path through unknown structures, a more intuitive way of writing many algorithms, and a more elegant approach to writing some kinds of code. Hopefully this article has helped to establish recursion as an important and useful tool in your retinue of PHP tactics. Happy coding!

Magic Constant in PHP

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are eight magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive and are as follows:

A few “magical” PHP constants
Name Description
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

Managing Sessions and State with PHP

In PHP, sessions can keep track of authenticated in users. They are an essential building block in today’s websites with big communities and a lot of user activity. Without sessions, everyone would be an anonymous visitor.

Due to the fast evolution of Web programming, the stateless nature of the HTTP protocol brought many problems to certain Web applications that required maintaining their state across several HTTP requests. This demanded a rapid development of several mechanisms aimed at tackling this issue through diverse methods. Then a session management emerged as a direct response to the above mentioned problem, and currently this mechanism is being used by PHP developers worldwide, in cases where a Web application needs to keep track of its “state” during the occurrence of different HTTP requests.

PHP sessions are very simple to use. They hide all the complexities inherent to where and how to store session data, and provide developers with a transparent mechanism for managing information that must persist or keep state even if different HTTP requests are triggered across the same Web application.

Thus, we get to know that session management is used to help web applications maintain their state across several HTTP requests when needed. In this first part of a series, you will learn the basics of the PHP built-in session mechanism, as well as some of its many useful functions.

Let us see how to maintain the state of applications with PHP session:

The first step involved in the use of PHP sessions is naturally indicating to the PHP interpreter that some kind of persistent data must be stored in the course of a session, in such a way that this data will maintain its value across different HTTP requests.

A cryptographic session identifier is created (known as the session ID), which is saved in the client in a cookie (this is the default behavior), or propagated by the URL as part of the query string (also known as URL propagation). Session data is stored on the server in text files (the default directory for storing session data is /tmp), but this behavior can be easily changed to save session data in shared memory or even database tables. The corresponding session ID is associated with saved session data, in this way providing a method for tying a particular user to this data.

Now let us know how session IDs are propagated across different HTTP requests. First off, the PHP session module uses cookies as the default way to propagate session IDs between different pages. Additionally, IDs can be propagated by GET/POST requests, by appending to each URL the name of the session together with the corresponding session ID. The following example shows how to pass a session ID between pages:

<?php

session_start();

?>

<a href="sesionscript.php?<?php echo 'PHPSESSID='.session_id()?

>">Click here</a>

In addition, PHP offers the global constant SID, which can be used to propagate session IDs within the URL, as follows:

<?php

session_start();

?>
<a href="sesionscript.php?<?php echo SID?>">Click here</a>

Finally, it’s possible to propagate session IDs by using the powerful “URL rewrite” feature, which automatically parses relative URLs and includes the session ID as part of the query string. To enable this handy feature, PHP must be configured with the “—enable-trans-id—option and then recompiled. Here’s a simple script that creates (or resumes) a session, and registers some data in the superglobal $_SESSION array:
session_start();

// register session variables

$_SESSION['firstname']='Alejandro';

$_SESSION['lastname']='Gervasio';

// display session variables

echo 'My first name is '.$_SESSION['firstname'].' and my last

name is '.$_SESSION['lastname'];

As you can see, the above script is very simple. It first creates a new session or resumes an existing one by the “session_start()” function, and then stores my first and last names respectively as session data. If there is not a previous session, PHP will first generate a pseudo random session ID, then create a session file on the server using that ID, and save the serialized data in this file. In addition, the corresponding session ID will be stored in the client by using a cookie.

 

This sequence is the default behavior of the session module. However, as you’ll see later on, this process can be entirely changed, in order to utilize either shared memory or database tables for storing session data. Let us continue exploring the PHP session module, by using some other interesting functions. Have a look at the following example, which uses the “session_id()” function:

session_start();

echo 'Old session ID :'.session_id();

// generate a new session ID

session_id(md5(rand(1,5000)));

echo 'New session ID: '.session_id();

In this case, after running the above script, these are the values outputted to the browser:

Old session ID :e0c9904e70f283343f5aba1bad09aa69

New session ID: b0169350cd35566c47ba83c6ec1d6f82

As shown above, the “session_id()” function comes in very handy either for retrieving the ID of the current session, or for generating a new session identifier. To increase the overall security of a session, generating a new ID sometimes can be quite useful, in order to avoid possible session ID interceptions from malicious users. In case you need to regenerate the ID of a current session, PHP also provides the “session_regenerate_id()” function, which can be used as follows:

session_start();

$oldid=session_id();

session_regenerate_id();

$newid=session_id();

echo 'Old session ID is '.$oldid;

And the corresponding output for this script would be similar to this:

Old session ID is 8245009bcf9e24a738804323e779a3b7

New session ID is 680ee3c504bdecaf270539b254dd97df

In this example, as its name suggests, the “session_regenerate_id()” function is used to generate a new ID for the current session, but the good thing is that session data is always maintained. This function is extremely useful for avoiding some issues related to session ID fixation, and should be utilized in order to increase the security of session handling scripts.

In many situations, the logic of a particular PHP application requires that a specific session be terminated. In order to end an active session, PHP includes the “session_destroy()” function, which as the name indicates, destroys all the data associated with the current session. This function doesn’t unset any of the global variables tied to the session or the respective cookie. The use of this function is exemplified below:

session_start();

session_destroy();

Calling the “session_destroy()” function doesn’t delete the corresponding session variables or associated cookies. Thus a typical script, excerpted from the PHP manual, which destroys the current session along with all the session variables and the cookie associated to it, is listed below:

// destroy a session and all variables and cookies associated with it.

session_start();

$_SESSION = array();

if(isset($_COOKIE[session_name()])){

setcookie(session_name(),'', time()-48000,'/');

}

session_destroy();

In the above example, all the session variables are unset by the line:

 

$_SESSION = array();

while the corresponding cookie is deleted by the following code:

 

if(isset($_COOKIE[session_name()])){

setcookie(session_name(),'', time()-48000,'/');

}

Additionally, all the registered session variables can be freed up with the “session_unset()” function. However, for a complete and secure deletion of the entire session, it’s recommended to use the “session_destroy()” function in conjunction with the superglobal $_SESSION array and the “setCookie()” function, as shown in the example above.

If the session ID is transmitted by cookies, they will be deleted as soon as the browser is closed. Bearing in mind this condition, you should configure (when possible) the “gc_maxlifetime” and “gc_probability” directives of the php.ini file, in order to instruct PHP to trigger its garbage collection mechanism, in accordance with the requirements of the application being developed.

Let us see the example, which displays the name of an active session:

session_start();

echo session_name(); // displays PHPSESSID

// generate new session name

session_name('NEW_SESSION_NAME'); //displays NEW_SESSION_NAME

echo session_name();

As shown in the above script, the name of a session can be obtained by using the “session_name()” function. This function returns the name of the active session or assigns a new name to it.

After running the previous snippet, the output I get on my browser is the following:

PHPSESSID

NEW_SESSION_NAME

If a new session is started with the same browser or even with a different one, the value returned by the “session_name()” function (without passing any argument to it) will always be “PHPSESSID,” because this is the default session name assigned in the php.ini configuration file.

PHP also exposes a bunch of handy functions, aimed at returning and modifying some configuration parameters assigned as default values in the corresponding php.ini file. The examples begins with the “session_cache_limiter()” function, which returns the current setting of the “session.cache_limiter” directive, included in the php.ini file:

echo session_cache_limiter(); // default value is 'nocache'

// set new cache limiter to 'public'

session_cache_limiter('public');

echo session_cache_limiter();

// set new cache limiter to 'private'

session_cache_limiter('private');

echo session_cache_limiter();

As shown above, the “session_cache_limiter()” function allows you to return or change the settings of the “session.cache_limiter” directive. This parameter controls how server responses will be cached by the browser, and its default value is “nocache.” This means that any client/proxy caching process will be disabled by default in PHP.

On the other hand, if a value of “public” is assigned to this parameter, it will allow proxies and the client to cache content respectively. A value of “private” will disable caching by proxies, but enable caching by the client. As you may have guessed, all the cache directives are handled directly by the appropriate HTTP headers.

Also have a look at another handy PHP session function, in this case “session_cache_expire(),” which returns and eventually modifies the settings of the “session.cache_expire” directive:

session_start();

echo session_cache_expire();// default value is 180 seconds.

// set new cache expire value

session_cache_expire(20); // set cache value to 20 seconds.

echo session_cache_expire();

The above example shows how to use the pertinent “session_cache_expire()” function. Of course this function should be utilized when cache is enabled, and its default value is 180 seconds. If a new setting is assigned to this directive (the example sets a new value of 20 seconds for caching contents), the current value will be replaced with the new one. If you’re going to modify the “session.cache_expire” setting, keep in mind that the default value of 180 seconds is assigned to it with every new HTTP request, so you should change this directive each time a request is triggered and before calling the “session_start()” function.

Another helpful function that will allow you to modify the value assigned to PHP session storage modules is the “session_module_name()” function. In case you didn’t know about this feature, PHP can be configured to use different storage modules. As you saw before, the default storage module is “files,” but it’s possible to modify this setting, in order to use shared memory, by assigning a value of “mm,” or utilizing user-level callback functions, which are used in conjunction with the “session_set_save_handler()” function. For this last option, the assigned value should be “User.”

Now, here’s an example of how to use this function:

echo session_module_name().'<br />'; // default value is 'files'

// set new module name

session_module_name('user');

echo session_module_name(); // displays ‘user’

After demonstrating a simple implementation of the “session_module_name()” function, we are going to explain the combination of “session_set_cookie_params()/ session_get_cookie_params()” functions. Here are a couple of examples that show how to use them:

 

$cookieparams=session_get_cookie_params();

print_r($cookieparams);

In the above script, the “session_get_cookie_params()” function is used to return the settings of the following php.ini directives: “session.cookie_lifetime,” “session.cookie_path,” “session.cookie_domain” and “session.cookie_secure.” And the output I get on my browser is listed below:

Array ( [lifetime] => 0 [path] => / [domain] => [secure] => )

As you can see, the above function returns nicely the values assigned to the php.ini entries that I mentioned before. Its counterpart, the “session_set_cookie_params()” function, should be used in the following way:

session_set_cookie_params(3600,'/cookiepath/','mydomain.com');

session_start();

$cookieparams=session_get_cookie_params();

print_r($cookieparams);

And the output would look similar to this:

Array ( [lifetime] => 3600 [path] => /cookiepath/ [domain] =>

mydomain.com [secure] => )

In this case, this function sets new values for the corresponding php.ini settings, which will only be valid during the execution of the script in question. Thus, if you need to keep the new assigned values across different HTTP requests, the function should be called each time a new request is made.

Conclusion

In this article, we have covered the basics of the PHP built-in session mechanism, as well as some of its many useful functions. For more information, keep on logging www.phpfresher.com.

Protecting your PHP Source Code with Ioncube Encoder

The ionCube Standalone PHP Encoder is the leading script protection solution for PHP 4, PHP 5 and PHP 5.3 based software.

IonCube protection uses 100% compiled PHP, and utilizing a closed source execution engine, ionCube Encoding tools deliver the best performance and PHP source code protection of any encryptor solution currently available. With features to meet the demands of both small and enterprise scale applications, the ionCube Encoder’s unrivaled PHP protection, performance, and all round flexibility and feature set, is the ideal and only serious no-compromise solution for protecting PHP.

As PHP is encoded into a special byte-code, a loader must be installed on your web server. A loader is a PHP module that must be installed. Before we proceed, let’s take a quick look at an encoded file. Listing 1 shows a basic PHP script.

                               helloworld.php

<?php

echo "Hello, world!\n";

?>

We can then run this script through the encoder. While there are many different options available, encoding a script with the default options yields the following PHP file.

helloworld-enc.php

<?php //000a8

echo('Site error: the file <b>'.__FILE__.'</b> requires the ionCube PHP Loader '.

basename($__ln).' to be installed by the site administrator.');exit(199);

?>

4+oV5BgRgd22U2z7JoK/KmKPIcszhD8pg3hvN+5vc4HFcsGMn/El/4CMYaLFFzaqguLCeb9su8xn

i0+eWxJg/kwNHRkiBvY1aMf1AvwPf14DIwCvegtJC7cbx9cN5jBjwSspVjhVsQnxFx9oBut6R0Kc

V+OLw6XBTNm5sKpbL6DVm2jqk8Wasm9oJgKLZxBtvVBeP5vZrOiod+L7SoplcmTgtyr5wzS3sEzj

r7ixXPUY4H82MyuzZyjYTkSKkz9qlMzWHddrUHJX3y0zPfDqWDUeD1BibJQJ9BXkP7jb4pdKQv/hsMqhthNQQRSp6nOJHq8oDDYLE+p403GYs2As9qEI2wNAg6j6ln0BRP7shcbNTb5a8O4VjjLhGDwG

1AYOxaM4R5QneCFr+xYdtEYSep8FW1i9IBzF1FuDa7eMoPDqaQdjTLAPsy5O831yGpAHohx3FzUK

aewZTV+tdru=

 

While you cannot understand what this code does just by looking at it, your PHP installation with the correct loader installed interprets this just as if it was the code in Listing 1.

Encoding your PHP files

The ionCube PHP Encoder is a command-line script you run either one or more files, or on an entire set of folders. If you’re encoding an entire PHP application you would typically run it on the original source folder. The encoder will duplicate the entire tree, except the PHP code will be encoded.

Now let us use the command to generate this encoded script  as shown in Listing 3.

listing-3.txt

/usr/local/ioncube/ioncube_encoder5 helloworld.php -o helloworld-enc.php

In this example, the -o specified the output location. In this example we just created the encoded file in the same directory with a different filename. Typically you would want to create the file with the same filename as the original (without replacing the original source code).To achieve this, set the input and output both to be a directory. The encoder will automatically recurse through all directories in the input directory and encode all PHP files. To demonstrate this, let’s assume helloworld.php is in a directory called src. Listing 4 shows the command we use to encode this entire path. The example outputs the encoded files to the build directory.

listing-4.txt

/usr/local/ioncube/ioncube_encoder5 src -o build

We now have a directory called build which is identical to src except that the PHP files are encoded. There are many other command-line options. You can discover some of these by running ioncube_encoder5 with no arguments. Additionally, the “Encoder User Guide API” document is extremely useful.

 

 

Protecting Non-PHP Code

Depending on how your web application has been designed, there may be some non-PHP files you would to prevent users from being able to read. A good example of such files is XML files or Smarty template files. The ionCube PHP Encoder includes an encryption option. This feature is used to protect non-PHP files (but it differs from the PHP encoding since the output isn’t a bytecode format format).

To encrypt files, the –encrypt command-line option is used. You can then specify a file pattern that will be encrypted. For example, if you want to encrypt every file with extension tpl you would specify –encrypt “*.tpl”. Without doing so, the encoder would simply copy all tpl files exactly as-is into the target directory.

Listing 5 shows the command we can now type on our src directory. The directory contains the helloworld.php script and a template called index.tpl.

listing-5.txt

/usr/local/ioncube/ioncube_encoder5 src/ -o build –encrypt “*.tpl”

Listing 6 shows the original template file:

{foreach from=$myArr item=row}

{$row}

{/foreach}

Now when we run the command from Listing 5, not only is the PHP script encoded, the index.tpl file is encrypted. Listing 7 shows what the encrypted file may look like.

index.tpl

!odMbo!

oGkVHCn70iD3x0iNno6StW4000000000pkStDhZrw5wtaVwr8YByvTkxU/tMRAa8JBW2sOPu5OTW

Yk1KK+DyvUiMDXg2Wasd9IU12Kno0p0HeaPHg8258DO=1

Your application must be able to handle these encrypted files. Fortunately, when a loader is present in a PHP installation, a number of additional functions are made available that allow you to deal with encrypted files.

The ioncube_read_file() will decrypt files that have been previously encrypted. This function accepts a file system path as its only argument and will return the decrypted data. If the input path was not encrypted it will be returned as-is.

Note: The ioncube_read_file() method will only work from within an encoded PHP file. Additionally, it can only decrypt files that were encrypted with the same encoder that encoded the PHP file. This prevents other people from being able to decrypt your files.

Since we encrypted a Smarty template in the previous example, let’s take a quick look at the changes required to Smarty to read encrypted files. The ionCube website contains notes on patching Smarty so it is compatible. This change ensures ioncube_read_file() is available, meaning you can used the patched version in applications whether or not they’re encoded. The API also includes a ioncube_write_file() function which allows you to directly write encrypted data from within your application. This allows you to protect data generated by your application.