Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

These Things I Know, PHP Tips

Rated 2.59 (Ratings: 11) (Add your rating)

Log in to add a comment
(31 comments so far)

Want more?

  • More articles in Code
  • More articles by 53x11
 
Picture of 53x11

Nick Schaffner

Member info | Full bio

User since: September 06, 2005

Last login: December 28, 2005

Articles written: 1

There is more than one way to achieve the same result when programming in PHP. There are many shortcuts I wish someone had explained to me when I began learning the language. (One would assume that is what those $49.99 books are for, but apparently there are only written to bewilder the reader into buying another book.)

It All Adds Up

$variable = $variable + 1;

Is the same as:

$variable ++;

This method also works for subtraction:

$variable --;

You can also apply a similar method for concocting strings. So instead of:

$mytext = 'Done and Done.';
$mytext = "$mytext And I mean Done!"; // $mytext = 'Done and Done And I mean Done!';

Use this shorthand method of adding another string of text onto the end of the first string:

$mytext = 'Done and Done.';
$mytext .= ' And I mean Done!'; // $mytext = 'Done and Done And I mean Done!';

Single Quotes versus Double Quotes


Any time you put something in "double" quotes, you are asking PHP to check that content for a variable. So even though the following lines do not contain variables within the double quotes, PHP will still waste precious computing time scanning them anyway.

$mytext = "Dental Plan";
if ($mytext == "Dental Plan") {
echo "Lisa needs braces"; }

Those same three lines of code could be executed much faster if 'single' quotes were used in place of "double" quotes.

$mytext = 'Dental Plan';
if ($mytext == 'Dental Plan') {
echo 'Lisa needs braces'; }

Now that may not seem like much, but having PHP check for variables where it doesn't need to over the course of a larger script, can certainly impede run-time. Just to clarify my point, PHP will not read a variable if it is within 'single' quotes.

echo '$mytext, Lisa needs braces.';
// Will output: $mytext, Lisa needs braces.
echo "$mytext, Lisa needs braces.";
// Will output: Dental Plan, Lisa needs braces.

What is the the super-secret of keeping those scripts speeding along the rusty pipes of your server? Avoid double quotes at all costs. Even if you are working with a variable and think you need double quotes, it is more efficient for PHP to execute this:

echo $mytext . 'Lisa needs braces.';

As opposed to this bit of molasses-like code:

echo "$mytext Lisa needs braces.";

One control structure to rule them all, One constant to find them, One set of conditional brackets to bring them all and in the darkness bind them


Not anymore! If you have a single expression following a control structure, you do not need to waste your time with brackets { }.

if ($gollum == 'halfling') {
$height --;
}

Is the same as:

if ($gollum == 'halfling') $height --;

This can be applied to any control structure statement. For example:

if ($gollum == 'halfling') $height --;
else $height ++;

if ($frodo != 'dead')
echo 'Gosh darnit, roll again Sauron';

foreach ($kill as $count)
echo 'Legolas strikes again, that makes' . $count . 'for me!';

The fewer brackets you have cluttering up your code, the easier it may be to read.

They true did false, they were the trueiest bunch of falses that ever trued

If all you are trying to test for is a boolean (true/false) of a variable or function then instead of laying down a bunch of code like this:

if ($blackbeard == true) echo 'Arr, this chair be high, says I.';
elseif ($seacaptain == false) echo 'Yar, I'm not attractive.';

You can omit == and != with:

if ($blackbeard) echo 'Arr, this chair be high, says I.';
elseif (!$seacaptain) echo 'Yar, I'm not attractive.';

This same format can apply to functions and multiple conditions. For example:

if ($benedict_arnold != true && strpos($photo,'map') == true)
echo 'You idiot, you can't read!';

if (high_chair($blackbeard) == false)
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

The following is the same exact statement (except with less code):

if (!$benedict_arnold && strpos($photo,'map'))
echo 'You idiot, you can't read!';

if (!high_chair($blackbeard))
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

In and out of PHP before they even knew what hit 'em

When embedding PHP within HTML, you can close your PHP tag whenever you want to output HTML. This enables speedier processing of your PHP. For instance:

<?php if($bush_sewer) { ?>

<div class='neighbor'>
<strong>Hey Turkeys! Behind ya!</strong>
</div>

<?php } elseif (street($gorbachev)) { ?>

<div class='russian'>
<i>I just drop by with present for warming of house, instead find you grappling with <?php echo $local_oaf ?></i>
</div>

<?php

}

