PHP Coding Tips

Monday, August 27, 2012

PHP File extension - How to get file extension ?

You can get a file extension in PHP using function pathinfo(). Here is sample usage:$extension = pathinfo( $fileName , PATHINFO_EXTENSION );

Monday, August 20, 2012

PHP Function default parameter value

You can set default parameter value for method or function by giving it's initial value at argument declaration, see example:function myFunc( $number = 8 ) { } If client will pass a number to that function like myFunc( 11 ), then $number value will be 11. But if user will call it without argument or parameter, the $number variable will have value of

How to remove white space on the left of a strin ?

You can use ltrim() function to remove white symbols at begining of a string, as example shows:$leftTrimmed = ltrim( $oldText );

PHP Store variable in a session

As you propably know, HTTP protocol is stateless, that means that each request run php parser and doesn't know about variables from previous page displayed.You can mantain variable values betweend numerous requests of the same user by storing this varaibles in session. To do that, you just have to call session_start() to start a session (a ID of session will be stored in browser cookies) and add a variable to $_SESSION array.See example below:session_start(); $_SESSION['myvalue'] = 5; Now, if you get $_SESSION['myvalue'] on other user request, you will get value of 5.

PHP Print state of a session

If you want to print all current variables stroed in session just use print_r function, as exaple shows:print_r( $_SESSION ); This will print all varaibles previously set in current session. Don't forget to call session_start() earlier to start a browser session

How to incrase a variable by given value ?

You can incrase a varaible value by number by += operator. If you want to incrase string by appending some data at the end, then use .= operator.See examples below:$number += 10; $string .= " and something";

How to access property of an object in PHP ?

You can access property of an object in php by opeartor ->.Just place it after a object variable, but remeber that accessed property must have valid access like private/protected/public.You can't access a private or protected object property from outside of a class or subclass.Item that you are accessing have to be public. You can access protected properties from subclasses and private properties if you are working with class wich have that property.Here is example how to access a public property in a object:class Sample { public $value; } $object = new Sample(); $object->value = 8; Remeber that good practice says to use getter and setter methods. If your project at some point will needa refactor that accessing some variable needs additional action then you can just change get or set method for that varaible.

Friday, August 17, 2012

Get last element of an array in PHP

To get last element of an array just use end() function. First idea can by get a index at count()-1 but remember that php arrays are associative arrays, so you can grab last element just by number.$lastElement = end($array); As simple as you see. It works even if your indexes are strings like 'name','surname' etc.

How to get size of an array in PHP (count elements) ?

To count elements and grab size of an array in php just use a count function:$elementsNumber = count( $array ); This will return a number of elements that are set in array

Get random element from an array in PHP

This tutorial will show you how to get a random element from an array in PHP. We will use mt_rand function and count to determine minimal and maximal index of a array. Remeber that arrays are indexed from 0, so if you have a ten elements array, the elements have indexes from 0 to 9. So, we need a random number that will by at least 0 but smaller than 10. Wi will user mt_rand function te generate that number. Se example how to use count and mt_rand to get random element from an array:$array = array( 1,2,3,4,5 ); echo $array[mt_rand(0,count($array)-1)]; As you can see we have to substract 1 from the size of an array. Also we use faster and better function mt_rand, because rand is slower and less randomness.

PHP Print array - how to show contents of an array

You can simple show entire contents of an array by callind print_r function:print_r($theArray); $arrayContents = print_r($theArray,true); Second example show how you can grab output to a variable to parse it or store somewhere (lika a file)

PHP Array add element - how to append element to an array

If you have a PHP array and wants to add element to it, you can do it just in this way:$myArray[] = 'new element'; This will add element to php array at its end

PHP Integer - how to determine if a value is a number in PHP ?

You can check type of a varaible in php calling gettype:$type = gettype( $variable ); var_dump( $variable ); Second line shows another easy way to show variable type, but it works by outputing result and you cannot grab it to variable. But second way can traverse arrays recursive and show all of its contents. Also it will show you all informations about any object.

Tuesday, August 14, 2012

Maximum execution time of 30 seconds exceeded in...

If you encounter this error that means, that work to do by apache web server to handle your taks was long-time nad it was stopped by time limit provided by ini configuration in php. Such task as image resizing or huge files operations can ast long. You can change setting of time limit in PHP by function set time limit, where you give max execution time in seconds as parameter:set_time_limit( 300 );But be aware. You can hung your server if your job is endless (like never ending loop), so don't set this value too high.

