Excellent PHP Tips/Tricks/Techniques To Follow

Status
Not open for further replies.
How about the use of includes...for fuck sake I swear I've seen an include for a group of includes that grouped another group of includes and still a billion includes to include more includes...fucking includes.
 


No mention of ' vs. " ?

Single quotes are faster than double as PHP won't parse them for variables.

The only real rule with single quotes besides double quotes are that you use single quotes when you don't want to expand a variable value into a string for instance.

Code:
$variable = 'This is a string';

1) echo 'This is a string';
2) echo "$variable";
3) echo '$variable';

In the above example numbers 1 and 2 will echo the same thing but number 3 will only echo $variable and not This is a string. So double quotes are just used to expand the variable.

PHP 5 also has cleaned up a bunch of things that I haven't got around to digging into considering most hosting companies seem to still be only supporting PHP 4.3 and lower.
 
I actually use alot of functions, helps me write stuff faster. I create "black boxes", that way I only care about what goes in and what comes out. I could care less about optimizations until I know that I need to address a speed issue. Much of the stuff I write is quick and dirty, one off stuff. So really it all depends on your point of view.

I do try and create function "libraries" that I can use between programs, saves me a ton of time. Many functions that start out as only a few lines but have more features added later.
 
Just dropping a line saying that I'll team up with Aqeuitas in here to answer some coding questions..
 
The only real rule with single quotes besides double quotes are that you use single quotes when you don't want to expand a variable value into a string for instance.

Code:
$variable = 'This is a string';

1) echo 'This is a string';
2) echo "$variable";
3) echo '$variable';
In the above example numbers 1 and 2 will echo the same thing but number 3 will only echo $variable and not This is a string. So double quotes are just used to expand the variable.

PHP 5 also has cleaned up a bunch of things that I haven't got around to digging into considering most hosting companies seem to still be only supporting PHP 4.3 and lower.

Another thing to mention, since were doing basics, is inserting a variable into a string. You'll do this alot with MySQL coding.

If you have a variable you want to insert in a string, you use ". to break out of the string and concatenate a variable and the reverse, ." , to go back into the string.


PHP:
$variable = "Fire";
$string = "Wicked".$variable." rocks.";
echo $string;
This would print out 'WickedFire rocks.'. Here's some food for thought. Assume you have a variable with someone's username in it. If you wanted to pull someones record from a database, your string might look like:
PHP:
$results = mysql_query("SELECT * FROM users WHERE username = ".$userName."");
Enjoy.
 
How about the use of includes...for fuck sake I swear I've seen an include for a group of includes that grouped another group of includes and still a billion includes to include more includes...fucking includes.

Yeah you can do that. Shit, I've done it plenty of times.

include ("whatever.php");

will, quite frankly, copy and paste whatever the hell the contents of whatever.php are exactly where you wrote that command.

Nest that in multiple files and it'll just work its way up. Ultimately, PHP is going to get your code so that, in cache, its one file. So, before executing code, it'll handle all the includes you throw at it first, basically by just copy and pasting whatever you specify, wherever you specify it.
 
Anyway.. Moving on, do talk about some more advanced optimizations..