$name = 'Stu';
echo 'Disco' . $name . 'doesn't advertise...'; ?>

Hopefully that last one didn't confuse you as much it confused me, the example is a bit extreme. However look over it a few times and you will understand exactly what is going on.

A few more for the road...

  1. Don't use spaces to format your code, use tabs. Every space takes up 1 byte, every tab takes up 1 byte too. So if you are using 4 spaces to make 1 tab, you will have added unnecessary bulk (and CPU time) to your code.
  2. Learn Regular Expressions, which are beyond the scope of this article. However once mastered, you will transform into an unstoppable coder of such power that even your own expertise of regular expressions cannot calculate your might.
  3. If you are dealing with external variables through get/post. Always use $_POST['variable'] or $_GET['variable']. Assuming $variable can open a huge security hole into your script. With the upgrade to PHP5, register_globals is turned off, by default - so scripts will be forced to use the above method.

    Here is a code snippet to quickly gather $_GET and $_POST variables:

    // $_POST['form_name'] = 'Anus Mcgee';

    foreach ($_POST as $key => $value)
    $$key = $value;

    // Now $form_name = 'Anus Mcgee';

PHP Links and Resources

Hopefully a few of the examples I have demonstrated have made you hit yourself on the head and say - "I wish I had known that before!" I think each one had that effect on me.

Nick got hooked into the whole web fad back in the summer of 99'. Come snow-fall, he had his own domain name and a firm grasp of HTML. It all just kind of snowballed from there as the content and complexity on his first site began to multiply. By the winter of 2000 he was sick of the internet. Nick wasn't on the web to write articles and feed substance to the masses. He was there to offend people, make neat shit, and look at porn.

Nick maintains a weblog about bikes, music and bullshit: 53x11.com

another tip:

Submitted by jadwigo on November 2, 2005 - 17:30.

another tip:

if you need to output a lot of small strings, first make them into one string.

<?php
echo 'string one';
echo
'string two';
echo
'string three';
echo
'string four';
echo
'string five';
?>

is much slower than

<?php
$output
= 'string one';
$output .= 'string two';
$output .= 'string three';
$output .= 'string four';
$output .= 'string five';
echo
$output;
?>

Though I prefer the print() and printf() functions over echo.

One negative mark about strings enclosed in single quotes is that you cannot use special control characters like \n, \r and \t inside them, if you want to format your code / output an email body you'll need a string enclosed in double quotes. I never noticed any speed difference, and vaguely remember someone actually testing the speed difference who found the impact negligable.

login or register to post comments

Brackets make code easier to read, for me at least

Submitted by jtnt on November 2, 2005 - 17:53.

I disagree with your statement: "The fewer brackets you have cluttering up your code, the easier it may be to read."

I use the brackets to MAKE my code easier to read. They are visual breaks that allow me to scan the code quickly to see where blocks of code stop and start.

Good tips, though, overall, particularly for beginners, I'd think.

login or register to post comments

Brackets make code easier to read, for me at least

Submitted by jtnt on November 2, 2005 - 17:55.

I disagree with your statement: "The fewer brackets you have cluttering up your code, the easier it may be to read."

I use the brackets to MAKE my code easier to read. They are visual breaks that allow me to scan the code quickly to see where blocks of code stop and start.

Good tips, though, overall, particularly for beginners, I'd think.

login or register to post comments

curly braces, etc

Submitted by pjohanneson on November 2, 2005 - 21:56.

I always use curly braces* around my if() and foreach() and etc loops. I find that it's all well and good to leave them off in the heat of coding, but it's a lot easier to read six months later if you've got the {'s and }'s to guide your eye.

I like the $$key = $value trick; I'll have to use that one.

And lastly, let me just say, thank you for using the Simpsons as your examples. Made me smile.

login or register to post comments

Concatenation Rules!

Submitted by mgirouard on November 2, 2005 - 23:24.

You could also do something like the following, but it won't be as readable:
<?php
$message
= "Greetings $user, \n\n"
    
."We have noticed an irregular ammount of activity on your \n"
    
."account so we have taken the liberty to close it permanently\n"
    
."and taking all your assets.\n\n"
    
."Hope you don't mind!\n\n"
    
