Donkeys and Elephants and Delegates,oh my!
Check out the most popular
10 Tips That Every PHP Newbie Should Know
phpbuilder.com — 10 things you (probably) didn ’t know about PHP A few obvious items in this list, but a number of gems too. Even PHP experts should take a quick look—there ...
- 1910 diggs
- digg it
- mojaam, on 10/12/2007, -3/+9Nothing noobish about that.
- bioskope, on 10/12/2007, -4/+15I concur, The authors definition of 'newbie' must be skewed or he must think of himself as an uber-god that noob to him encompasses everything else. But arrogance apart those tips were excellent
- t3soro, on 10/12/2007, -1/+3heres a nifty function to escape strings for sql queries:
function sqlesc($str) {
if(ini_get("magic_quotes_gpc")) $str = stripslashes($str);
return mysql_real_escape_string($str);
} - shadus, on 10/12/2007, -2/+13The tips were excellent ... however, that being said.
Real newbie tip:
Be careful with your php and mysql or you're opening yourself to several well known and practiced attacks that have been repeated across about 80% of the php software out there dozens of times.
PHP is a powerful language and its an easy language, thats a rough combo because it can yield some very very insecure code that does exactly what it should but enables a lot of outside tampering.
Outside of an intranet, php newbies shouldn't be authoring code for large scale web apps. - gcnaddict, on 10/12/2007, -3/+12everyone bury diggmirrors down when he posts here. Go flag his blog too. He'll do it once this reaches the front page.
- ExposeIT, on 10/12/2007, -24/+1Hey check out this mirror!
http://www.duggmirror.com
LOLTHErMITE IT ReALLY HAPPENEDDDD 9/11 WAS A CONSPIRACY OMFG. - mroo, on 10/12/2007, -13/+4This is NEWBIE level stuff, it covers extreme basics like input validation, how to use a procedural language. It doesn't get much more newbie than this.
On a more positive note, can conceptually apply to any procedural language.
Secondly, the database tip is pointless, it creates a new connection for every '$db = new db'; - tagawa, on 10/12/2007, -0/+8Part 2:
http://www.phpbuilder.com/columns/vaska20050812.php3 - mroo, on 10/12/2007, -3/+6@bioscope: You are obviously not a programmer, I think your character assasination of the author is unwarrented.
He certianly doesnt come across as an 'uber-god' ( as you put it).
If input validation and 'how to use a function' are not generic procedural programming newbie tips, then I dont know what is. I mean this is the kinda stuff you learn in the first chapter of 'php in 30 days for non-programmers'. - PARAPA, on 10/12/2007, -2/+7@mroo
Quote:
"This is NEWBIE level stuff, it covers extreme basics like input validation, how to use a procedural language. It doesn't get much more newbie than this."
What about:
echo "hello world";
??? - dAbReAkA, on 10/12/2007, -0/+4newbies working with classes.. lol..
- ecb29, on 10/12/2007, -1/+1I once was curious about what the digits on a credit card meant, so I wrote a script to do the Luhn check, decode the industry type and card types, as well as attempt to match the BIN (bank ID number): http://credit-card-information.elliottback.com/?number=5105105105105100 . Here's a sample.
- ecb29, on 10/12/2007, -2/+1I once was curious about what the digits on a credit card meant, so I wrote a script to do the Luhn check, decode the industry type and card types, as well as attempt to match the BIN (bank ID number): http://credit-card-information.elliottback.com/?number=5105105105105100 . Here's a sample.
- trghpy, on 10/12/2007, -9/+5I guess newbie means someone who can't read help documents.
- bdurkin, on 10/12/2007, -1/+5he actually states that everything that he wrote came from the manual or the php builder website.
- kb0x, on 10/12/2007, -1/+2So what was that you were saying about people not being able to read trghpy?
- gmprunner, on 10/12/2007, -3/+3"10 Tips That Every PHP Newbie Should Know"
That's me!- aclements, on 10/12/2007, -0/+4AOL!
Oh, wait, no one knows what that means in the pejorative anymore...
http://catb.org/esr/jargon/html/A/AOL-.html
- aclements, on 10/12/2007, -0/+4AOL!
- jalenack, on 10/12/2007, -0/+13One nitpicky thing:
function escapeString($post) {
if (function_exists('mysql_real_escape_string'))
return array_map('mysql_real_escape_string',$post);
else
return array_map('mysql_escape_string',$post);
}
Use the direct function_exists() as opposed to roundabout version checking. - gharding, on 10/12/2007, -0/+2In regards to the first tips, if all you're going to put in a class is a constructor, just make it a function.. it's much more efficient.
Another useful debugging snipper: http://us2.php.net/manual/en/control-structures.declare.php#control-structures.declare.ticks
And in the author's magicQuotes function, why return nothing if mq is on? How about returning $post as-is.- mroo, on 10/12/2007, -0/+0I agree, also using a static inside the function to implement the singleton pattern would be advantageous to reduce db overhead as well.
- mroo, on 10/12/2007, -0/+0I agree, also using a static inside the function to implement the singleton pattern would be advantageous to reduce db overhead as well.
- 8086ed, on 10/12/2007, -0/+12Is that seriously a 2 part top 10 list? WTF?
- toast1226, on 10/12/2007, -4/+2I agree.
- kb0x, on 10/12/2007, -6/+2You agree with a question?
- drepmoreh, on 10/12/2007, -0/+2Heads up kb0x!
http://en.wikipedia.org/wiki/Rhetorical_question
- joevill, on 10/12/2007, -1/+1Awesom-O! I need to learn as much as I can !
- chrisxkelley, on 10/12/2007, -1/+7I really dont like any of that code. I do a lot of php and the code uses a lot of techniques that will work fine at a small level, but really arent that great when building larger applictions...
Especially the first one- If you're going to make a DB class or similar, it's really better to just put it all into a global file where you hold all config stuff and just have htaccess auto prepend the global file to all of your pages.- bdurkin, on 10/12/2007, -0/+1Agreed but I think the points he was making were the important part. I think the tips were good but the code could be better.
- dankosaur, on 10/12/2007, -0/+7include("db.inc.php");
- slasherx, on 10/12/2007, -2/+6First off, that's only 5 tips. Sounds as if the submitter didn't bother to read the article. Second, those tips are pretty lame. The debugging one is default in php recommended ini file. The database tip is foolish too since it's not a real database class. You'd be better off using Pear DB as opposed to some cheesy object that gives you nothing an include won't work. Burried as lame.
- sagy, on 10/12/2007, -2/+0Great!
- chapium, on 10/12/2007, -0/+2$db = new $DB ?
Thats gotta be confusing in the long run.- cozinator, on 10/12/2007, -0/+9It also produces a fatal error for attempting to instantiate a non-existent class. It should be:
$db = new DB; - tobyjoe, on 10/12/2007, -0/+1Those connection values should be injected, as well. It's bad form to include those values in a class definition.
- cozinator, on 10/12/2007, -0/+9It also produces a fatal error for attempting to instantiate a non-existent class. It should be:
- DonWilson, on 10/12/2007, -1/+2Not too bad of an article. I didn't know about array_map() and I use error_reporting(E_ALL) always when I'm developing.
- micsco, on 10/12/2007, -3/+2What a waste of time. Those 5 tips, while good, are covered by many many other websites. A simple google search is more informative than that traffic-whoring website.
Whats more is they say to come back for part two, it was created in 2005! wtf... - icexe, on 10/12/2007, -0/+3forget all that magic_quotes and strip slashes crap and use prepared statements instead.
- jmjjg, on 10/12/2007, -0/+1I second that: use PDO ( http://www.php.net/pdo/ ), which is PHP standard response to tips 1 and 3 (if you can use PHP 5.1, or at least PHP 5.0 and PECL).
- BrainInAJar, on 10/12/2007, -6/+3numbers 1 through 10.
Stop what you're doing right now, and go learn J2EE or Ruby or .net . You may think PHP is good now, and it is.... but if you start scaling it up you'll cause more headaches than if you had just taken the little bit of extra time to write it in a more complicated & robust language- mroo, on 10/12/2007, -2/+2I dont see how ruby / .net or Java, C++ / C / perl are any better than php? They all have there place.
( Well.. if we ignore the lack of object-oriented features in php4 and the lack of late static binding in php5 ).
You can write bad programs in any language.
You can use a good framework in any language, then write bad programs with it too. - tybris, on 10/12/2007, -2/+4Higher performance, better security, more tools, more libraries, better application models, bigger communities, less volatile technology, proven technology, more platform-independent, lots of other things. I dropped PHP completely, except for very simple tasks, and got myself a Tomcat server. I'm now developing web applications much faster than ever with much higher quality.
- tybris, on 10/12/2007, -3/+4P.S. No, PHP doesn't have a place. I've been working with it for 5 years. You will start hating it sooner or later. Hopefully sooner, otherwise you'll have to hate it even more.
- mroo, on 10/12/2007, -2/+2I dont see how ruby / .net or Java, C++ / C / perl are any better than php? They all have there place.
- kday, on 10/12/2007, -0/+6***** all that code and functions. Get yourself a rapid development model, view, controller based framework such as CakePHP.
http://www.cakephp.org/
If you are familiar with Ruby on Rails, you will have no problem picking up CakePHP. CakePHP is the PHP clone of RoR. I prefer CakePHP over RoR because just about any host is compatible with it, and installing/configuring RoR + Fast CGI can be a real pain in the ass.- tobyjoe, on 10/12/2007, -0/+1FCGI? I know the Rails world evolves quickly, but FCGI is NOT the way to go these days. There are far better options out there. I prefer nginx + mongrel, personally.
- knugen, on 10/12/2007, -0/+2Also, you can (often) set PHP flags in .htaccess-files on Apache; this lets you you disable magic_quotes to avoid the overhead of adding/stripping slashes.
Just add this to your .htaccess file:
php_flag magic_quotes_gpc off
And addslashes aren't even safe, everyone should know this: http://shiflett.org/archive/184 - ellisgl, on 10/12/2007, -0/+2I only see five tips on this page.. Oh there's a part 2 - where is it..
Why don't they give them tips about single quotes vs double quotes and when to use them. Also my favorite $i++ which I have seen in a bunch of books and tutorials should be ++$i.. I've done the tests and have found out that later is much faster. This is only for PHP thou from my reading.
There's a lot for newbs to know. Don't make your variable to long, don't make them too short (the later rule can be bent). Make the code readable.. While it may run - but if someone cant read it and it takes time to parse it out then it's not good.
I.E. (I know I'm going to get ***** for the way I parse)
If you do the following:
function myfunction() {
(tab)stuff here...
}
I can follow it - but what I do is:
function myfunction()
.{
..stuff here
.}
the periods are for spaces..- tagawa, on 10/12/2007, -0/+1Part 2 is here:
http://www.phpbuilder.com/columns/vaska20050812.php3
(also posted above for the scroll-wheel challenged) - dankosaur, on 10/12/2007, -0/+1you're really airing your dirty laundry here, ellisgl
- mroo, on 10/12/2007, -0/+5Coding style is usually dependent on the project!
The reason why you do NOT use ++$i instead of $i++ is because they do two different things.
One passes in the value of the variable first and then increments, the other increments the variable then passes the value.
- tagawa, on 10/12/2007, -0/+1Part 2 is here:
- randomguru, on 10/12/2007, -0/+1nice tips for newbies. though the db connect class could utilize another function to close the database. it's not necessary to close a database, but it's good practice (to avoid too many open connections), especially when handling larger web apps in PHP and MySQL, and also when working with more than 1 database.
- d3faultnet, on 10/12/2007, -0/+1i suggest you learn how to count to 10 before learning how to code php. yea, there's only 5.
I understood everything in this article (I read it because it said even experts may learn something, which i did not)... and I have to say, it was very poorly written. It doesn't really explain anything very well... It assumes the "PHP Newbie" knows all sorts of terminology from the get go. - kingkong118, on 10/12/2007, -0/+1thats not exatly new information.. lol, also the article was like 2 years old, and there was some errors... NOT DIGGED :)
- netferret, on 10/12/2007, -3/+3NOTE TO SELF: Never use php as when they make changes the language structure and everyhting that previously worked will need to be changed/updated. This will piss my clients up and will lose me money.
NOTE TO SELF 2 : Never forget the first note!
NOTE TO SELF 3: People who love php will now digg this down.- tybris, on 10/12/2007, -3/+4That was going to be my tip.
I've developed PHP applications for quite a few years, but finally came to the realization that it was the worst invention in the history of computing.
Never try to build web applications with PHP. It is not designed for that (or they failed at it) and it will only disappoint you.
If you're serious, get a Tomcat server.
If you feel like living on the edge, try Ruby. - jspegele, on 10/12/2007, -0/+1web applications like, say, i don't know . . . digg?
- tybris, on 10/12/2007, -3/+4That was going to be my tip.
- ryanonfire, on 10/12/2007, -7/+1what is PHP?
- flump, on 10/12/2007, -0/+2If you're going to the effort of using a class to set up your database connection, why not make it so you can use $result = $db->query('SELECT * FROM table') so in the future you can change your whole DBMS if you need to, or simple use a function instead of a class in the case provided. Also that makePrefix() function would be better suited to a switch statement rather than using IFs.
- Saiing, on 10/12/2007, -0/+2A few comments. I just read the first part. Haven't been through the rest yet.
1. The database connector class doesn't use mysqli which is vastly superior to the old set of mysql functions. Not sure why he chose to do this.
2. Do it his way and you're exposing your database to serious attack as you're showing both your database username and password in a publically accessible file. This kind of information should at the very least be held outside of the web tree.
3. His code would be a lot more standard, and readable if he defined his class variables at the top of the class using: var $var_name; While this isn't strictly necessary it's good practice and is something I'd expect to see in a "newbie" guide.
4. In his SQL query "ASC" isn't strictly necessary as it's the default, but there's no problem with putting it in for clarity's sake.
5. If you ever actually build a PHP/MySQL site, you're almost certainly going to need to use prepared statements. His method of building a simple query, while obviously easy for beginners, isn't really going to serve you well in the long run.
This guide seems to be caught between stuff that is too difficult for absolute beginners to be able to read straight off, and too simple and misleading for those with a little PHP knowledge. My honest advice would be, learn mysqli from the beginning. Learn how to do prepared statements early on - they're pretty much as straightforward, but so much more secure than other methods, even if you filter your user input.
One more thing. I can't agree at all with tybris in this comments section. PHP is a great language for beginners and seasoned programmers alike. He seems to be spouting a lot of puff to big himself up and sound knowledgeable, but hasn't said anything of any value yet. Half of his comments are factually incorrect and the others are irrelevant to the uses that PHP is designed for. - Saiing, on 10/12/2007, -3/+1Error - digg this down
- coditza, on 10/12/2007, -0/+2"An easy way to describe classes is to think of it as a collection of functions that work together." what?
Down for lameness- coditza, on 10/12/2007, -0/+2not to mention that article is OOOOOOOOOLD
- nwkeeley, on 10/12/2007, -0/+3for all you that use print_r($result) try wrapping it in PRE tags..... makes it so much easier to read / debug
- Negligence, on 10/12/2007, -0/+5Absolutely terrible guide for a newbie. This is the best way to teach wrong practices. Two things with the first point and I digress:
1) He doesn't accomplish anything with the DB class other than establishing a connection. A class is not necessary for something as simplistic as this. At least he could of expanded it to include other database engines.
2) He uses mysql_query(). He should revise tip #1 and show a database abstraction class so a newbie isn't locking himself into MySQL as the database engine. Think future, not present. What's the problem with programming using mysql_query()? Well, what happens if you want to change to Postgre? Imagine all the code changes. This is a big problem in PHP web development.
We have uneducated and unexperienced people acting as mentors (the author here) to new programmers, who are also uneducated and unexperienced and can't discern between right and wrong. Dugg down for being an example of what not to show a newbie.
Seriously, it's no kidding that PHP has the reputation it does. Anyone who believes these are excellent tips is headed down the wrong path, and I urge you to learn elsewhere.- DavidDigg, on 10/12/2007, -0/+1This is a good point, but I think it is a common problem --- experienced people for any given programming language are hard to come by. I have found Code Complete by Steve McConnell to be very useful in distilling a huge amount of experience into practical guidelines. It is not specific to PHP, but it will give you a basic foundation in software construction for any language.
- volscio, on 10/12/2007, -0/+3Someone revise the tips with correct code, please -- it would be useful instead of just pointing out its flaws.
- arctic, on 10/12/2007, -1/+1I think the author is a noob, he thinks 10 == 5
- jspegele, on 10/12/2007, -0/+1I think you didn't read the last sentance . . . check back for part 2
- echoic, on 10/12/2007, -6/+211. They're not really programmers and will never get a real job.
- nwkeeley, on 10/12/2007, -0/+2Your saying PHP programmers are not really programmers? And will never get a job? Hm.... I wonder how digg works, must have been thrown together by a bunch of unemployed non-programmers.. Dugg down for idiocy.
- tylerman, on 10/12/2007, -1/+2wish it had stuff on updating the database :-/
- LiquidPenguin, on 10/12/2007, -0/+1Why isn't the most critical tip of all in there? RTFM.
Many many times I've audited PHP code prior to a site launch and discovered not only some of the problems this article points out (as well as many others the article does not), but some really shoddy code because the author had no idea about the existence of a particular function. I've condensed as many as 30 or more lines of code into two or three using some of the intrinsic functions available in PHP.
Reading and understanding at least the PHP reference guide is critical. Often more so than many other languages due to PHP's inconsistent naming conventions. PHP is not one of my primary languages and yet I still find myself writing better code than many of the "experts" who write some of the most oft used PHP applications out there. - JonLatane, on 10/12/2007, -0/+2A more important tip, for security and peace of mind, is to make ABSOLUTELY SURE register_globals is turned off. This directive, essentially, lets users initialize global variables as they request the page, and so if as a coder you don't initialize (for example) a variable that determines whether the user is an administrator, then they can just say they are and take all administrator actions.
To do this on Apache servers, add "php_flag register_globals off" to your .htaccess file. For other servers, as far as I know, you're SOL and will have to recompile to disable it. Or, just upgrade to >=PHP 4.2.0. If you are a programmer that relies upon the "magic" of register globals, BREAK THE HABIT. Additionally, a good security practice is to use $_POST, $_REQUEST, $_COOKIES and $_GET only for managing the initialization of other global variables rather than relying upon them multiple times in the scope of your application. - tomarocco, on 10/12/2007, -1/+1Regarding his 5th tip: Good programming practice is to have only one return point from a function/method. It would have been better to have assigned each item to a variable and return that variable once at the end of the function.
function makePrefix($prefix='')
{
$x = '';
if (!$prefix) $x = '';
if ($prefix == 1) $x = 'Mrs. ';
if ($prefix == 2) $x = 'Ms. ';
if ($prefix == 3) $x = 'Mr. ';
return $x;
}- tobyjoe, on 10/12/2007, -0/+1Your example function is wasteful. It evaluates every possible condition, even comparing '' against those values.
- DonWilson, on 10/12/2007, -2/+2I like how everyone tries to show off their super cool PHP knowledge, as if most of us don't know anything about PHP =P
- kenmantx, on 10/12/2007, -0/+1Here's a sample function for you:
< ?php
$tipsAdvertised = 10;
$tipsActual = 5;
echo compareItems($tipsAdvertised,$tipsActual);
function compareItems ($reportedItems, $actualItems)
{
if ($reportedItems !== $actualItems)
{
return 'Buried as Inaccurate.';
}
return 'Dugg.';
}
?> - kenmantx, on 10/12/2007, -0/+1I also find it humorous that he says this is bad practice, because this format is actually sometimes much easier to deal with:
var = "This is the $value of things."; // ok, but harder to read/debug
However, this is how he says the ternary operator should be used:
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
Which is actually poor because it is redundant. This is better:
$action = empty($_POST['action']) ? 'default' : $_POST['action']; - imatard, on 10/12/2007, -0/+1Only on digg can a two year old and clearly wrong tutorial get such fanfare.
PHP is written for two reasons that are adopted from Perl
Make difficult things easier,
Keep easy things easy.
PHP is grand in that it pulls both of these off in a very similar method to Perl.
Anyone who says otherwise doesn't know how to make PHP do its Pirouettes.
Browsing Digg on your phone just got easier with our enhancements to the