for ($i=0; $i<count(..).. <- not good etc
Meh. I've seen better. That's a pretty fundamental control structure, though.

regexes like you said in your last line of the orig post (ctype_digit)
As you study (if you study) the history of Unix environments, you'll see RegEx (or Regular Expression) popup. RegEx is like the elder sage of functions. There's definitely newer and better functions out there, but this works and its well documented. Its not as pretty or efficient, but RegEx is HIGHLY powerful (ridiculously powerful). But it'll be slow. Alternatives to RegEx include XPath and, depending what you're trying to accomplish, PHP DOM functions.

require versus require_once (< php5.2)
require_once is a new function in PHP4. It pretty much does what it says. It only allows you to require the file once in the script. If you inadvertently require something twice, you'll get an error indicating that you can't redefine whatever is in that file. Basically, just don't be sloppy in your coding and you'll never have to worry about it.

Call me old fashioned but I tend to avoid these 'fallback' functions. I'd rather be a good programmer at the core than have an arsenal of 'fallback' functions that prevent me from fucking up. Its much better to be a good coder and not fuck up to begin with. :D

Also, even though you didn't ask for it, check out this page on 'require' vs 'include':
PHP Tutorial - Require
(Btw, Tizag is, in the words of Tyrone Biggums, dah bommm)


But still, most slowdown comes from external factors, like mysql. So maybe you could show how to cache a query. Or if you have a curl app, obviously you're going to spend most your time waiting for a response from the remote server.
Definitely doable, I just haven't taken the time to think about it first. I'm pretty sure you can store common queries in your MySQL tables as stored procedures. Its possible, look it up.
 
ANOTHER IMPORTANT TIP: SETUP A LOCAL WAMP SERVER FOR TESTING YOUR CODE

I use WAMP to develop all my code. Its basically an all-in-one file that sets up a web/php/mysql server on your computer. This way, you don't have to upload, pay for bandwidth and hosting, and won't crash any servers with your shitty noob code.

Just download, install, and put all your stuff in C:\wamp\www (or wherever you installed it to).
Then, access it with cPanel® << heh Jon, your code's showing me stuff I shouldnt see :)
You can manage your SQL dbs with http://localhost/phpmyadmin/ (make sure you have that trailing slash as, by default, its not correctly configured to work without it).

You can do damn near anything you can do on a regular server (and sometimes more) with a WAMP server. I'll get into the more complicated configuration if anyone requests it.

Download it here:
PHP5 APACHE MYSQL for Windows : install WAMP5
 
krazyjosh, what he was trying to say is that alot of projects include tens of files, which will affect your performance alot. I try to minimize the includes required.

Ofcourse, if you use some open source project, you have no control over this.

And what I meant by require versus require_once is that require_once does an extra check to see if the file has already been required. So require is faster. However, in php 5.2 they seem to have fixed this performance issue.

And again, as this is about performance issues, ctype_digit will be faster than any regex to see if a variable is indeed numerical. Always use ctype_whatever if that's just what you need. ctype_alnum etc.

- What's also great is that APC and memcache amongst others allow you to save stuff to memory, which means it's really fast. Do check that out.

- One other tip, if you have a page that requires that you update the view_count, don't do that immediately every time. It has to create a table lock and what not and it's slow. Save it to memory or INSERT in a memory table and then write that out as a query once per hour.

- Another tip, if you have multiple inserts use this sql statement:

insert into table (col, col2) values (1, 2), (3, 4); etc..

- Only fetch the columns you need. Don't do select * from table, do select id, name from table if these are the only values you need. Saves up memory and is generally faster.

- If you're using PHP 5, use mysqli_ instead of mysql_ functions.

- Use multi_curl if you want to fetch multiple pages (from different servers) at once.

- Use UPDATE LOW_PRIORITY if you want.

- Always use indexes on your tables.

- Use a PHP profiler to find out where your code is slow: xdebug, apd.

- Log slow queries with mysql slow query log.

- Golden tip: use mysqlnd; a native PHP driver for mysql. Much faster.

He used Xdebug and system statistics to test PHP 5 with mysqlnd. Some of his findings:

Connection time has gone down: from ~900ms down to ~320ms
Better query time: from ~350ms down to ~300ms
Less memory consumption: ~30% according to server statistics
All in all he describes the mysqlnd test run with:

You can download it for PHP5, will be built-in with PHP6.
 
Thanks for doing the post, Aequitas, I was just thinking their needed to be one in this section. Where would you guys recommend a COMPLETE and TOTAL n00b with php start? I'm talking See Spot Run, shit.
 
In the grand scheme of things, duplicating code is BAD. That's one reason functions and include files are used. See The DRY Principle

Worrying about performance optimizations unnecessarily is called premature optimization. See "when to optimize" here Optimization (computer science - Wikipedia, the free encyclopedia) It rarely makes sense to duplicate code for optimization's sake anymore. One place I know it's still done is at the core of game engines in assembly language. The only way it would make sense in PHP would be if you were having a known performance problem that couldn't be solved another way (adding memory or CPU would likely make more sense).

Some good stuff, particularly regarding comments and code formatting but I would definitely advise not duplicating code.

A great basic programming theory book is "The Pragmatic Programmer".
 
Thanks for doing the post, Aequitas, I was just thinking their needed to be one in this section. Where would you guys recommend a COMPLETE and TOTAL n00b with php start? I'm talking See Spot Run, shit.

See spot run shit, huh?

Step 1.) Setup a WAMP server
Step 2.) When your WAMP server is installed, put it online (using the menu from the icon in the system tray).
Step 3.) Open C:\wamp\www (or wherever you installed it to) and create the following file named 'phpinfo.php':
PHP:
<?php
phpinfo();
?>
Step 4.) Load up http: // localhost / phpinfo.php (without the spaces)
Step 5.) You should see a page similar to this. If so, congrats you wrote your first PHP script. Continue on. If not, go back to 1 and figure out what you did wrong.
test-php-installation.gif

Step 6.) Read and go thru this: PHP MySQL Tutorial (skip step 1 since you already installed WAMP)

I actually really like this website. Its pretty no-bullshit about what you need to know and teaching it to you. Plain design, straightforward tuts.
I think its just as good as any book will teach you, honestly.

Start from the 2 and work your way down to 11.


While you are coding:

Two bookmarks you should use are:
W3Schools Online Web Tutorials
Tizag Tutorials


And this is your PHP manual: PHP: PHP Manual - Manual
Get to know it and love it. When I'm coding PHP, I'm typically landing on that site anywhere from 2-20 times per hour. Everything that PHP can do is listed and defined on that site. Functions, inputs, outputs, syntax, everything. That is your bible.

Use the search in the top right. For example, here are your mysql functions:
PHP: mysql_query - Manual

Googling a PHP command usually works, too. Often times the first result in the SERPs is the PHP manual. And the comments in the PHP manual are often times very helpful, as well.
 
Thanks for doing the post, Aequitas, I was just thinking their needed to be one in this section. Where would you guys recommend a COMPLETE and TOTAL n00b with php start? I'm talking See Spot Run, shit.

I just uploaded a ton of good books you can start out with, you can download them for free without a password by clicking here.

They are basically all the O'Riely books on PHP and MySql.
 
Status
Not open for further replies.