."Sincerely, "
    
."Your Bank ";
?>

login or register to post comments

Not great for security

Submitted by macgruder on November 3, 2005 - 03:18.

In one for the road 3, it's suggested that you use:
<?php
foreach ($_GET as $key => $value) //$_POST in the actual example
$$key = $value;
?>
to gather the variables. This is effectively the same as turning register_globals on defeating the purpose of keeping them off in the first place, as now a visitor can send any variable they want by popping it into the the URL or HTML. /mypage.php?admin=1

Will now mean admin = 1 runs through the script. I prefer to avoid the above for each altogether or limit the loop to known variables. The nice thing about keeping $_GET and $_POST within your script is that it makes debugging very easy as you can spot immediately what they are.

Of course, the above is not a security flaw per se, but it does mean that a security flaw is much more easily introduced as keeping track of the impact of the ability of the user to set ANY variable themselves can be tricky.

login or register to post comments

Quick if else statement

Submitted by jish on November 3, 2005 - 22:08.

Here is the syntax of a "normal" if-else statement:

<?php
    
if( $color == 'green' ) {
        echo
'Green';
    } else {
        echo
'Not Green';
    }
?>

This statement will do the exact same thing.

<?php
    
echo ( $color == 'green' ) ? 'Green' : 'Not Green';
?>

login or register to post comments

This hint is helpful

Submitted by llbbl on November 4, 2005 - 23:36.

Not great for security

Submitted by macgruder on November 3, 2005 - 03:18.

You shouldn't be using the code you mentioned to check to see if someone is a admin user or not. That is something you should do with sessions.

So to anyone reading this, don't believe what this guy is saying because he is using the example in the wrong way for what it is intended. The hint is very helpful!!

Take this phpbuider page for an example.

http://www.phpbuilder.com/columns/index.php3?cat=1&subcat=28

Using that code you can extract that $cat=1 and $subcat=28. This is very handy for getting certain pages to display the data you want it to.

Of course don't anything stupid and pass username and password info in your URL. Like I said before, this is something sessions should be doing.

login or register to post comments

An even easier option is

Submitted by Daeg on November 5, 2005 - 02:50.

An even easier option is using Heredoc output.

login or register to post comments

It isn't great for security, it could be downright bad for it.

Submitted by Nilloc on November 7, 2005 - 18:16.

<?php
foreach ($_GET as $key => $value) //$_POST in the actual example
$$key = $value;
?>

He may have used a bad example with the admin=1 bit, but it could be a security flaw whether you are using sessions or not. With a lucky guess, any variable that is set in the script could be changed by anyone.

Also he wasn't saying to get rid of "http://www.phpbuilder.com/columns/index.php3?cat=1&subcat=28" links, he--and I--are just advocating control over what variables can be retrieved from the URL.

login or register to post comments

A better way to confirm conditionals...

Submitted by eli on November 7, 2005 - 18:57.

In order to avoid errors that may be hard to find when writing a conditional conside using the following method;
if("foo" == $myString){
   echo $myString . " is my string\n";
} else {
   echo $myString . " is not my string\n";
}
By placing the value first you avoid a couple of problems, one being variable reassignment, consider;
if($myString = "foo")
$myString now is equal to "foo" and is TRUE no matter what. Another problem is improper comparison operators get located quickly;
if("foo" = $myString)
will throw an error immediately and lead you to see that you have used an assignement operator instead of a comparison operator.

login or register to post comments

Multi-line assignment

Submitted by Douglas Clifton on November 7, 2005 - 20:19.

Another method of assigning multiple lines of text to a string variable is to use heredoc syntax:
<?php
$vars
= 'variables';

$paragraph = <<<PARA
This is a multi-line assignment.
Newlines are preserved, and
$vars are interpolated.
PARA;

print
$paragraph;
?>
This is a multi-line assignment.
Newlines are preserved, and
variables are interpolated.
More PHP Resources: drx: PHP.

login or register to post comments

Still not good for security

Submitted by macgruder on November 8, 2005 - 12:12.

libbl, you are totally missing the point.

The example was a deliberately simple one. Furthermore, the admin=1 in the URL was precisely NOT the logging system. That's the whole point. $admin is a variable strictly within the script, but with the 'hint' as it stand you can manipulate ANY variable in the script through GET/POST.

How about this example:

$query = "delete from table where username = '$username';