Monday, August 13, 2012

How to measure length of a string ?

If you want to check a length of the string in php, just user strlen() function. It will return the given string length. See example:if ( strlen( $unknownString ) > 10 ) { echo "String has more than 10 characters"; }

How to remove white space in PHP (remove spaces at begining and end of string)?

You can remove trailing and leading white characters in PHP. What is white character ? it's just a character wich we don't see like tab, space, or new line character. To remove white space characters in PHP just use trim() function. It will do the work, here comes two sample codes:$trimmed = trim( $somestring ); echo "[".trim(" hello ")."]"; As you can see you can use this function inline to for example filter output.

Friday, August 10, 2012

Why not to use rand() in PHP

The rand() function in PHP is much more older, and doesn't generate such a good results as mt_rand(). What means good ? Just random. Computers cannot create real random numbers, so rand() and mt_rand() are just using some mathematic calculations to create pseudo random numbers, and mt_rand() has better and faster algorithm. Code sample:$i = rand(1,5); // don't use ! $i = mt_rand(1,5); // betterIf you want to check this, just generate a image with black and white pixels, selecting it by rand and mt_rand 0 and 1 values. You can see some patter-like areas in image created by rand()

mysql_fetch_array and mysql_fetch_assoc difference

Many beginners in php user mysql_fetch_array after using mysql_query. This taking a row from mysql result set and put it's resulting data to an array format. By first look, this work same as mysql_fetch_assoc but the difference is in way that data is put. Assoc is creating less indexes, because it uses only those indexes thar are column names. Mysql_fetch_array will also create values in numered indexes starting from 0, representing next columns.$q = mysql_query("SELECT id,val FROM table"); // This create indexes 0,1,id,val: print_r( mysql_fetch_array( $q ) ); // This create indexes id,val: print_r( mysql_fetch_assoc( $q ) );So if you are not using indexes like 0, 1 when getting data from your query, but using only associative array keys - don't use mysql_fetch_array to gain performance.

How to randomize array in PHP ?

If you want to random order of elements in your php array, use shuffle function:$somethings = array(); $somethings[0] = "element1"; $somethings[1] = "element2"; $somethings[2] = "element3"; shuffle( $somethins );Notice that this will modify that array wich you put as a argument (pass by reference)

How to add element to an array ?

If you want how to add or append element to a PHP array, see this code snippet:$somethings = array(); $somethings[] = "element"; // append as last element $somethings[4] = "other element"; $somethings['thekey'] = "some other element";

Wednesday, August 8, 2012

How to check that one string contains another in PHP

If you want to check if one string contains desired string, you can use strpos function. But be aware - the problem rises when a needle is on position 0 of checked string. In that situation php strpos() returns 0, and it will return false if string is not found. So, to compare if a string is containing user string, use !== operatorif ( strpos( $string , 'somestring' ) !== false ) { }Also use === false if you want to check that string doesn't not contains data

jQuery action called twice or more times

If you are begginer in jQuery you can do a common mistake, espacially when dealing with dynamic content, ajax, and dynamic interactive elements. This problem can be non-working action that you have bind to some element (but really did not) or action is evaluated multiple times. To deal with that problem, you must understand how jQuery works. When you add action like .click(function(){....}); you are binding this action only in time when this element exists, so if you provide new element in for exaple AJAX request, it will not react to click. You must bind this event after adding element to DOM structure by calling .click with its selector. Another common problem is that function can be called multiple times. This works this way, because you are binding function to element multiple times. Each time witch executing .click(function(){});. You can clear previously assigned action to that element and call click() to assign fresh, single event listener, like that:$("#mybutton").unbind('click'); $("#mybutton").click(function(){ alert('x'); });But be carefull, you can detach some earlier bind to other actions you have binded !

How to call parent constructor ?

If you write your own constructor, you propably will want to call a parent construtor first to set up a class. You can do it in that way:parent::__construct();This can be used also to call parent methods.

Multiple checkboxes send to array as php

If you have bad experience with making inputs named like cat1,cat2,cat3, there is a way to post to php custom amount of elements within the same field name. If you add [] to your field name, this value will be posted to PHP script as array of values, and you can traverse array easily: Category 1 Category 1 Category 1 // in php: foreach( $_POST['selectedcategories'] as $cat ) { echo "User selected $cat !
"; }
Of course, you can generate inputs by php from some source selecion model

Deal with path errors when using mod rewrite and directory-like url

