tag:blogger.com,1999:blog-25481672725144577852024-03-28T03:53:22.672-07:00PHP Coding TipsPHP Coding tips & tricks. Function & error explanation, coding style, how tos etc. Short notes posted directly from developer work environment.Unknownnoreply@blogger.comBlogger47125tag:blogger.com,1999:blog-2548167272514457785.post-31051072096566176192013-03-28T08:01:00.001-07:002013-03-28T08:01:19.220-07:00PHP password hash with saltIt 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:<code>function getHash( $pass , $login ) {
$salt = substr( md5( $login ) , 0 , 10 );
return hash( 'sha256' , $pass . 'ThEStAtIcSaLe' . $salt );
}</code>Remeber to use same function when checking user credentials.It will be also more secure to use slower hashing/crypting function Unknownnoreply@blogger.com312tag:blogger.com,1999:blog-2548167272514457785.post-3315901533887809502013-03-28T07:58:00.001-07:002013-03-28T07:58:58.122-07:00Inheritance in PHPInheritance (extending classes) is realised in PHP with extends keyword:<code>class albumController extends MfStandardController {</code>Now, object of class albumController will be of type albumController, but also of type MfStandardController, because MfStandardController is a parent of this class Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-78319321343052885632013-03-28T07:57:00.001-07:002013-03-28T07:57:36.833-07:00Sample smarty loop with imagesIf 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:<code>{foreach from=$sm_photos item=item}
<img src="/content/photophoto/1/{$item.file}">
{/foreach}</code>If your path will not target image file, you can get 404 error, but typically image will be just hidden Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-60597239876863113872013-03-21T06:01:00.001-07:002013-03-21T06:01:29.264-07:00PHP: Get last element of arrayOften 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:<code>$exampleArray = array( 3,6,8,11,14 );
$lastElement = $array[ count($exampleArray) - 1];
echo $lastElement; // prints 14</code>This is the obvious way for some begginer developers. But more experienced developers will know,
that there is a function defined especially for this purpose:
<code>
echo end( $exampleArray ); // prints 14
</code>
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:
<code>
reset( $exampleArray ); // prints 14
</code>
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:
<code>
echo end(array_keys( $exampleArray) );
// or:
end( $exampleArray );
echo key( $exampleArray );
</code>
If you don't want to move internal array pointer, you can use another one-liner to get last element from array:
<code>
$last = array_slice($array, -1, 1, true);
</code>Unknownnoreply@blogger.com42tag:blogger.com,1999:blog-2548167272514457785.post-62446868625570515672013-03-21T05:09:00.001-07:002013-03-21T05:09:53.461-07:00How 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 <b>escape sequence</b>. 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:<code>echo "This example shows \"escape sequences\" in php string, like quotes etc";
echo 'This example shows \'escape sequences\' in php string, like quotes etc';</code>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: "\\".Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-16714097878129470092013-03-20T01:48:00.001-07:002013-03-20T01:48:26.224-07:00How 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:
<code>// 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}</code>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.
<br>
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.
<br>
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 <b>do not use dollar sign</b>.
<br>
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.
<br>
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.
<br>
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 <a href="http://phphowtos.blogspot.com/2012/08/printr-in-smarty-how-to-print-your.html">using print_r in SMARTY</a>, so check itd.
<br>
If you want to provide additional filtering when iterating over items, see my
<a href="http://phphowtos.blogspot.com/2012/08/filter-smarty-variable-in-tpl-file-for.html">tutorial about modifiers here</a>.Unknownnoreply@blogger.com14tag:blogger.com,1999:blog-2548167272514457785.post-55397987892260657062013-03-19T06:43:00.001-07:002013-03-19T06:43:45.886-07:00Call superclass method in object oriented PHP applicationYou can call parent methods using :: operator, as in example below:<code>parent::init( 'aaa' );</code>This situation works also, when dealing with static methods.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-6994063216440789802013-03-19T06:42:00.001-07:002013-03-19T06:42:04.745-07:00Call parent constructor in PHPYou 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:
<code>public function __construct() {
parent::__construct( 11 );
}
</code>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.Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-2548167272514457785.post-66446630945663540192013-01-30T01:58:00.001-08:002013-01-30T01:58:27.865-08:00Best way to secure e-mail in SMARTY template and CSSSee the best way to secure your e-mail from spambots. Just rearrange text flow to reverse and reverse an email with strrev() function:<code><span style="unicode-bidi:bidi-override; direction: rtl;">
{$sm_item.email|strrev}
</span> </code>Now you have your e-mail backwarded in page source, but displayed properlyUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-64029524911178016952012-11-14T06:07:00.001-08:002012-11-14T06:07:00.916-08:00A three-line guestbook in PHPBelow you can see a short script that causes to write somthing you enter a form to a file. Each entry is appended in new line.<code><form method=post><input name=a><input type=submit></form>
<?php
if($_POST['a'])file_put_contents('z.txt',$_POST['a']."\n",FILE_APPEND);</code>Unknownnoreply@blogger.com12tag:blogger.com,1999:blog-2548167272514457785.post-90378828408398679962012-08-27T03:14:00.001-07:002012-08-27T03:14:14.556-07:00PHP File extension - How to get file extension ?You can get a file extension in PHP using function pathinfo(). Here is sample usage:<code>$extension = pathinfo( $fileName , PATHINFO_EXTENSION );
</code>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-2548167272514457785.post-90968392304057228622012-08-20T05:51:00.001-07:002012-08-20T05:51:17.196-07:00PHP Function default parameter valueYou can set default parameter value for method or function by giving it's initial value at argument declaration, see example:<code>function myFunc( $number = 8 ) {
}
</code>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 Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-2548167272514457785.post-84606419617192851802012-08-20T05:48:00.001-07:002012-08-20T05:48:51.869-07:00How 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:<code>$leftTrimmed = ltrim( $oldText );
</code>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-30614673762672703032012-08-20T05:47:00.001-07:002012-08-20T05:47:39.273-07:00PHP Store variable in a sessionAs 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:<code>session_start();
$_SESSION['myvalue'] = 5;
</code>Now, if you get $_SESSION['myvalue'] on other user request, you will get value of 5.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-73376914723943287132012-08-20T05:44:00.001-07:002012-08-20T05:44:34.217-07:00PHP Print state of a sessionIf you want to print all current variables stroed in session just use print_r function, as exaple shows:<code>print_r( $_SESSION );
</code>This will print all varaibles previously set in current session. Don't forget to call session_start() earlier to start a browser sessionUnknownnoreply@blogger.com2tag:blogger.com,1999:blog-2548167272514457785.post-36511137156037545082012-08-20T05:43:00.001-07:002012-08-20T05:43:05.415-07:00How 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:<code>$number += 10;
$string .= " and something";
</code>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-80420314314841467232012-08-20T05:41:00.001-07:002012-08-20T05:41:16.197-07:00How 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:<code>class Sample {
public $value;
}
$object = new Sample();
$object->value = 8;
</code>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.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-29226194275848398402012-08-17T03:24:00.001-07:002012-08-17T03:24:04.413-07:00Get last element of an array in PHPTo 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.<code>$lastElement = end($array);
</code>As simple as you see. It works even if your indexes are strings like 'name','surname' etc.Unknownnoreply@blogger.com22tag:blogger.com,1999:blog-2548167272514457785.post-65175056213388708402012-08-17T03:21:00.001-07:002012-08-17T03:21:01.679-07:00How 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:<code>$elementsNumber = count( $array );
</code>This will return a number of elements that are set in arrayUnknownnoreply@blogger.com1tag:blogger.com,1999:blog-2548167272514457785.post-23962590570093929372012-08-17T03:19:00.001-07:002012-08-17T03:19:49.233-07:00Get random element from an array in PHPThis 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:<code>$array = array( 1,2,3,4,5 );
echo $array[mt_rand(0,count($array)-1)];
</code>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.Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-2548167272514457785.post-47653916490613111672012-08-17T03:16:00.001-07:002012-08-17T03:16:13.763-07:00PHP Print array - how to show contents of an arrayYou can simple show entire contents of an array by callind print_r function:<code>print_r($theArray);
$arrayContents = print_r($theArray,true);
</code>Second example show how you can grab output to a variable to parse it or store somewhere (lika a file)Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-2548167272514457785.post-420548422580481122012-08-17T03:14:00.001-07:002012-08-17T03:14:20.137-07:00PHP Array add element - how to append element to an arrayIf you have a PHP array and wants to add element to it, you can do it just in this way:<code>$myArray[] = 'new element';
</code>This will add element to php array at its endUnknownnoreply@blogger.com13tag:blogger.com,1999:blog-2548167272514457785.post-63863498165406678662012-08-17T03:12:00.001-07:002012-08-17T03:12:58.347-07:00PHP Integer - how to determine if a value is a number in PHP ?You can check type of a varaible in php calling gettype:<code>$type = gettype( $variable );
var_dump( $variable );
</code>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.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-49351332035016735692012-08-14T00:19:00.001-07:002012-08-14T00:19:43.773-07:00Maximum 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:<code>set_time_limit( 300 );</code>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.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-2548167272514457785.post-70562845963158466772012-08-13T05:00:00.001-07:002012-08-13T05:00:41.204-07:00How 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:<code>if ( strlen( $unknownString ) > 10 ) { echo "String has more than 10 characters"; }</code>Unknownnoreply@blogger.com1