Results 1 to 25 of 73
-
07-21-2004, 01:29 AM #1Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
How To : Improve Your PHP Programming
Hello everyone,
I've decided that I would make a thread here describing the different things that I do to improve other people's PHP scripts.
Hope you enjoy it and learn a thing or two.
1 - Your PHP Tags
I know some of you prefer to use the short tags when writing PHP scripts <? ?> but this is not always the best way of doing it.
The standard tags <?php ?> are much better as they will work on every server that you write your PHP code on. You may move to a server some day that doesn't allow the short tags or the ASP-style tags and you will have to sit for an hour and update your PHP scripts.
2 - Debugging Your PHP Code
Some of us may run into a problem when programming a PHP script and don't know what's wrong with it. The error_reporting() function in PHP helps you out by telling every error you have on your page. To show all of the errors on the page that you're editing, put this on the second line :
PHP Code:error_reporting(E_ALL);
When you finish editing your 1200-line PHP script, click onto it in your Internet browser, you see an error that says that is on line 561. Don't hit the panic-attack button quite yet, because there is an easy way to find out what line 561 is. Follow these easy steps :
- Open up Microsoft Notepad
- Paste your PHP script into it
- Go to 'Edit' >> 'Go To...' (or Control+G)
- Type in line #561 and hit the enter key
- Your cursor is taken to line #561.
- Look above and below line #561 to see if there is any kind of trouble.
- Fix the error, re-upload the script to your website, and most likely it will work. If there is another error, repeat the above steps.
4 - Using Comments
If you have a 1200-line PHP script, it may be quite hard to figure out what's going on all through-out it. The solution to figure out what you're doing is to add PHP-comments.
PHP-comments are different than the <!-- HTML Comments --> as they are not outputted to the user's page (meaning that they are not even going to see it in the source code).
There are three ways to make comments in PHP :
PHP Code:<?php
// The double-backslash is my personal favorite. I add another set after my code so that it looks even, though it is not necessary. //
# The hash-style comment is another way of making a comment.
/* And, this is the final way of making PHP-comments. You can use
multiple
lines
at a time by using this style. */
?>
5 - Indenting Your PHP Codes
I don't personally like to indent my PHP codes, but it helps when reading it. When I do have to, I use the tab key to accomplish this. Example :
PHP Code:<?php
// Settings //
$var1 = "This";
// Showing Variables //
if($var1 == "This"){
echo"You said This";
}else{
echo"You said That";
}
?>
I'm sure that most of us on here include a PHP file or two for our layouts. Well, what if your layout file was missing ? Wouldn't that look pretty unprofessional to the people on your website ?
In every PHP-script that I write, I make sure that the file exists before it is even included. Here's an example :
PHP Code:<?php
if(!file_exists("layout.inc.php")){exit("Error : LayOut File Missing");}else{include_once("layout.inc.php");}
?>
7 - Your MySQL Queries
Sometimes when you're writing a PHP script that includes connections to your MySQL database, you may run into a few problems. Most everyone that had MySQL problems ran a command like this one :
PHP Code:<?php
mysql_query("INSERT INTO tableName ('id','name') VALUES('1','Mike')");
?>
PHP Code:<?php
mysql_query("INSERT INTO tableName ('id','name') VALUES('1','Mike')") or exit("MySQL Error : " . mysql_error());
?>
You may have a register page, and want to make sure that everything has been filled-in. You may use many if-then statements like so :
PHP Code:<?php
if(!$_POST[name]){exit("Sorry, but you did not fill-in all of the requested fields.");}
if(!$_POST[email]){exit("Sorry, but you did not fill-in all of the requested fields.");}
?>
PHP Code:<?php
if((!$_POST[name]) || (!$_POST[email])){exit("Sorry, but you did not fill-in all of the requested fields.");}
?>
9 - Using echo or print ?
Most of you may say 'echo is the same thing as print', in which I agree with you all. The echo command is much faster than the print command, and is one less character to type. The echo command came later than the print command (I believe), so you make the judement on which to use.
10 - Printing out a Huge Chunk of HTML at a Time
Well, I'm sure that many of us found a way to get around this, but I'd like to share with you a few of the ways you can do it.
1 - Break off your PHP-code, print the HTML, and start your PHP-code up again. (I don't prefer doing this as it looks pretty unprofessional to me).
2 - Adding backslashes to each HTML tag. (It works, but takes forever to do).
3 - Using the echo/print command, but without having to do much work. (I recommend) :
PHP Code:<?php
// Showing a huge chunk of HTML at a time //
echo<<<END
<font face="Verdana" color="Orange" size="3">Large, Orange Text in Font Size 3</font>
<br><br>
More HTML down here..
<br><br>
<div align="Center">Centered text</div>
END;
?>
I hope I've helped.
Best Regards,
- Mike.Last edited by giropets; 07-21-2004 at 01:40 AM.
0
-
07-28-2004, 08:03 AM #2Newbie
- Join Date
- Jun 2004
- Location
- Islamabad
- Posts
- 11
Very nice How To , and its not boring at all..your writing style is very interesting and i hope to have more ideas from your mind in the future. Thanx for sharing these tips.
MaJiD SaeeD Khan
Software Engineer - Bahriasoft
http://www.Bahriasoft.com0
-
07-28-2004, 09:44 AM #3Newbie
- Join Date
- Jul 2004
- Posts
- 23
Ild just like to point out something on the echo and print argument. You say "The echo command is much faster than the print command". I'ld like to point out why.
Print has a return value, echo does not.
Consider:
PHP Code:<?php
if (print('foo')) { print('foo printed'); } // Will be true
if (echo('foo')) { echo('foo printed'); } // Will be false
?>
PHP Code:<?php
function print($stringToPrint) {
system.out($stringToPrint);
return 1;
}
function echo ($stringToPrint) {
system.out($stringToPrint);
}
?>
- Kar0
-
07-28-2004, 09:50 PM #4Newbie
- Join Date
- Jul 2004
- Location
- Ann Arbor, MI
- Posts
- 17
The only things I would point out are:
1. Use variable names that make sense.
a) $string is a string, and $string_array is an array for example. $flag is a flag...
2. Put your code into functions as much as possible, and write your functions so they can be used in multiple projects - try not to write code that is proprietary to the project at hand.
a) save your functions in library files that you can use the 'include' command to call them up again in your projects.-------------------------------------------
http://www.jmrtechnet.com0
-
07-28-2004, 10:44 PM #5Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
Hello again everyone,
Since all of you thought it was not boring, I've decided that I would add a few more to my list.
11 - Multiple Items in the If-Then Statement
As said in #8, you can combine alike if-then statements into one. This also works...
PHP Code:if($this == "that" && $that == "this"){echo"This and that match";}
PHP Code:if(($this == "that") && ($that == "this")){echo"This and that match";}
When using functions, and you want to include a load of settings, you need to include every single of them at a time, as so...
PHP Code:<?php
$time = date("Y-m-d:H.i.s");
$name = "Mike";
$comment = "Just a simple comment";
function show(){
global $time,$name,$comment;
echo"$time - $name - $comment";
}
show();
?>
PHP Code:<?php
$_SETTINGS[time] = date("Y-m-d:H.i.s");
$_SETTINGS[name] = "Mike";
$_SETTINGS[comment] = "Just a simple comment";
function show(){
global $_SETTINGS;
echo"$_SETTINGS[time] - $_SETTINGS[name] - $_SETTINGS[comment]";
}
show();
?>
13 - Shortening exit(); and die(); Functions
If you want to stop the page load, you can use the exit(); or die(); functions. But, if this is all you want to do, then you can shorten it...
PHP Code:exit();
exit;
die();
die;
If you want to stop the page load and show text, you can do this..
PHP Code:echo"You did not finish all of the required fields.";
exit;
PHP Code:exit("You did not finish all of the required fields.");
Arrays are used to store temporary data in a PHP code. Here's an example...
PHP Code:<?php
$names = array("Mike","Charlie","Amanda","Caroline");
echo $names[0]; // Outputs 'Mike'
echo $names[1]; // Outputs 'Charlie'
echo $names[2]; // Outputs 'Amanda'
echo $names[3]; // Outputs 'Caroline'
?>
Best of luck,
- Mike.Last edited by giropets; 07-28-2004 at 10:48 PM.
0
-
08-05-2004, 08:43 PM #6Disabled
- Join Date
- Jun 2004
- Location
- USA, Ohio
- Posts
- 96
Very nicely done giropets.. *cheers*
0
-
08-05-2004, 09:17 PM #7Web Hosting Master
- Join Date
- Aug 2004
- Location
- Canada
- Posts
- 3,785
That's very nice and informative for anyone specially beginners
Some other stuff to keep your code more clean and manageble would be to keep HTML and PHP completly seperate for the most part seperate files for them. So useing functions to call the html keep it much cleaner or a template system. Obviously functions like jasonr33 said specially for database stuff make it much easier.
Heck I've had the same functions for quite a while the same mysql, template and functions files you'd be surprised how much time is saved when all your php scripts use the same set of functions.0
-
08-05-2004, 11:38 PM #8Web Hosting Master
- Join Date
- Aug 2003
- Posts
- 4,279
Re: How To : Improve Your PHP Programming
Originally posted by giropets
3 - Debugging Your PHP Code (again)
When you finish editing your 1200-line PHP script, click onto it in your Internet browser, you see an error that says that is on line 561. Don't hit the panic-attack button quite yet, because there is an easy way to find out what line 561 is. Follow these easy steps :
- Open up Microsoft Notepad
- Paste your PHP script into it
- Go to 'Edit' >> 'Go To...' (or Control+G)
- Type in line #561 and hit the enter key
- Your cursor is taken to line #561.
- Look above and below line #561 to see if there is any kind of trouble.
- Fix the error, re-upload the script to your website, and most likely it will work. If there is another error, repeat the above steps.
Best Regards,
- Mike.
I strongly suggest that instead of using plain notepad/wordpad or ms-word to code your scripts you get a proper PHP editor such as PHPcoder or the one by Zend. (which is great, I love it. )
it has a ton of time saving advantages such as syntax highlighting and line numbering, 'etc.
EugeneIWDN - Really smart web developers... and me!
More than any time in history mankind faces a crossroads.
One path leads to despair and utter hopelessness, the other to total extinction.
Let us pray that we have the wisdom to choose correctly.0
-
08-05-2004, 11:39 PM #9Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
I think I've figured it out the hard way, but thanks for letting me know as I take interest in it.
0
-
08-09-2004, 12:37 PM #10Newbie
- Join Date
- Mar 2004
- Posts
- 15
I have recently begun to comment all my closing tags and that is really helping a lot. Like I did in the last two lines of this dummy code below. If there is a lot of stuff contains in the if tags where the opening and closing tags are far apart it helps to know where one starts and ends, as well as telling if your number of brackets match up.
PHP Code:if ($something == "this") {
for($i=0; $i<10; $i++) {
echo $i;
$double[$i] = $i*2;
} // for
} // if
0
-
08-09-2004, 05:03 PM #11Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
That's actually not a bad idea, I should try using that from now on.
0
-
08-17-2004, 02:49 PM #12Temporarily Suspended
- Join Date
- Aug 2004
- Posts
- 41
Yes. For clarity you can even do this for nested statements like
Code:for($i = 0; $i < 10; $i++) { for( ; ; ) { break; } // inner for } // outer for
0
-
08-24-2004, 12:09 PM #13Junior Guru Wannabe
- Join Date
- May 2003
- Posts
- 44
<?php
if(!file_exists("layout.inc.php")){exit("Error : LayOut File Missing");}else{include_once("layout.inc.php");}
?>
Code:function includeme ($addr) { //Check that file exists if (! file_exists($addr)) { exit("Error : '$addr' File Missing"); } //Include File include($addr); }
0
-
08-26-2004, 12:59 PM #14New Member
- Join Date
- Aug 2004
- Posts
- 3
PHP Code:<?php
mysql_query("INSERT INTO tableName ('id','name') VALUES('1','Mike')") or exit("MySQL Error : " . mysql_error());
?>
PHP Code:<?php
$sql = "SELECT value FROM table";
$query = mysql_query($sql)
or die("You got the error: " . mysql_error() . "with the query: $sql");
?>
You should never make a variable like $_SETTINGS. The _ is there to show that it is a system (php-specific) variable like $_POST, $_GET and $_SERVER. Rather do $settings then!
PHP Code:<?php
$_SETTINGS[time] = date("Y-m-d:H.i.s");
$_SETTINGS[name] = "Mike";
$_SETTINGS[comment] = "Just a simple comment";
function show(){
global $_SETTINGS;
echo"$_SETTINGS[time] - $_SETTINGS[name] - $_SETTINGS[comment]";
}
show();
?>0
-
08-26-2004, 04:55 PM #15Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
Thanks for pointing those out, scuba. I should try using the SQL lines you done in my code to help debug even better.
0
-
08-27-2004, 10:47 PM #16Newbie
- Join Date
- Aug 2004
- Posts
- 23
Just a quick comment:
'&&' and 'AND' aren't exactly the same, they have different precedence. For example:
Code:<PRE> <?php $a = "hello\n"; $b = "goodbye\n"; print "First trial\n"; if (print $a && print $b) { print "Bad\n"; } print "\nSecond trial\n"; if (print $a and print $b) { print "Good\n"; } ?> </PRE>
First trial
goodbye
1Bad
Second trial
hello
goodbye
Good0
-
09-06-2004, 12:17 PM #17Newbie
- Join Date
- Sep 2004
- Posts
- 11
Advantage of PHP?
May i know what PHP can be used for?
How powerful is this language?
Thanks!0
-
09-06-2004, 01:37 PM #18Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
Well, PHP can be used for a lot of things on the internet.
I programmed a whole entire site with my friend that was a web game with PHP back-end programming.
It is very powerful - just depending on how you want to use it.0
-
09-06-2004, 10:00 PM #19Newbie
- Join Date
- Sep 2004
- Posts
- 11
Wouldn't it be better and easier to make a web game using Flash instead of PHP? If not, what advantages does PHP have over Flash?
0
-
09-06-2004, 10:03 PM #20Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
GiroPets.net is the web game that I made. It includes a few Flash games as well. I recently sold the site (I should get myself a new screen name for WHT)...
0
-
09-07-2004, 02:40 PM #21Registered User
- Join Date
- Jun 2002
- Location
- Minnesota
- Posts
- 9
thanks for this post
0
-
09-25-2004, 07:26 PM #22Aspiring Evangelist
- Join Date
- Jul 2004
- Posts
- 360
Thanks to everyone that posted ideas and how-to's on this board.
I have succesffully created a few php programs - but my coding was sloppy and hard to change.
On my next few programs I plan on changing that and this post will definitly help me keep my code clean and concise.
Billy0
-
09-25-2004, 09:30 PM #23Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
Originally posted by billy79
Thanks to everyone that posted ideas and how-to's on this board.
I have succesffully created a few php programs - but my coding was sloppy and hard to change.
On my next few programs I plan on changing that and this post will definitly help me keep my code clean and concise.
Billy0
-
10-05-2004, 08:33 AM #24WHT Addict
- Join Date
- Oct 2004
- Posts
- 100
Also, read the Open Web Application Security Project guide:
http://www.owasp.org/documentation/g...ide_about.html0
-
11-06-2004, 05:43 PM #25WHT Addict
- Join Date
- Jun 2004
- Posts
- 112
Just a little something to add:
* switch/case is faster than an if condition
* Type cast any foreach arguments to avoid error messages
PHP Code:<?php
//Assume $someArray is the return value of a function
//and it will only be an array if the function
//was successful
$someArray = (array) $someArray;
foreach($someArray as $eachElement)
{
echo $eachElement . '<hr />';
}
?>
* To view the contents of a variable, you can use print_r() which will print the variable out in a human readable format.
* You can use var_dump() or var_export() to view the values and types of a variable. The latter will show the values in a format that can be used within a PHP script directly (i.e. it wont cause any parse errors)
* When using comparison operators, you can either use == or === The latter will check for the type as well as the value and it is faster.
PHP Code:<?php
$boolTrue = TRUE;
$boolFalse = FALSE;
$intOne = 1;
$intZero = 0;
$intOther = 5;
//This evaulates to true
if($intOne == $boolTrue)
{
echo 'Loose checking';
}
//This is false because one is an
//integer, while the other is a boolean
if($intOne === $boolTrue)
{
echo 'Strict checking';
}
?>
PHP Code:<?php
//This snippet will strip any tags off all GET arguments
foreach($_GET as $myKey => $myValue)
{
$_GET[$myKey] = strip_tags($myValue);
}
?>
PHP Code:<?php
//This will output an error if the password is wrong
mysql_connect('localhost', 'username', 'wrongPassword');
//This will not display any error messages
@mysql_connect('localhost', 'username', 'wrongPassword');
//Assuming the method myMethod has an error in it,
//it wont spit out any warnings because of the @ prepend
@$myObj->myMethod($myArgument);
?>0