PHP Coding Tips

Thursday, March 28, 2013

PHP password hash with salt

It is more secure to stora a password hashed with added static (or even dynamic salt). To achieve static salt in password just append a string when calculating a hash. Example below shows dynamic salt, most secure:function getHash( $pass , $login ) { $salt = substr( md5( $login ) , 0 , 10 ); return hash( 'sha256' , $pass . 'ThEStAtIcSaLe' . $salt ); }Remeber to use same function when checking user credentials.It will be also more secure to use slower hashing/crypting function

Inheritance in PHP

Inheritance (extending classes) is realised in PHP with extends keyword:class albumController extends MfStandardController {Now, object of class albumController will be of type albumController, but also of type MfStandardController, because MfStandardController is a parent of this class

Sample smarty loop with images

If you want to print several images on your site, you must assign array of those images to smarty variable. Then, you can iterate over this array in smarty and show img tags for each image. Rember about good path:{foreach from=$sm_photos item=item} <img src="/content/photophoto/1/{$item.file}"> {/foreach}If your path will not target image file, you can get 404 error, but typically image will be just hidden

Thursday, March 21, 2013

PHP: Get last element of array

Often you need to get the last element of PHP array. This is easy to achieve with using count() function, wich counts all elements in array. Because PHP arrays are indexed from 0, you must remeber to get "count()-1" element of an array, not "count()" element:$exampleArray = array( 3,6,8,11,14 ); $lastElement = $array[ count($exampleArray) - 1]; echo $lastElement; // prints 14This is the obvious way for some begginer developers. But more experienced developers will know, that there is a function defined especially for this purpose: echo end( $exampleArray ); // prints 14 Because this function will move internal array pointer to the end, you can reset it if you are currently iterating over this orray, for example: reset( $exampleArray ); // prints 14 If you are afraid about non set array, or set as other type than array, you can use function is_array() to check if this variable is defined as array. You can also get a last key of an array in several ways: echo end(array_keys( $exampleArray) ); // or: end( $exampleArray ); echo key( $exampleArray ); If you don't want to move internal array pointer, you can use another one-liner to get last element from array: $last = array_slice($array, -1, 1, true);

How to quote in echo or print in PHP?

If you are creating applications in PHP, even if you are beginner, you definatelly see echo function already. Echo function just outputs it's argument to a user browser or to a console/terminal if PHP script is running in the CLI mode. The trouble rises, when you have to put ' or " sign in a echo, because you have to use one of this characters just to begin and terminate echo literal. To embed such characters in displayer string, you need to use escape sequence. It is a special characters combination, that makes some special sense in string literal. So, if you want to send quote sign to user, not to terminate echo string, use \" escape sequence. If your sequence is terminated by single quotes ('), then you can also include this character in string by escape sequence \'. See examples below:echo "This example shows \"escape sequences\" in php string, like quotes etc"; echo 'This example shows \'escape sequences\' in php string, like quotes etc';You can be confused if you think, what to do to put a slash in php string (\), because it has some special meaning. But I have solution for you: this character also have some custom escape sequence, and this sequence is: "\\".

Wednesday, March 20, 2013

How to do SMARTY foreach loop to present array values from PHP?

SMARTY is a very good template engine that helps you decompose application view and model. If you want to create a SMARTY foreach loop, you need to have assigned array first. If you want only to present array values, then it can be a usual PHP array without special keys. But SMARTY foreach, same as foreach in PHP, can present keys for array items. The basic construction of foreach loop in smarty, together with PHP array assigment to present in view, you can see below: // In PHP: $array = new array( 'key1' => 'val1' , 'key2' => 'val2' ); $smarty->assign('someAssignedArray' , $array ); // In SMARTY: {foreach from=$someAssignedArray key=keyOfItem item=itemValue} The key of this item is: {$keyOfItem}<br> The value of this item is: {$itemValue}<br> {/foreach}As you can see, we have to have defined array first. Example above shows custom keyed array, but this array can also have standarized default keys like 0,1,2,3,4 etc. The first step is to assign our array to SMARTY variables, because SMARTY doesn't have access to global PHP scope in nice way. So we must define a custom name for this variable -in example above i named it 'someAssignedArray'. So, the array wich in PHP exeist as $array, will exist in smarty as $someAssignedArray.
Now, you can write a foreach loop in your tpl file. The basic atribute of SMARTY foreach tag is from. This attribute says, from wich array you want to pick up all items for iteration. Remeber that this variable must have a dollar sign at begining.
Second required parameter in this loop construction is item. Item refers to name of variable, wich will have a value from array inside the loop. Key attribute works in the same way - it will contains key for item value in single loop iteration. There is some important thing - remeber that you create a new SMARTY varaibles here, so do not use dollar sign.
Inside the foreach loop, you can access your array item value and key by varaible names you specified as foreach tag attributes, this time begininnig with a dollar sign.
Of course, if yours item value is an array, nothings stop you to provide a nested foreach loop, with new key and value variables. This is useful thing.
If you want to print your array in fastest way, only for debug etc. you can try to use print_r function in your SMARTY tpl file. I wrote some nice tutorial about using print_r in SMARTY, so check itd.
If you want to provide additional filtering when iterating over items, see my tutorial about modifiers here.

Tuesday, March 19, 2013

Call superclass method in object oriented PHP application

You can call parent methods using :: operator, as in example below:parent::init( 'aaa' );This situation works also, when dealing with static methods.

Call parent constructor in PHP

You can call constructor of the superclass of your class. Why to do that? It's important if you write your own constructor. If you derive from a class and write custom constructor then, when object is creating o only yours constructor will be called. This can casue a situation, when object isn't propably initialised. For example, some fields can be not set, null valued etc. To prevent those situations it is a good practice to call parent construtor in your class constructor as the first line like example below: public function __construct() { parent::__construct( 11 ); } In this situation you prevents errors like uninitialised class variables, uncalled other initialisation methods etc. As you can see, there is also a posibility to pass some variables to parent conscturctor. This is common case - if you derive from a class, wich have some variables in constructor, then you have to pass those variables in parent constructor call. If you are afraid, that some developer who will expand your classes will omitt ocnstructor call, then you can create some variable and set it to some value in constructor. Then in working methods, you can check if this variables is still set like in constructor association. Then, if other developer will forget to call your parent constructor, this custom variable will not be set and you can throw a Exception, or other sign of error, to ensure that developer of a subclass will init object properly by parent constructor call.