with $username only occurring in the script.

(simplified and unencoded for explanation purposes). now do:

x.php?username=x' or username !='

This will mean the above $query will be:

delete from table where username = 'x' or username !='';

deleting all the table entries.

Of course, you can write your code to combat the above as well, but you are opening yourself up for all manner of SQL injections if you apply the above hint, and if one of them slips through you are screwed.

llbbl, don't give 'security advice' when you are not aware of the implications of what you are saying.

login or register to post comments

Security...

Submitted by 53x11 on November 10, 2005 - 06:52.

Unfortunately, even with register_globals turned off - anyone can easily inject their own $GET and $POST variables into PHP scripts. While it was beyond the scope of this article, the only way to truly secure any variable is to validate it. Writing extra code to inspect/modify/correct sensitive variables can add a significant amount of work to any script, but it is much safer than relying on "register_globals" to cover your ass. Thanks for the comments!

login or register to post comments

foreach ($_POST as $key => $value); $key = $value;

Submitted by webinista on November 10, 2005 - 18:16.

Well, at least one person points out that using foreach ($_POST as $key => $value); $key = $value; kind of undermines the whole point of using $_POST in the first place.

But validation is key.

login or register to post comments

Security

Submitted by macgruder on November 16, 2005 - 04:49.

"Unfortunately, even with register_globals turned off - anyone can easily inject their own $GET and $POST variables into PHP scripts"

Yes, that's true, but they are still limited to only those variables that occur as $_GET/$_POST within the script. By looping, you are making your script that every *possible* variable has to be validated. This significantly raises the chance of something slipping through that you don't notice.

"Writing extra code to inspect/modify/correct sensitive variables can add a significant amount of work to any script, but it is much safer than relying on "register_globals" to cover your ass."

Yes, but that's precisely the point. The longest time is spent debugging and writing this extra code, and that's where avoiding this loop saves you time. Search your script top to bottom and look for $_POST $_GET etc. and make sure that each occurence is harmless. $age = intval($_POST['age']);

With your loop you have to check every variable everywhere, and you can't search either. A script might have dozens of variables but only 2 or 3 occurences of $_POST, $_GET.

login or register to post comments

JavaScript, too

Submitted by DanteCubed on November 16, 2005 - 04:54.

The tips about the boolean operators and no brackets for if/else statements apply to JavaScript as well as PHP.

Good article.

login or register to post comments

These tips mean well, but will cause headaches in the future

Submitted by corephp on November 16, 2005 - 08:18.

I was asked to post my overview of these tips here, but I notice now that someone has already posted a link to my blog entry commenting on these tips. However I thought it only fair I show my face, especially as it's not just me who thinks this way. Views from Chris Shiflett, Chris Cornutt, and even on the Pro PHP Podcast, all reflect the main sentiment of my article: that while good in their intentions, these tips will cause more problems than they are worth in the long run. There is nothing personal about my comments, they are directed at the PHP tips, not the author.

login or register to post comments

Thanks eli for reversed conditionals order tip

Submitted by thatscriptguy on November 22, 2005 - 11:17.

Thanks for the tip eli - I never thought of reversing the order of items inside an 'if' - I'm usually pretty good at remembering the two ='s, but typos do happen! Will add this to my arsenal :)

For more from David (That Script Guy), visit PHP Tips and Tricks

login or register to post comments

Brackets and Booleans

Submitted by johnlwd on November 24, 2005 - 00:27.

--- Brackets ---

Not only to curly braces make if statements easier to read, they will also ensure that the code nevers 'falls through'.
consider the following:

<?php
if ($something == true)
   
$blah = doSomething();

$done = true
?>

At this point it is extremely hard to tell wether the last assignment is part of the if statement or part of the code that follows. whereas:

<?php
if ($something == true) {
   
$blah = doSomething();
}
$done = true
?>

ensures that anyone who reads the code will be able to tell exactly what is executed when and where, and certainly makes debugging a lot easier.

Another nice reason to use brackets is the editors and IDE's that are around now will have bracket-highlighting, which helps immensely when browsing through large constructs.

--- Booleans ---

replacing the == and/or != in if statements when testing for boolean evaluation is fine, but you might also want to consider that one might write a function that returns an integer, and as we all know when you test

<?php
  
