tags:

views:

669

answers:

8

As you probably figured out from the title, I'm relatively new to PHP, I'm not PHP retarded, but I'm still in my error prone phase. I would just like to know some good tips to help expedite my progress. I recently learned that it's good practice to totally separate everything from everything else, so keep my html forms in one file, and my form handlers in another and just include the two. That was a good tip. If you cant think of anything, just try to think back to when you were a newbie and what you had to learn the hard way. Any tips would help, thankyou

+2  A: 

Don't use the error suppression operator (@). It's tempting to turn off a pesky notice or warning that you otherwise might not know what to do with, but there's always a better way, and it will come back to haunt you later.

That goes hand-in-hand with doing your development with display_errors set to on for E_NOTICE error_reporting level. The warnings and notices will let you know if you're doing something that might be considered bad practice (such as not checking if an array index exists before using it).

zombat
That's generally true, but there are specific use cases for @ error supression, for example: $page = (int) @$_GET['page'];
Pies
No ... check if `$_GET['page']` isset first. Really simple if statement.
Chacha102
Rarely? Sure. Never? No way. There are cases you need to use it to avoid spurious errors in your log.
cletus
BTW .. My comment was directed at that specific case. There are instances where you need to use it, just not for assigning variables.
Chacha102
I'd love an example of some code where you couldn't solve the problem by addressing the problem itself instead of suppressing the error. I'd love that more than just the downvote, actually.
zombat
There is one I've heard of, Its like getmxrr or something, they errors if the domain doesn't have a DNS record. Only one I have ever came accross.
Chacha102
Just to clarify, this is a tip for a beginner. I firmly believe that beginners should never use the `@` operator. I will change the language to say "Don't" instead of "Never" to avoid starting a semantics war, but if you're suppressing errors in code, then you'd better know what you're doing, in which case you won't be a beginner.
zombat
Good example: deleting a file. unlink() will generate a warning if the file isn't there but if you don't care if its there or not then @unlink($filename) is entirely appropriate.
cletus
@cletus: I would counter-claim that that is not a good example, as there are many reasons an `unlink()` might fail. I would use `if (file_exists($filename)) unlink($filename);` specifically to avoid that. In the case a warning was ever generated, then I would be aware that something went wrong, for example a permissions problem that prevented a deletion, which could be a serious issue depending on what I was deleting.
zombat
+31  A: 

Note: I (Chacha102) missed stuff! Edit it as needed.

General

  • Dabble in OOP/Classes. After you've dabbled enough, you'll probably use them in every script.

  • Session_Start should be called before any white space.

  • Use a Configuration File. This is a file that is included in the beginning of your script and sets up Constants and PHP Settings before your script runs.

  • Use Comments in Your Code. You will not remember why you did things a certain way if you come back to your code in a month. That isn't a guess either, its a guarantee.

  • Using <?php and ?> make sure your PHP code works everywhere. That is really important.

Scope

  • Understand Scope. It means that variables inside functions can't be accessed in variables outside the function.

  • The Global Scope is basically anything that isn't in a function, class, or (since PHP 5.3) namespace. If you put too many variables in the Global Scope, you end up needing long variable names to seperate everything (You might have multiple variables that hold 'file paths', and they can't all be $file_path). You'll understand this more when you get into OOP.

  • Know when Constants should be used vs. Global Variables. Constants are normally things that don't change through the entire script, and should stay ... errr.... constant. IE: Having an Array that holds your script's settings is probably a bad idea.

Reusability

  • Use functions to do code that you would normally do several times.

  • Foreach and While are your friends. They really are.

  • Seperating classes or related functions into individual files makes it much easier to transition between projects that use the same code. IE: I have a single file that contains functions for URL based activity.

