Results 1 to 10 of 12
Thread: Some PHP Tips
-
01-01-2012 #1
Some PHP Tips
As of late I've been doing more and more PHP work, and figured I would post here some useful tips and tricks for the other PHP developers (just to as a reminder) and for the up and coming developers.
Function with unknown or variable amount of arguments.
This has come in handy a few times for me, first for example lets take a look at a usual everyday, function
OutputCode:<?php function some_functoin($arg1, $arg2) { print "argument 1: $arg1"; print "argument 2: $arg2"; } some_function("f00", "bar"); ?>
As you can see this is just a function that has to be passed two arguments, but what if suddenly we need to pass 3 or more, or perhaps only one?Code:argument 1: f00 argument 2: bar
Consider using the following.
OutputCode:<?php function some_function() { $args = func_get_args(); foreach ($args as $key => $value) print "argument {$key}: {$value}"; } some_function("foo"); some_function("f00", "bar", "w00t", array("yay", "win")); ?>
Now in our second example you can pass any # of arguments or none at all to our function, provided you make sure the appropriate checks are in place within the function you should have no problems.Code:argument 0: foo argument 0: f00 argument 1: bar argument 2: w00t argument 3: Array
PHP Constants
PHP has a wonderful set of very useful constants. These are as follows.
- __LINE__
- __FILE__
- __DIR__
- __FUNCTION__
- __CLASS__
- __METHOD__
- __NAMESPACE__
You should by the name alone be able to figure out what these are below is a quick example. Consider we are trying to include a script from our main directory called config.php we might write something like this. This is usually referred to as relative inclusion.
Now this is fine until we want to include our config.php from a file within a sub-directory it will not find our config/config.php file. So using the above we can do something like this. This way it will ALWAYS be relative to the files directory.Code:<?php require_once('config/config.php'); ?>
Code:<?php require_once(dirname(__FILE__) . '/config/config.php'); ?>
Random ID String
This is funny as a see this quite often people trying to generate a random ID string and using something like this.
Now I'm not sayin this is wrong as it would work just fine however most people don't realize that PHP already has a build in function to do just what they are looking for. A function called uniqid().Code:<?php function random_string($length = 10) { $allowd_chars = "abcdefghijklmnopqrstuvwxyz1234567890"; $buffer = ""; for ($x = 0; $x < $length; $x++) { $buffer .= rand(0, strlen($allowd_chars) - 1); } return $buffer; } ?>
OutputCode:<?php print "Random ID: " . uniqid(); print "Random ID: " . uniqid("foo_"); ?>
Getting a Users Real IP (Proxy Support)Code:Random ID: 6a9end93jd8 Random ID: foo_a639023bs0
Sometimes you need to get the users IP, perhaps for session matching etc... but what happens if they start using a proxy. Well we can still find their IP.
OutputCode:<?php if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } print $ip; ?>
Code:192.168.1.9 (Users Ip)
Serialize almost anything for cleaner storage.
This is a tip that can turn a good web application into a a great one. Serializing data is one of those things everyone seems to talk about yet, hardly anyone uses it. A good example is users preferences, lets say for example when you're developing your system you hypothesis that users will have the following preferences available for them to set. Time Zone, Default View, Number Entries.
Most people would create a users preferences table in MySQL and add those three values, however while this does work, we have to query the table and pull three different values, while 3 is not a huge number what if ti was 10, 20 or even more? A quick and simple way to do this is to create and array of you're preferences and then serialize that array and store it into a single database field, or flat file or whatever you're storage method may be.
OutputCode:<?php $user_preferences = array( 'time_zone' => -5, 'default_view' => 'main', 'num_ent' => 10, 'another_pref' => 'some value', 'foo' => 'bar', ); // serialize the data $prefs = serialize($user_preferences); // now in this i'm simply going to output however in rl situation you would read or write this // data to a db or file etc... print $prefs; ?>
As you can see from the above a nice serialize string with all your user preferences. This can later be unserialized or stored etc... and makes adding more later on a very quick and simple process, with no need to change your database or file scheme.Code:a:5:{s:9:"time_zone";i:-5;s:12:"default_view";s:4:"main";s:7:"num_ent";i:10;s:12:"another_pref";s:10:"some value";s:3:"foo";s:3:"bar";}
PHP Supports Native GZIP
This can be extreamly helpful in situations where you need to push data fast, and have the client decompress it on their end, or vise-versa.
OutputCode:<?php $data = "This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data. This is just an example of some long string data."; $comp_data = gzcompress($data); print "Data Size: " . strlen($data); print "Compressed Size: " . strlen($comp_data); ?>
As you can see this could be very helpful.Code:Data Size: 1099 Compressed Size: 66
------ Updates (July 17th 2012) ------
Mind your quotes!
As a c/++ programmer I find the PHP quoting system both odd and very handy. This is due the main difference between " and '.
For a moment lets assume we have the following code.
Now, while both of these statements will produce the exact same output. One is deemed a little more sanitary to use than the other in this particular instance. Do you know which one? and why?Code:<?php echo 'hello world'; echo "hello world"; ?>
In this case it's the single quote ' the reason for this is PHP treats the single quote as exactly what it is, in this case the letters 'hello world' zero pre or post processing is done to this string saving time. (Even though it's fractions of second these could add up)
Where as the double quote " will actually evaluate the string first, then process it. Consider the following example.
OutputCode:<?php $myvar = 'pixldrop is awesome'; echo '$myvar'; echo "$myvar"; ?>
Note: how the variable $myvar was not processed in the first instance.Code:$myvar pixldrop is awesome
Syntax, your best friend or worst enemy!
Yes it's true PHP's syntax is indeed a fickel mistress, it can be both friendly (in the fact that it's forgiving and takes many forms) but harsh in that it can get overwhelming and there can be many styles. Mixing PHP and HTML is never fun and can often get ugly fast, however here are a few tips to help you keep it clean!
For example sakes lets say we have an array with several elements, I'm going to use the names of my pugs in this case.
Now lets say we need to create a nice HTML list that end users would see.Code:<?php $options_array = array("Susie Q", "Savanna P", "Sasha D"); ?>
Note the : syntax we used to tell PHP that we are breaking from the foreach loop with the following, now this is not limited to foreach this can be done with almost all PHP keywords.Code:<html>etc.... <ul> <?php foreach($options_array as $opt) : ?> <li><?php print $opt; ?></li> <?php endforeach; ?> </ul> etc...</html>
Now knowing what we know above we can make this even more clean using PHP shorttags. However! be warned shorttags are may or maynot be supported on your version / installation of PHP they must be esnabled via the php.ini file.Code:<html>etc... <?php if ($myvar === 'some value') : ?> <p>This would only show if $myvar was equal to 'some value'</p> <?php else : ?> <p>This would show if $myvar is equal to anything other than 'some value'</p> <?php endif; ?> etc...</html>
Lets consider our first foreach loop example would could make a little more clean using short tags as follows.
Notice how we've dropped the opening <?php in place of a <? these should be fairly self explanitory. Also we've also dropped our <?php print for a <?= this tag means simple echo the following.Code:<html>etc.... <ul> <? foreach($options_array as $opt) : ?> <li><?=$opt ?></li> <? endforeach; ?> </ul> etc...</html>
Ternary operators
While we are talking about syntax it seems only fitting we talk about ternary operators. Ternary operators are simple a cleaner way of doing if ... else statments.
Note how we can take 8 lines and turn it into one! Using ternary operators.Code:$myvar = 10; // normal if etc.. if ($myvar > 9) { echo "my var is greater than 9, in fact its $myvar"; } else { echo "my var is less than or equal to 9 in fact its $myvar"; } // using ternary operators echo ($myvar > 9) ? "my var is greater than 9, in fact its $myvar" : "my var is less than or equal to 9, in fact its $myvar";
------ Updates August 20th, 2012 ------
So with the new PHP version 5.4.6 released they have introduced a lot a nice new ways to do things even some handy new features! With that I figured I would update this thread with
some of those new goodies.
Bring in the Traits
One feature of note with PHP 5.4 is Traits. Traits are a set or collection of methods grouped similarly in fashion to that of a class, however traits do NOT need to be and can't for that matter be instantiated.
Consider the following let's say we have a classes foo and bar now both foo and bar classes need to access a method called syn() prior to PHP 5.4 you could either a) write the method twice (once in each class) or b) create a global function however we all know that globals are never ideal.
Code:<?php class foo { public function blah() { ... $this->syn(); } private function syn() { echo "synmuffin is great!"; } } class bar { public function anotherblah() { ... $this->syn(); } private function syn() { echo "synmuffin is great!"; } } ?>
Now let's face it a golden rule to programming has always been and still is "If you have to write it twice your doing it wrong." As there should bever bee a reason to write the exact same code twice. However now with Traits we can create a collection of these methods and use them in any class without having to worry about inheratance etc...
Code:<?php trait misc { function syn() { echo "synmuffin is awesome!"; } } class foo { use misc; public function blah() { ... $this->syn(); } } class bar { use misc; public functoin anotherblah() { ... $this->syn(); } } ?>
Ahh much better we only had to write the function once, and we can simply use our trait within any class we like. Keep in mind you can use multipul defined traits by addine more with , example "use misc, anothermisc, etc..."
Array Hooray!
Finally arrays have gotten so much needed attenion in PHP 5.4, along with a new declaration syntax update (don't worry the old way still works) but they also now have built in dereferencing! One thing I used to envy java developers for, well no longer!
First up the new array syntax declaration.
Old Way
Code:<?php // example of a simple array $my_array = array("this", "is", "ma", "array"); // example of a assoc. array $my_array = array( "my_key0" => "this", "my_key1" => "is", "my_key2" => "ma", "my_key3" => "array" ); ?>
New Way
Code:<?php // example of a simple array $my_array = ["this", "is", "ma", "array"]; // example of an assoc. array $my_array = [ "my_key0" => "this", "my_key1" => "is", "my_key2" => "ma", "my_key3" => "array" ];
Next we have dereferencing! YAY!
Prior to PHP 5.4 lets say we had a string we wanted to break into peices and we only needed the first part. What we had to do was use something similar to the code below.
Code:<?php // our string $str = 'http://www.pixldrop.com/'; // lets say we wanted to split by : and get the protocol. $tmp = explode(':', $str); $protocol = $tmp[0]; echo "Your using: $protocol"; ?>
This is fine and will work however note the $tmp var we had to use and then transfer our $tmp[0] "protocol" to another var etc... well this is no longer the case.
Code:<?php // our string $str = 'http://www.pixldrop.com/'; // now we can do the following $protocol = explode(':', $str)[0]; echo "Your using: $protocol";
I know this seems like a very small bit but consider the above in a large nested loop with multipuil splits etc... those extra lines over and over, and keeping sorted all your temp vars can
become a real task, well no longer!
Back to our <?= again
A while back I had talked about syntax and using <?= in html files and how I liked it but it was never the same on all servers so be cautious with it blah blah etc... Well again this is no longer the case, go ahead and use <?= as of PHP 5.4 freely as it's now simply ALWAYS ON regardless of php.ini setting.
Code:// old way <html> ... more html here <?php echo $somevar; ?> </html> // now as of PHP 5.4 this will produce the same result as above <html> ... more html here <?=$somevar?> </html>
Get right down to proc level!
As of PHP 5.4 you can now (for some reason I've yet to use or find) specific number in binary format. Yes binary format.
Code:<?php $a = 0b10; echo "There are only $a kinds of people in thise world, those who understand binary and those who do not."; ?>
Time as a CONST?
This is hands down one of my fav new things on PHP 5.4 way back up top ^ I yammered on about PHP Constants and PHP having ones like __FILE__, __LINE__ etc... for those of you who listend and used them there is a new one that can be used to measure how long it took to process a page. The $_SERVER variable now has a element called "REQUEST_TIME_FLOAT". This handy little guy (or girl not sure) holds a microsecond precision float of the execution time for a script!
Code:<?php for ($x = 0; $x < 1000000; $x++) { // looping for 1 million iterations. } echo 'damn that took me ', round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2), 's'; ?>
Be sure to update to PHP 5.4 as it not only has these improvements but is vastly better at memory management, and have 100's of other goodies in it, for more info on PHP 5.4 http://www.php.net/ChangeLog-5.php can be your friend!
---------------------------------------------------------------------------------------
This thread has been going on for some time now, and I hope someone has found it useful. If you have any specific PHP question feel free to ask here and I'd be happy to answer to the best of my abilities.
- syn
Updated: August 20th 2012Last edited by synmuffin; 08-20-2012 at 09:20 AM.
-
The Following 9 Users Say Thank You to synmuffin For This Useful Post:
bigtimer5 (01-01-2012), Brandon (01-02-2012), godzcheater (07-17-2012), Governor (07-17-2012), imnotanoob (01-12-2013), Mac (01-02-2012), ModioHomeBasic (01-12-2013),
Seras(01-09-2013), _r0gu3__ (01-08-2012)
-
01-01-2012 #2
Re: Some PHP Tips
I'm not even learning php yet, but ***** youda best.

-
01-02-2012 #3
-
The Following User Says Thank You to Brandon For This Useful Post:
Mac (01-02-2012)
-
01-02-2012 #4
Re: Some PHP Tips
Added a few more things I remember this morning as I was eating my cerial.
Fast, simple, lightweight and FREE image capture and upload!
Check out pixldrop.com today!
Game-Tuts IRC Channel
Webchat: Click here
irc.epicgeeks.net -j #gametuts
-
The Following User Says Thank You to synmuffin For This Useful Post:
Brandon (01-02-2012)
-
07-17-2012 #5
Re: Some PHP Tips
Updated with a few more tidbits! Enjoy.
Fast, simple, lightweight and FREE image capture and upload!
Check out pixldrop.com today!
Game-Tuts IRC Channel
Webchat: Click here
irc.epicgeeks.net -j #gametuts
-
The Following 4 Users Say Thank You to synmuffin For This Useful Post:
Brandon (07-23-2012), Governor (07-17-2012), imnotanoob (01-12-2013), NoVa Gamester (07-17-2012)
-
08-20-2012 #6
Re: Some PHP Tips
Again, I've done some more updates these are specific to the new PHP 5.4 enjoy, questions, comments, feedback are all welcome.
Fast, simple, lightweight and FREE image capture and upload!
Check out pixldrop.com today!
Game-Tuts IRC Channel
Webchat: Click here
irc.epicgeeks.net -j #gametuts
-
-
01-12-2013 #7
-
01-12-2013 #8
Re: Some PHP Tips
Thanks syn, been looking for some PHP on here.
-
01-12-2013 #9
-
01-12-2013 #10
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)



LinkBack URL
About LinkBacks
Reply With Quote













Bookmarks