if(getNumber()) { // get a number and check its not false
?>

it will evaluate to false when the number returned is 0 ... and because that number might actually be a value we want to have evaluated as true, we should do the following comparison:

<?php
  
if (getNumber() !== false) {
?>

here we use the comparison operator with an extra '=' to make the comparison explicit. This will ensure that the value is checked for a boolean false (or true) only, integers such as 0, 1, 2302 will not evaluate in these comparisons.

login or register to post comments

You lose.

Submitted by amiller on December 3, 2005 - 19:27.

Whatta load. People have been arguing single-vs.-double-quotes and preincrement-vs.-postincrement since before I started hacking, and the whole argument's been nothing but an exercise in intellectual wankery since about 1998 -- one might cost more than the other, but it takes timing a loop that runs ten million iterations to see which is faster, and even then it's not conclusive -- why bother? I'm not going to get into a stylistic argument, mind; I'm just saying that on the performance front it doesn't make enough difference to be worth caring about.

I've never in my life seen a script, in any language, where either of those counted one way or the other toward performance, for or against. I have, on the other hand, seen in my working life quite a large number of scripts where a little basic, simple intelligence, of the sort that says 'perhaps foreach()ing across the same ten-thousand-element array four times in a row is not very efficient', would've gone a hell of a long way. If you're going to advise people on how to improve the performance of their scripts, I suggest you skip the quoting holy war and talk about something that will actually help, such as understanding data structures and how they can be used to avoid iterating over the same array more than once.

While I'm on the subject of foreach() and its ilk, I would add that I wasn't pleased in the slightest to find that PHP permits lazy-assed-programmer shortcuts like single-statement blocks without braces; that's been execrable style since ANSI C, and people've been rightly complaining about it for just about that long.

Don't even get me started with the foreach($_POST as $key=>$value) { $$key = $value } thing. If you want register_globals enabled, and the massive security cornholing which is almost sure to follow in short order, you know where to find it -- as I see you do, and assert that it should be disabled for security reasons. You're right, of course, but what boggles me is the way you say that and then turn around and suggest doing something that's not only at least as insecure but is also much slower. It's almost enough to make one consider that you don't really know what you're talking about.

Besides, while we're talking performance issues, how much do you think a symbolic reference like '$$key' costs compared to a simple array lookup like $_POST['key']? Hint: Arrays are optimized for speed, while symbolic references involve the equivalent of an eval() call, which is just about the slowest single function you can call in PHP.

Arguing that tabs beat spaces because they cost fewer bytes is just silly, unless you're serving pages from hardware so old it'd burst into flame just thinking about running PHP, plugged into pipes narrower than my old granny's 14.4 dialup. If you're that worried about slow transfers, get rid of a couple of images; there are usually plenty to choose from, most of them there only to stroke the unjustified ego of a 'designer', whatever the hell that is. That'll save you a lot more bytes than converting space indentation to tabs.

It's true that regular expressions, once mastered, are an incredibly powerful tool. Unfortunately, that 'once mastered' counts for a lot; regexes are hard. I use a lot of regexes because I'm a Perl geek, have been for years, and I'm pretty handy with them. I wouldn't recommend them to someone who doesn't know a zero-length negative lookahead assertion from a pair of non-capturing parentheses but does need to get a job done by a deadline; almost every purpose for which regexes are used (including most of the ways I use them) can be handled by something that doesn't require learning a whole 'nother language, and a famously intimidating one at that. Besides, PHP's PCREs aren't as PC as they claim, and that irritates me sometimes.

You've got a couple of good points in here; turning $var = $var + 1 into $var++ (or ++$var, as necessary, but you didn't know that and had to be told) comes to mind, for example, and so does implied truth testing (if ($var) { do_something(); };). Unfortunately, they're not enough to redeem the rest of the article; your understanding of programming is all surface, you have no comprehension of the way things actually work, and believe it or not such comprehension is necessary if you want to write code that doesn't suck. Please refrain from claiming a position of undeserved authority from which to offer advice (or, perhaps, parrot without attribution things you've read elsewhere and failed sufficiently to understand) until you have sufficient understanding to avoid telling other people to make dumb mistakes.

-- Aaron I'd have just said 'don't listen to him, he doesn't know what he's talking about', but I felt that wouldn't sufficiently make the point.

login or register to post comments

Let's be positive

Submitted by Xanadu on December 5, 2005 - 16:56.

Why does PHP arouse anger whenever someone offers advice? People make it their mission to bring down the author (as Pink Floyd sang "by exposing every weakness, however carefully hidden"). They take an attitude that unless the advice matches exactly what they know, then the author must an idiot, his advice must be full of security holes, he shouldn't even be on the internet, dammit! What's wrong with these people? Are they just venting steam after a hard day's programming?

Let's be positive and thankful for the advice given. Sure, if there are issues with any of it, point them out peacefully.

The tips in the article are ones I would mostly recommend myself. Not all, but most. The main one I would take issue with is writing HTML full of opening and closing PHP statements. If I have a file with only a few lines of HTML inbetween PHP, I prefer to keep within PHP and just echo the HTML.

Regarding single vs double quotes, be aware of some key differences:

Double quotes
You must escape any double quotes inside them. You can add variables.
Single quotes
You must escape any single quotes inside them, and concatenate any variables.

As for line breaks, I have found you can simply enter these in the source code, by pressing the ENTER key, and they will appear. No need for slashes and n's. Use PRE tags if you are ouputting raw text.

The heredoc syntax really is the killer. It enables you to add variables without concatenation. Just be wary of array values - they need curly brackets around them. Even so, I try to use this method for multiple lines with variables in, as it's so much better to write and read.

Another tip I have found handy is to do away with variable names in URLs. Instead of "example.php?author=tolkein&location=forest&wizard=gandalf" you can apply the same variables by joining them together. Eg: "example.php?tolkein.forest.gandalf". Use other joining characters if you need a dot in a variable. Then, on the page linked to, simply separate the variables into names, using the server query string.

This works great with only one variable too. "example.php?generation=x" is wasteful when all you need is "example.php?x". The only drawback is changing the order of variables, or inserting new ones, which could lead to confusion without the names.

login or register to post comments

Plus...

Submitted by Xanadu on December 6, 2005 - 10:12.

I forgot to add that the heredoc syntax also allows you to use single or double quotes without escaping them. Also, if you always start it with "HTML" then some editors will use code highlighting, which is useful.

login or register to post comments

Missing Tip

Submitted by ourfriendbernard on December 21, 2005 - 03:52.

Howdy, In the "In and out of PHP before they even knew what hit 'em" bit,
which I started using a while ago and think is great.
The article goes back into php to print a variable in the middle of the HTML.
The code was
<?php
echo $local_oaf
?>
This can be done also like this "< ?=$local_oaf ?>" (I am using spaces between the < and the ? to make the code show up in the forum)
You dont ever need to use the "< ?php" the "< ?" is fine,
and if printing out a vaiable an "echo" can be replaced by an"=",
No spaces after the "?" Im not sure if that matters though...

login or register to post comments

the trick with short open

Submitted by jadwigo on January 10, 2006 - 16:22.

the trick with short open tags
<?= 'this will be printed' ?>
will only work on some hosts where "short tag style" is enabled, for readability and portability using the verbose alternative is better, and just as fast in execution (only more characters to type)
<?php
print 'this will be printed';
?>

login or register to post comments

In and Out

Submitted by dominic.baggott on February 1, 2006 - 12:15.

Another lurvely feature for this style of coding is to use alternative control structure syntax. It will often result in much cleaner more readable code:
<dl>
  <?php foreach ($var as $key => $value) : ?>
    <dt><?php echo $key; ?></dt>
    <dd><?php echo $value; ?></dd>
  <?php endforeach; ?>
</dl>
This avoids having the ambiguous "hanging braces" that you'll get from the usual syntax.

login or register to post comments

import_request_variables

Submitted by spanglerco on June 22, 2006 - 17:10.

// $_POST['form_name'] = 'Anus Mcgee';

foreach ($_POST as $key => $value)
$$key = $value;

// Now $form_name = 'Anus Mcgee';
You can do the same thing with import_request_variables("p"). This function can also to the same thing for $_GET variables and determine if one type overwrites the other. For added security, you can add a prefix to the imported variables as well, i.e. $in_form_name.

login or register to post comments

Thanks for the Tips

Submitted by Brad Henry on November 27, 2006 - 15:32.

I am somewhat new to PHP programming and find this to be very useful. Some of it is still above my skill level but I plan to bookmark this page for future reference. If anyone else has any good PHP code or tricks please add them here as well.

Thanks, Brad

login or register to post comments

Rated 1 star

Submitted by quaoar on March 8, 2007 - 13:22.

This is just such an article people learning PHP should NOT read...

For anyone trying to learn PHP, get a highly rated beginners book from Amazon, and read through the whole book. DO NOT read this article and think you have learned something useful. When you have finally gotten past the beginner stage, read through the book, you'll understand why this article is just awful.

you do not need to waste your time with brackets They are NEVER waste. You'll understand later when you either have to go back and edit old code, or make changes to code someone else wrote. Then you'll praise the lord if you bothered to use brackets wherever possible.

foreach ($_POST as $key => $value) $$key = $value; This is just weird. Why would you do this?

When embedding PHP within HTML, you can close your PHP tag whenever you want to output HTML. This enables speedier processing of your PHP No, it's not speedier. Every time Apache parses the page and hit php-code, it will have to start the php-parser.

What is the the super-secret of keeping those scripts speeding along the rusty pipes of your server? Avoid double quotes at all costs. Christ! This is also just plain weird. If there is one thing there is enough of in the modern day webserver, it is power. They tiny-tiny-tiny-tiny-tiny-tiny gain you -might- get from only using single quotes and string concatenation is BY FAR outweighed by using functions like sprintf with placeholders, DB wrappers with placeholders, and such. Most of them using double quoted strings for parsing. Just look at the code for Drupal, which evolt.org is using. There simply is NO gain in singel vs. double quotes. For speeding up webservers/webpages you using caching, template caching, proxy servers and/or php compilers, all which don't give a rats ass about your singel or double quotes.

The spaces vs. tabs is on the same level as the singel vs. double quotes comment. Just weird and stupid. EVERY major PHP framework in existanse today, use spaces instead of tabs. Following the advice of this person, you'll actually do opposite of what all experienced PHP coders do. Now THAT IS a swell advice! We use spaces because every editor know how much space each space takes (one char/one column). Most editors/systems/computers use different rules for how to display a tab. Which result in very strange formatting on different systems. Don't use tabs, use spaces!

login or register to post comments

Eloquent code

Submitted by Chris Boswell on September 19, 2007 - 18:15.

Its a long time since I had to write any PHP and it was never really my thing to be honest. However, I do beleive that eloquent code is always something worth striving for - I remember many years ago a few colleagues competing to solve a PERL problem over the weekend - one took most of the weekend and came up with a 200 line solution, the other took about 20 minutes and came up with a 2 line solution.

Anyway, my point is that there's nothing wrong with striving for eloquent solutions and cutting down on extraneous code. We all go down wrong paths at some point, but if software developers and web app devs in general worked on this principle of writing brief, efficient code we'd have a lot less baggy software out there, and possibly the hardware vendors wouldn't find it so easy to get us to constantly upgrade and less computer hardware would be heading off into landfill

login or register to post comments

My 2 Cents

Submitted by asylumet on December 6, 2007 - 08:56.

how about trying this on. add this to the top of your php file just below the opening php tag as so.
<?php
error_reporting(E_ALL ^ E_STRICT);
When your code does not report any errors or notices then you have achieved something but until then what you think you are saving in processing time and all of that is mute. Just because your servers error_reporting is set to E_NOTICE you do not see the errors and warnings in your browser but it is likely that they are still sent to syslog. If you have a shell account log in and tail your log messages you will see. For instance if you have not set $myvar yet for whatever reason and do
<?php
echo $myvar;
?>
You will see -> Notice: Undefined variable: myvar in /path/to/file.php on line 2 Or this conditional here is on 2 lines since the echo $myvar is what errors.
<?php
if ($myvar)
echo $myvar;
?>
Notice: Undefined variable: myvar in /path/to/file.php on line 3 To write this properly you could do either of the following
<?php
if (!empty($myvar)) echo $myvar;
if (isset($myvar)) echo $myvar;
?>
Or how about using ternary operators even?
<?php
echo isset($myvar) ? $myvar : '$myvar was not set';
?>
Another thing I did not see any mention of that I think you may like is sprintf
<?php
echo sprintf('On %s I turn %d years old', date('F jS',time()), (empty($age) ? 30 : $age));
?>
anyway hopefully that helps someone and regardless of what has been said this is a good article because not everything you mentioned was a good idea in practice and if anyone actually reads some comments they will find some useful information.

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.