Sanitization

  • Overview: Don't Trust any External Data.

  • Make sure all POST, GET, COOKIE, and all other data that is automatically generated is what you expect. If you have a 'action' variable in the URL (http://example.com?action=get), make sure that it one of the actions you are expecting. If it isn't, replace it with a default or error.

  • Sanitize POST, GET, COOKIE Data.

  • Use MySQLi->Prepare for Database Based Queries. (It makes sure the data is entered right)

Databases

  • Learn MySQL, SQL, and other database snytax if you want to deal with databases.

  • Use the proper PHP library for each database type. (MySQLi, PG, etc)

  • Some people suggest using PDO, as it works with most databases without having to change your code.

  • Use md5() to hash passwords. (You might not need it immediately, but better to use it early.)

Errors

  • Have defaults. Always.

  • Make sure to run with error_reporting(E_STRICT | E_ALL). Get rid of any errors.

  • Use if statements to check for certain things to mitigate errors. Example

     if(isset($_GET['page']))
     {
          $page = $_GET['page'];
     }
     else
     {
          $page = "default";
     }
  • Never used the @ suppressor. Just get rid of the errors. If absolutely necessary, use them very sparingly.

  • Develop a way that 'you' code (style), and stick with it. The more familiar you are with how you code, the more likely it is that you can spot your errors.

  • Learn what the error messages means. Makes debugging a whole lot easier.

Resources

And as always, There is an Ask Question button on the top of StackOverflow. Use it.

I hope that helped!

Other Things to Know

  • Mod_Rewrite: It enables you to make URL's pretty. You should know how it works and how to use $_SERVER to get the 'requested' URL (the one shown to the user), and the 'actual' URL(the file that actually runs).

  • Javascript, jQuery: These extend your program into the actual browser. Just glance over the jQuery Docs and know how to include it into your page

  • CSS: Styles the Page.

  • HTML: You should know this before writing in PHP, but because HTML is such a small part of your program, you want to make sure the HTML you are putting out is valid. It is the only thing that the browser sees, so it makes a huge difference.

Chacha102
The @ suppressor can be useful. Imagine php trying to access a file that's been removed by accident. If you don't have another nice way to catch the error, the user will get a screen full of code and error messages.
WebDevHobo
Thats why you use 'require'. Which will end the script completely, which is better considering if your app uses functions in that file, there will be a lot more errors later on.
Chacha102
@WebDevHobo: @ suppressor is not needed in your example scenario, and it also makes it very hard to solve the problem. Just turn off `display_errors` and set up an error log using `log_errors` and `error_log` settings.
too much php
I am now ... exhausted.
Chacha102
And now that the main post has gone into Community Wiki, so does my answer.
Chacha102
I would say that one should use PDO, so they don't have to learn a new library every time they want to write for a different database.
Kibbee
Added that into the **Database** section.
Chacha102
great answer, Chacha. I agree with WebDevHobo about using @ with file access. `fopen` returns false if it can't open the file, but also spits out a lot of ugly errors *(which, yes, could be hidden)*. I prefer adding my own error handling: `if ($fh = @fopen($blah))`.
nickf
I think that would better be handled by a try/catch block. You are 'trying' to open the file, if it doesn't work, 'catch' the error, and put the proper error page.
Chacha102
I believe Try/Catch would solve that, but I'm not exactly sure. I don't do much file opening besides includes.
Chacha102
A: 

Make sure you have error_reporting set to E_ALL | E_STRICT:

ini_set('error_reporting', E_ALL | E_STRICT);
too much php
+7  A: 

Here's a really helpful list of tips for beginners:

30+ PHP Best Practices for Beginners

Very thorough list, was going to type out some of the tips, but every item in that list is worth reading and applying.

Farid
+1 Agreed, that list pretty much sums up all the basic good advices newbies should follow.
Alix Axel
+1  A: 

Take a look at:

cletus
A: 

Get a good book or two on intermediate PHP. Read them cover to cover.

I recommend The PHP Anthology and PHP & MySQL Web Development All-in-One Desk Reference For Dummies

And spend a bit of time reading through the official docs at PHP.net. You'll find some really useful lesser-known functions and techniques there.

redwall_hp
A: 

Follow Chacha102's advice, especially OOP, and then learn Design Patterns, in particular -> MVC. At the end, all you have to do is to be persistent, and realize that it will take time and time... Play with programming :)

Sapphire
A: 

Use a framework. If you choose one such as Zend Framework (the one I favour and recommend), it will give you an understanding of OOP and MVC.

Understanding MVC and why it is important will give you a better idea of how and why to seperate html forms, and the PHP form handlers.

JonB