If you are using directory-like url's like this:mysite.com/one/two/threeany css or javascript file accesed by "script.js" will be searched in /one/two/three/scrit.js when 404 error will occur. Add a slash symbol at begining of path to access that file from global context like "/script.js". This is also useful for broken mod-rewrite links, like 404 error on /one/two/index.php. Your href attribute should be set to "/index.php" not "index.php" or whole address: "http://mysite.com/index.php". You can write your own href-generating function/class that will append your current domain to every link.

How to pass value to included smarty template

You can pass a variable value to a smarty template while including it. Just type name of a variable as parameter and value in quotas:{include file="fielderror.tpl" fieldname="albums"}Now in fielderror.tpl you can access this variable just by {$albums}

Tuesday, August 7, 2012

print_r in smarty - How to print your array contents in smarty template.

You can print a array contents like in php print_r() function in smarty tempalte. The common mistake is to forget about second print_r parametr for returning it's output. This parameter have to be set to true. If you forget to set it to true, your array contents propably will be somewhere at begining of a content. This is the solution:
{$myArray|@print_r:true}
Notice the @ symbol that provides parsing argument as array, not as string.

Filter smarty variable in .TPL file for new lines to br tag

You can filter any smarty variable by using allowed php function as a modifier. For example to put BR tags instead new lines you can do this in smarty template:{$content|nl2br}Good way to output filter or (if you provide own modifier) you can format dates etc.

Smarty variable value in quotation mark

if you want to insert smarty variable value into string that is already in smarty "variable" (function call), just append it with `......` like shown in this example:{$obj->myMethod("This is my value: `$value`")}Usefull for owne link-preprocessor/rewriter

Organize your input checking and error reporting. Escape from too many inner if's

It's common to check some variables and report error / unsucceful operation if value is bad or to check result of operations before going forward. It can provide a bad code structure, where you can't find yourself in middle of a ton of bracets. Try to use return or exit instead, this will provide a cleaner, maintable code:function compute( $a , $b ) { if ( $a <= 5 ) { // outpu error return; } if ( $b >= 3 ) { // output error return; } // logic }As you can see, second solution is much more clear.

Organize your global functions to static methods - alternative to structural/procedural programming

If you are not into Object Oriented Programming, and include files and functions everywhere, you can get lost in your own function names. The good alternative is to group your functions into classes with static methods:class UserModule { public static function getUserId() { ... } public static function removeUser( $id ) { ... } } UserModule::removeUser( 11 );

How to merge (join) two arrayis in PHP together ?

You can merge all elements of two and more arrays into one array by array_merger func:$summaricArray = array_merge( $firstPartArray , $secondPartArray );This results in all elements from both arrays in summaricArray

User not logged in PHP when requesting from flash etc. because of invalid session.

This is way to set a session ID. Remember to call session_id before session_start. This is helpful for common issue when request from flash uploader (uploadify etc.) causes errors, because requested PHP file doesn'y knows that user is logged (see flash request as new, non-logged user).if ( isset( $_POST['sessionid'] ) ) { session_id( $_POST['sessionid'] ); } session_start();Remember that you must set sessionid on POST (or GET) request. This is useful when you connect to php page from other source than web browser (especially flash upload for example). You can pass your session ID to flash object 'flashvars' and when reqiesting upload or other page from SWF you can post/get session variable to access the same session normal web browser request has and for example be logged as current user.

How to split an array to parts by comma or special character (string to array) ?

Use explode function for this job:$names = 'John,Margaret,Thomas'; $namesArray = explode( ',' , $names ); echo $namesArray[0]; echo $namesArray[1]; echo $namesArray[2];You can also use a character sequence to split string like a "splitplace"

How to access global variable in php ?

If you are in a function on class method scope, you can gain access to a global variable by using a global keyword.$x = 5; function myFunc() { global $x; echo $x; }Remeber that using globals usually isn't a good idea. Better idea would be divide your globals by categories/modules and store it in static variables of some classes.

How to convert string to int, or other variable to integer

To convert string to int in PHP you can use casting or intval() function. See example: $intVariable = intval( $unknownVariable ); // or: $intVariable = (int)$unknownVariable;You can cast with this function every php variable, like double. Remember that php can throw a error or warning, especially if variable is not set

How to show informations about current PHP install

You can show informations about current php install by function:phpinfo();This will give you to output PHP version, variables, installed modules and versions and also all configuration directiories, ports etc.