Jump to content

Cleaning Up Code


shadowayex

Recommended Posts

Hello. I've been trying to clean up my code a bit. The problem is, I'm not too up to date about what's the best way to write PHP. Kind of like XHTML is clean HTML, I want to have my PHP code to be as correct as possible. So far, I have two pages. I've tried to make it so there's no place where PHP writes HTML, because I figured that'd be best. If not, let me know. Also I've tried to use mysql_real_escape_string() and mysql_free_result where they are needed. If I missed anything let me know. HEre's two pages I think I've covered. Please check them out and tell me if there's a better, cleaner way to write them.

<?php session_start();include("connect.php");$mode = mysql_real_escape_string($_GET['mode']);if(isset($_SESSION['user'])) { $user = $_SESSION['user'];}else { $user = "Guest";}?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>Welcome to Hug Don't Mug - <?php echo $user ?></title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><script src="mmenu.js" type="text/javascript"></script><script src="menuItems.js.php" type="text/javascript"></script></head><body><div class="ads"><h1>Ads here</h1></div><div class="content"><div class="banner"><h1>Banner Goes Here!</h1><p>Height is to be decided. It's currently set at 150 px.</p></div><p class="userinfo">Hello <?php echo $user ?>!<?phpif($user == "Guest") {?> Please <a href="index.php?mode=login">log in</a> to see your alerts. No account? <a href="index.php?mode=signup">Sign up</a>, it's free!<?php }else { if($mode == "viewmsg") {  $chngstat = mysql_query("UPDATE messages SET ReadStat = 'read' WHERE MsgId = '$id'"); } $msgs = mysql_query("SELECT * FROM messages WHERE Receiver = '$user' AND ReadStat = 'unread'"); $msgs = mysql_num_rows($msgs); if($msgs == 1) {?>  You have <a href="messages.php">1 message</a>.<?php } elseif($msgs > 1){?>  You have <a href="messages.php"><?php echo $msgs; ?> messages</a>.<?php  }}?></p><div style="padding: 0px 10px 10px 10px"><?phpif($mode == "signup") {?> <p>Choose a Username and Password under 15 characters long.</p> <form action="signup.php" method="post"> <div> Desired Username: <input type="text" name="username" value="" /><br /> Desired Password: <input type="password" name="password" value="" /><br /> <input type="submit" name="submit" value="Sign Up!" /> </div> </form><?php }elseif($mode == "login") {?> <form action="login.php?mode=firstlogin" method="post"> <div> Username: <input type="text" name="username" value="" /><br /> Password: <input type="password" name="password" value="" /><br /> <input type="submit" name="submit" value="Login" /> </div> </form><?php }else {?><div class="text"><h1 style="text-align: center;">Latest Update</h1><?php  $latestupdate = mysql_query("SELECT * FROM news ORDER BY MsgId DESC LIMIT 1"); $column = mysql_fetch_array($latestupdate); ?><h2><?php echo stripslashes($column['Title']); ?></h2><?php echo nl2br(stripslashes($column['News'])); ?><a href="news.php">More Updates</a></div><?php } ?></div></body></html>

<?php include("connect.php");/*---------------Log In On Page---------------*/if($mode == "login") { include("login.php");}/*---------------Check for User---------------*/if(isset($_SESSION['user'])) { $user = $_SESSION['user'];}else { $user = "Guest";}/*---------------Global Variables---------------*/$mode = mysql_real_escape_string($_GET['mode']);$id = mysql_real_escape_string($_GET['id']);$account = mysql_query("SELECT * FROM users WHERE Username = '$user'");$account = mysql_fetch_array($account);$timezone = $account['Timezone']*3600;$timestamp = date("U")+$timezone;if($account['DST'] == "yes") { $timestamp = $timestamp+3600;}$time = date('g:i A \o\n F jS, Y', $timestamp);/*---------------Page Functions---------------*//*------------User Info Bar------------*/function userInfo() { global $user; if($user == "Guest") { /*---------Guest Code---------*/?>  Please <a href="index.php?mode=login">log in</a> to see alerts. No account? <a href="index.php?mode=signup">Sign up</a>, it's free!<?php } else { /*---------User Alerts---------   ---------Messages---------*/  $msgs = mysql_query("SELECT * FROM messages WHERE Receiver = '$user' AND ReadStat = 'unread'");  $msgs = mysql_num_rows($msgs);  if($msgs == 1) {?>   You have <a href="messages.php">1 message</a>.<?php  }  elseif($msgs > 1) {?>   You have <a href="messages.php"><?php echo $msgs; ?> messages</a>.<?php   } }}/*------------Messaging Functions------------*//*---------Delete Functions---------*/function deleteAll() { global $user; $deleteall = mysql_query("DELETE FROM messages WHERE Receiver = '$user'"); if(!deleteall) {  die("Error: Messages could not be deleted. Sorry for the inconvenience."); } else {  echo "Messages were deleted."; }}function deleteMsg() { global $id; global $user; $deletemsg = mysql_query("DELETE FROM messages WHERE Receiver = '$user' AND MsgID = '$id'"); if(!$deletemsg) {  die("Error: Message could not be deleted. Sorry for the inconvenience."); } else {  echo "Message was deleted."; }}/*---------Creating And Sending---------*/function newMsg() {?> <form action="messages.php?mode=sendmsg" method="post"> <div> To: <input type="text" name="to" value="" /><br /> Subject: <input type="text" name="subject" value="" /><br /> Message:<br /> <textarea rows="10" cols="50" name="message"></textarea><br /> <input type="submit" name="submit" value="Send" /> </div> </form><?php}function reply() { global $id; global $user; $message = mysql_query("SELECT * FROM messages WHERE MsgId = '$id'"); $row = mysql_fetch_array($message); if($user == $row['Receiver']) {?>  <form action="messages.php?mode=sendmsg" method="post">  <div>  To: <input type="text" name="to" value="<?php echo $row['Sender'] ?>" /><br />  Subject: <input type="text" name="subject" value="<?php echo $row['Subject'] ?>" /><br />  Message: <br />  <textarea rows="10" cols="50" name="message"><?php   echo "\n\n-----\n{$row['Sender']}:\n";   echo stripslashes($row['Message']);?>  </textarea><br />  <input type="submit" name="submit" value="Send" />  </div>  </form><?php } else {  echo "Message does not exist!"; } mysql_free_result($message);}function sendMsg() { global $user; global $timestamp; $to = mysql_real_escape_string($_POST['to']); $subject = mysql_real_escape_string($_POST['subject']); $message = mysql_real_escape_string($_POST['message']); $check = mysql_query("SELECT * FROM users WHERE Username = '$to'"); if(mysql_num_rows($check) != 1) {?>  <p>User does not exist. Try again.</p>  <form action="messages.php?mode=sendmsg" method="post">   <div>   To: <input type="text" name="to" value="" /><br />   Subject: <input type="text" name="subject" value="" /><br />   Message:<br />   <textarea rows="10" cols="50" name="message"></textarea><br />   <input type="submit" name="submit" value="Send" />   </div>  </form><?php } else {  $sendmsg = mysql_query("INSERT INTO messages (Receiver, Sender, Subject, Message, Time) VALUES ('$to', '$user', '$subject', '$message', '$timestamp')");  if(!$sendmsg) {   die("Error: Message could not be sent. Sorry for the inconvenience.");  }  else {   echo "Message was sent.";  } } mysql_free_result($check);}/*---------View Boxes and Messages---------*/function viewInbox() { global $user; $inbox = mysql_query("SELECT * FROM messages WHERE Receiver = '$user' ORDER BY MsgId DESC"); if(mysql_num_rows($inbox) == 0) {  echo "No messages"; }?> <table><?php while($row = mysql_fetch_array($inbox)) {  if($row['ReadStat'] == "unread") {?>   <tr style="font-weight: bold;"><?php   }  else {?>   <tr><?php   }?>    <td><?php echo $row['Sender']; ?></td>    <td><a href="messages.php?mode=viewmsg&id=<?php echo $row['MsgId']; ?>"><?php echo $row['Subject']; ?></a></td>    <td><?php echo date('g:i A \o\n F jS, Y', $row['Time']); ?></td> <!-- 150 -->    <td><a href="messages.php?mode=deletemsg&id=<?php echo $row['MsgId']; ?>">Delete</a></td>   </tr><?php }?> </table> <a href="messages.php?mode=deleteall">Delete All Messages</a><?php mysql_free_result($inbox);}function viewMsg() { global $id; global $user; $chngstat = mysql_query("UPDATE messages SET ReadStat = 'read' WHERE MsgId = '$id'"); $message = mysql_query("SELECT * FROM messages WHERE MsgId = '$id'"); $row = mysql_fetch_array($message); //160 if($user == $row['Receiver']) {?>  From: <?php echo $row['Sender']; ?><br />  Subject: <?php echo $row['Subject']; ?><br />  <?php echo nl2br(stripslashes($row['Message'])); ?><br />  <a href="messages.php?mode=reply&id=<?php echo $row['MsgId']; ?>">Reply</a>   <a href="messages.php?mode=deletemsg&id=<?php echo $row['MsgId']; ?>">Delete</a><?php } elseif($user == $row['Sender']) {?>  To: <?php echo $row['Receiver']; ?><br />  Subject: <?php echo $row['Subject']; ?><br />  <?php echo nl2br(stripslashes($row['Message'])); ?><br /><?php } else {  die("Message does not exist!"); } mysql_free_result($message);}function viewSent() { global $user; $sent = mysql_query("SELECT * FROM messages WHERE Sender = '$user' ORDER BY MsgID DESC"); if(mysql_num_rows($sent) == 0) {  echo "No messages"; }?> <table><?php while($row = mysql_fetch_array($sent)) {  if($row['ReadStat'] == "unread") {?>   <tr style="font-weight: bold;"><?php   }  else {?>   <tr><?php   }?>    <td><?php echo $row['Receiver']; ?></td>    <td><a href="messages.php?mode=viewmsg&id=<?php echo $row['MsgId']; ?>"><?php echo $row['Subject']; ?></a></td>    <td><?php echo date('g:i A \o\n F jS, Y', $row['Time']); ?></td>   </tr><?php }?> </table><?php mysql_free_result($sent);}?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>Messages - <?php echo $user; ?></title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><script src="mmenu.js" type="text/javascript"></script><script src="menuItems.js.php" type="text/javascript"></script><script src="matching_columns.js" type="text/javascript"></script></head><body><div class="ads"><h1>Ads here</h1></div><div class="content column"><div class="banner"><h1>Banner Goes Here!</h1><p>Height is to be decided. It's currently set at 150 px.</p></div><p class="userinfo">Hello <?php echo $user; ?>!<?php userInfo(); ?></p><div style="padding: 0px 10px 10px 10px"><?phpif($_SESSION['logged_in'] != true) {?> <form action="messages.php?mode=login" method="post"> <div> Username: <input type="text" name="username" value="" /><br /> Password: <input type="password" name="password" value="" /><br /> <input type="submit" name="submit" value="Login" /> </div> </form><?php}else {?><div>Welcome <?php echo $user; ?>!<br /> <a href="messages.php?mode=newmsg">Send New Message</a> | <a href="messages.php?mode=viewinbox">Inbox</a> | <a href="messages.php?mode=viewsent">Outbox</a><!-- 60 --></div><?php  if($mode == "deleteall") {  deleteAll(); } elseif($mode == "deletemsg") {  deleteMsg(); } elseif($mode == "newmsg") {  newMsg(); } elseif($mode == "reply") {  reply(); } elseif($mode == sendmsg) {  sendMsg(); } elseif($mode == "viewinbox") {  viewInbox(); } elseif($mode == "viewmsg") {  viewMsg(); } elseif($mode == "viewsent") {  viewSent(); } else {  viewInbox(); }}mysql_close($link);?></div></div></body></html>

Link to comment
Share on other sites

The first thing I see is that your files could use more indentation. I think most people use 4 spaces, so this (which has single spaces as I'm submitting it but none in the preview)

if(isset($_SESSION['user'])) { $user = $_SESSION['user'];}else { $user = "Guest";}

would become this

if(isset($_SESSION['user'])) {	$user = $_SESSION['user'];}else {	$user = "Guest";}

And your HTML doesn't have any yet, but I don't indent PHP and HTML together. For example, this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>Messages - <?php echo $user; ?></title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><script src="mmenu.js" type="text/javascript"></script><script src="menuItems.js.php" type="text/javascript"></script><script src="matching_columns.js" type="text/javascript"></script></head>

would become this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">	<head>		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />		<title>Messages - <?php echo $user; ?></title>		<link rel="stylesheet" type="text/css" href="stylesheet.css" />		<script src="mmenu.js" type="text/javascript"></script>		<script src="menuItems.js.php" type="text/javascript"></script>		<script src="matching_columns.js" type="text/javascript"></script>	</head>

and this

<div class="banner"><h1>Banner Goes Here!</h1><p>Height is to be decided. It's currently set at 150 px.</p></div><p class="userinfo">Hello <?php echo $user; ?>!<?php userInfo(); ?></p><div style="padding: 0px 10px 10px 10px"><?phpif($_SESSION['logged_in'] != true) {?>

would become this

		<div class="banner">			<h1>Banner Goes Here!</h1>			<p>Height is to be decided. It's currently set at 150 px.</p>		</div>				<p class="userinfo">Hello <?php echo $user; ?>!<?php userInfo(); ?></p>				<div style="padding: 0px 10px 10px 10px"><?php		if($_SESSION['logged_in'] != true) {?>

Also, I prefer to put my PHP on separate lines and give my <?phps and ?>s their own lines if they contain any linebreaks, so this

<div style="padding: 0px 10px 10px 10px"><?phpif($_SESSION['logged_in'] != true) {?>

would become this

		<div style="padding: 0px 10px 10px 10px"><?php if($_SESSION['logged_in'] != true) {?>

and this

</form><?php}else {?>

would become this

		</form><?php}else {?>

Finally, I prefer to put each of my elses on the same line as both its } and its { in order to associate it with the previous block (not to mention save a line or two), so that last one would be

		</form><?php } else { ?>

Link to comment
Share on other sites

  • 2 weeks later...
I've tried to make it so there's no place where PHP writes HTML, because I figured that'd be best.
Do you mean echo '<html> blahblahblah </html>'? If yes, i'd like to know why?And also, i always dont know which is the best,
<?= '<span id="', $id, '">', $something_else, ' and ', $even_something_else, '</span>'; ?>

or

<?= "<span id=\"$id\">$something_else and $even_something_else</span>"; ?>

or

<span id="<?=$id;?>"><?=$something_else;?> and <?=$even_something_else;?></span>

Link to comment
Share on other sites

i wouldnt use <?=...?> at all, cause these get removed in php6
Oh really? So forget about <?= and imagine them as if <? echo. Which is better?
Link to comment
Share on other sites

@ midnite:Always use: <?php echo 'string';?>. Never use <?='asdf';?>From php.net: While some people find short tags (<? ?>) and ASP style tags (<% %>) convenient, they are less portable, and generally not recommended.On your own production server, short tags may be fine, but if you're distributing your source code, the short tags may not work on other people's servers as they may have short tags disabled in their php.ini file.

<?php echo "<span id=\"$id\">$something_else and $even_something_else</span>";?>

Even though single quotes are normally faster than double quotes, for the line above, definetely use double quotes. It looks a whole lot better and probably is faster too because you do not have to concatenate the string or pass multiple arguments to echo. I don't have access to PHP right now so I can't benchmark the difference. Don't quote me on this.But avoid doing this:

<span id="<?=$id;?>"><?=$something_else;?> and <?=$even_something_else;?></span>

@ ragae:Everyone writes code differently. Just make sure all your variables are set before you use them. For example, make sure you use:

if (isset($_GET['mode']))$mode = $_GET['mode'];else$mode = null;/* or you can simply combine that into one line */$mode = isset($_GET['mode']) ? $_GET['mode'] : '';

If $_GET['mode'] isn't set and you have error_reporting set to E_ALL, then a notice will be triggered. I suggest you put this at the top of your file:

error_reporting(E_ALL | E_STRICT);

In that way, you will know if all your variables are set or not.Also, I suggest you use single quotes instead of double quotes:include 'connect.php';Edit: If you really want to have good, organized code, you should go for some Object Oriented Programming.If you want to separate your HTML from your PHP so you don't clutter them together in the same file, you should probably take a look at PHP templating engines (e.g. Smarty)

Link to comment
Share on other sites

Thanks Silver,Why not

<span id="<?php echo $id; ?>"><?php echo $something_else; ?> and <?php echo $even_something_else; ?></span>

Is it the worst? Is it the slowest?Thanks again,midnite

Link to comment
Share on other sites

Thanks Silver,Why not
<span id="<?php echo $id; ?>"><?php echo $something_else; ?> and <?php echo $even_something_else; ?></span>

Is it the worst? Is it the slowest?Thanks again,midnite

Because you want to make as few calls to PHP as possible. When you embed PHP in HTML like the example above, the parser will have to repeatedly switch gears between HTML and PHP. It will be slow down the parser a bit and the code itself looks incredibly messy as well. But just use whatever works best for you. The speed difference is very very small (less than 0.01%).Because I don't have access to PHP right now, I cannot compare the performance differences.Try benchmarking it yourself:
<?php/* benchmark.php for PHP5 */$start_time = microtime(true);for($i = 0; $i < 10000; ++$i){?><?php /* Replace this comment with the PHP code you wish to benchmark */ ?><?php}$time = microtime(true)-$start_time;echo '<p>Script took: ', $time, ' seconds</p>';?>

Link to comment
Share on other sites

Hi Silver,My server was down last night. Probably because of the black Friday (?) :)Thanks for your code and here are my results: (mine is only experimental server. i know it is slow. Just for comparison)

<?php/* benchmark.php for PHP5 */$id = 1; $something_else = 'something_else'; $even_something_else = 'even_something_else';$a0 = 'aa '; $a1 = 'aa '; $a2 = 'aa'; $a3 = 'aa '; $a4 = 'aa '; $a5 = 'aa '; $a6 = 'aa '; $a7 = 'aa '; $a8 = 'aa '; $a9 = 'aa ';$start_time = microtime(true);for($i = 0; $i < 40000; ++$i){?><? echo '<span id="', $id, '">', $something_else, ' and ', $even_something_else, ' | ', $a0, ' | ', $a1, ' | ', $a2, ' | ', $a3, ' | ', $a4, ' | ', $a5, ' | ', $a6, ' | ', $a7, ' | ', $a8, ' | ', $a9, '</span>'; ?><?php}$time = microtime(true)-$start_time;echo '<p>Script took: ', $time, ' seconds</p>';?>

(5.10774087906 + 5.37114286423 + 5.51149892807 + 6.13020420074 + 5.16465401649+ 5.19873785973 + 5.31841397285 + 5.09353208542 + 5.30105209351 + 5.63901996613) / 10= 5.38359968662

<?php/* benchmark.php for PHP5 */$id = 1; $something_else = 'something_else'; $even_something_else = 'even_something_else';$a0 = 'aa '; $a1 = 'aa '; $a2 = 'aa'; $a3 = 'aa '; $a4 = 'aa '; $a5 = 'aa '; $a6 = 'aa '; $a7 = 'aa '; $a8 = 'aa '; $a9 = 'aa ';$start_time = microtime(true);for($i = 0; $i < 40000; ++$i){?><? echo '<span id="'.$id.'">'.$something_else.' and '.$even_something_else.' | '.$a0.' | '.$a1.' | '.$a2.' | '.$a3.' | '.$a4.' | '.$a5.' | '.$a6.' | '.$a7.' | '.$a8.' | '.$a9.'</span>'; ?><?php}$time = microtime(true)-$start_time;echo '<p>Script took: ', $time, ' seconds</p>';?>

(5.29522109032 + 4.06656694412 + 4.80098891258 + 4.8137550354 + 5.20452594757+ 6.00905609131 + 4.8895111084 + 5.03454303741 + 5.29297709465 + 4.56197690964) / 10= 4.99691221714

<?php/* benchmark.php for PHP5 */$id = 1; $something_else = 'something_else'; $even_something_else = 'even_something_else';$a0 = 'aa '; $a1 = 'aa '; $a2 = 'aa'; $a3 = 'aa '; $a4 = 'aa '; $a5 = 'aa '; $a6 = 'aa '; $a7 = 'aa '; $a8 = 'aa '; $a9 = 'aa ';$start_time = microtime(true);for($i = 0; $i < 40000; ++$i){?><? echo "<span id=\"$id\">$something_else and $even_something_else | $a0 | $a1 | $a2 | $a3 | $a4 | $a5 | $a6 | $a7 | $a8 | $a9</span>"; ?><?php}$time = microtime(true)-$start_time;echo '<p>Script took: ', $time, ' seconds</p>';?>

(5.0854279995 + 4.51923298836 + 6.54459500313 + 5.20875811577 + 5.95256710052+ 5.15285611153 + 5.41061592102 + 5.11159420013 + 5.23796606064 + 5.46267604828) / 10= 5.36862895489

<?php/* benchmark.php for PHP5 */$id = 1; $something_else = 'something_else'; $even_something_else = 'even_something_else';$a0 = 'aa '; $a1 = 'aa '; $a2 = 'aa'; $a3 = 'aa '; $a4 = 'aa '; $a5 = 'aa '; $a6 = 'aa '; $a7 = 'aa '; $a8 = 'aa '; $a9 = 'aa ';$start_time = microtime(true);for($i = 0; $i < 40000; ++$i){?><span id="<?php echo $id; ?>"><?php echo $something_else; ?> and <?php echo $even_something_else; ?> | <?php echo $a0; ?> | <?php echo $a1; ?> | <?php echo $a2; ?> | <?php echo $a3; ?> | <?php echo $a4; ?> | <?php echo $a5; ?> | <?php echo $a6; ?> | <?php echo $a7; ?> | <?php echo $a8; ?> | <?php echo $a9; ?></span><?php}$time = microtime(true)-$start_time;echo '<p>Script took: ', $time, ' seconds</p>';?>

(5.60847997665 + 5.78493905067 + 4.85777878761 + 5.93815803528 + 5.18643403053+ 5.54992198944 + 5.71307301521 + 5.96453905106 + 5.21330285072 + 5.69345784187) / 10= 5.5510084629concatenating single quotes is the winner in my box!Silver is smart that parser switching really the most time consuming.midnite

Link to comment
Share on other sites

If you use single quotes, do you still have to escape double quotes? For example would echo '<p class="para">A styled Paragraph</p>' work or should it be echo '<p class=\"para\">A styled Paragraph</p>?Also, which is better, echo 'Hello ' . $user; or echo 'Hello {$user}';?

Link to comment
Share on other sites

As long as the quotes are different, escape \ is not necessary. That is, single in double, or double in single, no escape needed, isn't it?Oops i didn't know i can '{$var}'. i will try later =]midnite

Link to comment
Share on other sites

If you use single quotes, do you still have to escape double quotes? For example would echo '<p class="para">A styled Paragraph</p>' work or should it be echo '<p class=\"para\">A styled Paragraph</p>?Also, which is better, echo 'Hello ' . $user; or echo 'Hello {$user}';?
The first one works better.I don't think 'Hello {$user}' works for single quotes.Sigh, there are so many ways to echo stuff in PHP.echo 'Hello World ', $variable;echo 'Hello World ' . $variable;echo "Hello World $variable";echo "Hello World ${variable}";echo "Hello World {$variable}";echo <<<EOFHeredoc: Hello World {$variable}EOF;echo <<<'EOF'Nowdoc: Hello World which works only >= PHP 5.3.0EOF;And the list goes on...Just use whatever is the easiest to read. The performance difference is so small, no one notices the different. If you really want good performance, you might as well get APC (like me), eAccelerator, Zend Optimizer, or another PHP accelerator that will cache the compiled Bytecode of your scripts.
Link to comment
Share on other sites

<?php$var = 'string';$start = microtime(true);for ($i = 0; $i < 10000000; $i++){  $str = 'first ' . $var . ' last';}$end = microtime(true);echo 'single quotes: ' . ($end - $start) . ' seconds<br>';$start = microtime(true);for ($i = 0; $i < 10000000; $i++){  $str = "first {$var} last";}$end = microtime(true);echo 'double quotes: ' . ($end - $start) . ' seconds<br>';?>

single quotes: 4.3222439289093 secondsdouble quotes: 7.5165069103241 seconds

Link to comment
Share on other sites

Yeah. I've converted a lot of my code. I now use as few of PHP calls as I can, I use single quotes for everything, and when writing, I use the format echo 'Hello ' . $user. I was wondering, would it be better to put my PHP processing scripts into another file and include() the file? Or should I move my PHP code into another file and have the form action be that file and have it redirect when need be? I know keeping it in with the HTML is the worst way to do it. But is it better to include() or just change the action.Also. I have a chunk of variables that are needed for each page. I saved them into an external file and used include() on each file that needed it. Is that a good practice?

Link to comment
Share on other sites

I edited my index.php page and hopefully made the code as clean and effective as possible. Here's what it looks like:

<?php$page = 'index.php';include('PHP_Files/connect.php');$clubupdates = mysql_query("SELECT * FROM news WHERE NewsType = '1' ORDER BY MsgID DESC LIMIT 1");while($row = mysql_fetch_array($clubupdates)) {	$clubupdate = '<p>' . $row['Title'] . '</p>';	$clubupdate .= '<p>By: ' . $row['Username'] . ' at ' . date('g:i A \o\n F jS, Y', $row['Time']) . '</p>';	$clubupdate .= nl2br(stripslashes($row['News']));}$siteupdates = mysql_query("SELECT * FROM news WHERE NewsType = '0' ORDER BY MsgID DESC LIMIT 1");while($row = mysql_fetch_array($siteupdates)) {	$siteupdate = '<p>' . $row['Title'] . '</p>';	$siteupdate .= '<p>By: ' . $row['Username'] . ' at ' . date('g:i A \o\n F jS, Y', $row['Time']) . '</p>';	$siteupdate .= '<p>' . nl2br(stripslashes($row['News'])) . '</p>';}?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title><?php echo 'Welcome to Hug Don\'t Mug - ' . $user; ?></title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><script src="JS_Files/mmenu.js" type="text/javascript"></script><script src="JS_Files/menuItems.js.php" type="text/javascript"></script><style type="text/css">div.club {border: 2px solid #000000;		  float: left;		  height: 300px;		  margin-right: 10px;		  overflow: auto;		  padding: 10px;		  text-align: left;		  width: 330px;}div.site {border: 2px solid #000000;		  height: 300px;		  margin-left: 10px;		  overflow: auto;		  padding: 10px 0px 10px 10px;		  text-align: left;		  width: 330px;}p		{margin-top: 0px;}</style></head><body><div class="ads"><h1>Ads here</h1></div><div class="content">	<div class="banner"></div>	<p class="userinfo">Hello <?php echo $user . '! ' . $alert; ?></p>	<div style="padding: 10px;"><?phpif($mode == "usersignup" || $mode == "signup") {	echo '<form action="PHP_Files/signup.php" method="post">';	echo '<div>';	echo '<p>Desired Username: <input type="text" name="username" value="" /></p>';	echo '<p>Desired Password: <input type="password" name="password" value="" /></p>';	echo '<p>Country: ';	echo '<select name="country">';	echo '<option value="Argentina">Argentina</option>';	echo '<option value="AscentionIs">Ascention Island</option>';	echo '<option value="Azores">Azores</option>';	echo '<option value="Bolivia">Bolivia</option>';	echo '<option value="Brazil">Brazil</option>';	echo '<option value="Canada">Canada</option>';	echo '<option value="CapeVerdeIs">Cape Verde Islands</option>';	echo '<option value="Casablanca">Casablanca</option>';	echo '<option value="China">China</option>';	echo '<option value="Columbia">Columbia</option>';	echo '<option value="Egypt">Egypt</option>';	echo '<option value="FalklandIs">Falkland Islands (Islas Malvinas)</option>';	echo '<option value="France">France</option>';	echo '<option value="FrPoly">French Polynesia</option>';	echo '<option value="Germany">Germany</option>';	echo '<option value="India">India</option>';	echo '<option value="Iran">Iran</option>';	echo '<option value="Iraq">Iraq</option>';	echo '<option value="Ireland">Ireland</option>';	echo '<option value="Japan">Japan</option>';	echo '<option value="Liberia">Liberia</option>';	echo '<option value="MarchallIs">Marshall Islands</option>';	echo '<option value="Mexico">Mexico</option>';	echo '<option value="MidwayIs">Midway Islands</option>';	echo '<option value="NKorea">North Korea</option>';	echo '<option value="Norway">Norway</option>';	echo '<option value="Portugal">Portugal</option>';	echo '<option value="Russia">Russia</option>';	echo '<option value="Samoa">Samoa</option>';	echo '<option value="SAfrica">South Africa</option>';	echo '<option value="SKorea">South Korea</option>';	echo '<option value="Spain">Spain</option>';	echo '<option value="StHelena">St. Helena</option>';	echo '<option value="Sweden">Sweden</option>';	echo '<option value="Taiwan">Taiwan</option>';	echo '<option value="UK">United Kingdom</option>';	echo '<option value="US" selected="selected">United States</option>';	echo '<option value="Venezuela">Venezuela</option>';	echo '</select>';	echo '<p style="font-size: 8pt;">Is your country not listed? Sign up under any country and send a message to an	administrator once you\'re in, letting us know. All we need to know is your username and the country you\'re from and	we\'ll make the adustments for you, as well as add the country to the menu.</p>';	echo '<p>Time Zone: ';	echo '<select name="timezone">';	echo '<option value="-12">(GMT - 12:00 hours) Enewetak, Kwajalein</option>';	echo '<option value="-11">(GMT - 11:00 hours) Midway Island, Samoa</option>';	echo '<option value="-10">(GMT - 10:00 hours) Hawaii</option>';	echo '<option value="-9.5">(GMT - 9:30 hours) French Polynesia</option>';	echo '<option value="-9">(GMT - 9:00 hours) Alaska</option>';	echo '<option value="-8">(GMT - 8:00 hours) Pacific Time (US & Canada)</option>';	echo '<option value="-7">(GMT - 7:00 hours) Mountain Time (US & Canada)</option>';	echo '<option value="-6">(GMT - 6:00 hours) Central Time (US & Canada), Mexico City</option>';	echo '<option value="-5">(GMT - 5:00 hours) Eastern Time (US & Canada), Bogota, Lima</option>';	echo '<option value="-4">(GMT - 4:00 hours) Atlantic Time (Canada), Caracas, La Paz</option>';	echo '<option value="-3.5">(GMT - 3:30 hours) Newfoundland</option>';	echo '<option value="-3">(GMT - 3:00 hours) Brazil, Buenos Aires, Falkland Is.</option>';	echo '<option value="-2">(GMT - 2:00 hours) Mid-Atlantic, Ascention Is., St. Helena</option>';	echo '<option value="-1">(GMT - 1:00 hours) Azores, Cape Verde Islands</option>';	echo '<option value="0">(GMT) Casablanca, Dublin, London, Lisbon, Monrovia</option>';	echo '<option value="1">(GMT + 1:00 hours) Brussels, Copenhagen, Madrid, Paris</option>';	echo '<option value="2">(GMT + 2:00 hours) Kaliningrad, South Africa</option>';	echo '<option value="3">(GMT + 3:00 hours) Baghdad, Riyadh, Moscow, Nairobi</option>';	echo '<option value="3.5">(GMT + 3:30 hours) Tehran</option>';	echo '<option value="4">(GMT + 4:00 hours) Abu Dhabi, Baku, Muscat, Tbilisi</option>';	echo '<option value="4.5">(GMT + 4:30 hours) Kabul</option>';	echo '<option value="5">(GMT + 5:00 hours) Ekaterinburg, Karachi, Tashkent</option>';	echo '<option value="5.5">(GMT + 5:30 hours) Bombay, Calcutta, Madras, New Delhi</option>';	echo '<option value="5.75">(GMT + 5:45 hours) Kathmandu</option>';	echo '<option value="6">(GMT + 6:00 hours) Almaty, Colombo, Dhaka</option>';	echo '<option value="6.5">(GMT + 6:30 hours) Yangon, Naypyidaw, Bantam</option>';	echo '<option value="7">(GMT + 7:00 hours) Bangkok, Hanoi, Jakarta</option>';	echo '<option value="8">(GMT + 8:00 hours) Hong Kong, Perth, Singapore, Taipei</option>';	echo '<option value="8.75">(GMT + 8:45 hours) Caiguna, Eucla</option>';	echo '<option value="9">(GMT + 9:00 hours) Osaka, Sapporo, Seoul, Tokyo, Yakutsk</option>';	echo '<option value="9.5">(GMT + 9:30 hours) Adelaide, Darwin</option>';	echo '<option value="10">(GMT + 10:00 hours) Melbourne, Papua New Guinea, Sydney</option>';	echo '<option value="10.5">(GMT + 10:30 hours) Lord Howe Island</option>';	echo '<option value="11">(GMT + 11:00 hours) Magadan, New Caledonia, Solomon Is.</option>';	echo '<option value="11.5">(GMT + 11:30 hours) Burnt Pine, Kingston</option>';	echo '<option value="12">(GMT + 12:00 hours) Auckland, Fiji, Marshall Island</option>';	echo '<option value="12.75">(GMT + 12:45 hours) Chatham Islands</option>';	echo '<option value="13">(GMT + 13:00 hours) Kamchatka, Anadyr</option>';	echo '<option value="14">(GMT + 14:00 hours) Kiritimati</option>';	echo '</select>';	echo 'Daylight Savings Time?';	echo '<input type="radio" name="dst" value="yes" /> Yes ';	echo '<input type="radio" name="dst" value="no" /> No</p>';	echo '<p style="font-size: 8pt;">DST can be changed in Account Settings at any time.</p>';	echo '<input type="submit" name="submit" value="Sign Up" />';	echo '</div>';	echo '</form>';}elseif($mode == "userlogin" || $mode == "login") {	echo '<form action="login.php" method="post">';	echo '<div>';	echo '<p>Username: <input type="text" name="username" value="" /></p>';	echo '<p>Password: <input type="password" name="password" value="" /></p>';	echo '</div>';	echo '</form>';}else {?>	<div style="text-align: center;">	<p style="text-align: left;">Welcome to the Official O.R.O. Website. As of right now, there's not much to it. But our	goal is to become one big, happy, anime-loving family with members from all over the world! Yaaaaaaay!!!!</p>	<img src="Images/paradas.jpg" />	</div>	<div style="float: left;">		<h2 style="text-align: center;">Latest Club Update/News</h2>		<div class="club">			<?php echo $clubupdate; ?>		</div>	</div>	<div>		<h2 style="text-align: center;">Latest Site Update/News</h2>		<div class="site">			<?php echo $siteupdate; ?>		</div>	</div>	<p style="text-align: center;"><a href="news.php">More Updates</a></p><?php}mysql_close($link);?></div></body></html>

If there's a better way to write anything, please let me know.I tried validating, but I get this error: Sorry, I am unable to validate this document because its content type is application/force-download, which is not currently supported by this service.The Content-Type field is sent by your web server (or web browser if you use the file upload interface) and depends on its configuration. Commonly, web servers will have a mapping of filename extensions (such as ".html") to MIME Content-Type values (such as text/html).That you received this message can mean that your server is not configured correctly, that your file does not have the correct filename extension, or that you are attempting to validate a file type that we do not support yet. In the latter case you should let us know that you need us to support that content type (please include all relevant details, including the URL to the standards document defining the content type) using the instructions on the Feedback Page.

Link to comment
Share on other sites

you call echo alot of times, eveytime u call echo it sends the data to the output (unless u use some outputbuffering thing)so instead ofecho 'this';echo 'that';echo 'something';try:echo 'this'.'that'.'something';

Link to comment
Share on other sites

You can also use a heredoc for all that.

echo <<< EOT<form action="PHP_Files/signup.php" method="post"><div><p>Desired Username: <input type="text" name="username" value="" /></p><p>Desired Password: <input type="password" name="password" value="" /></p><p>Country:<select name="country"><option value="Argentina">Argentina</option><option value="AscentionIs">Ascention Island</option><option value="Azores">Azores</option><option value="Bolivia">Bolivia</option><option value="Brazil">Brazil</option><option value="Canada">Canada</option><option value="CapeVerdeIs">Cape Verde Islands</option><option value="Casablanca">Casablanca</option><option value="China">China</option><option value="Columbia">Columbia</option><option value="Egypt">Egypt</option><option value="FalklandIs">Falkland Islands (Islas Malvinas)</option><option value="France">France</option><option value="FrPoly">French Polynesia</option><option value="Germany">Germany</option><option value="India">India</option><option value="Iran">Iran</option><option value="Iraq">Iraq</option><option value="Ireland">Ireland</option><option value="Japan">Japan</option><option value="Liberia">Liberia</option><option value="MarchallIs">Marshall Islands</option><option value="Mexico">Mexico</option><option value="MidwayIs">Midway Islands</option><option value="NKorea">North Korea</option><option value="Norway">Norway</option><option value="Portugal">Portugal</option><option value="Russia">Russia</option><option value="Samoa">Samoa</option><option value="SAfrica">South Africa</option><option value="SKorea">South Korea</option><option value="Spain">Spain</option><option value="StHelena">St. Helena</option><option value="Sweden">Sweden</option><option value="Taiwan">Taiwan</option><option value="UK">United Kingdom</option><option value="US" selected="selected">United States</option><option value="Venezuela">Venezuela</option></select><p style="font-size: 8pt;">Is your country not listed? Sign up under any country and send a message to anadministrator once you're in, letting us know. All we need to know is your username and the country you're from andwe'll make the adustments for you, as well as add the country to the menu.</p><p>Time Zone:<select name="timezone"><option value="-12">(GMT - 12:00 hours) Enewetak, Kwajalein</option><option value="-11">(GMT - 11:00 hours) Midway Island, Samoa</option><option value="-10">(GMT - 10:00 hours) Hawaii</option><option value="-9.5">(GMT - 9:30 hours) French Polynesia</option><option value="-9">(GMT - 9:00 hours) Alaska</option><option value="-8">(GMT - 8:00 hours) Pacific Time (US & Canada)</option><option value="-7">(GMT - 7:00 hours) Mountain Time (US & Canada)</option><option value="-6">(GMT - 6:00 hours) Central Time (US & Canada), Mexico City</option><option value="-5">(GMT - 5:00 hours) Eastern Time (US & Canada), Bogota, Lima</option><option value="-4">(GMT - 4:00 hours) Atlantic Time (Canada), Caracas, La Paz</option><option value="-3.5">(GMT - 3:30 hours) Newfoundland</option><option value="-3">(GMT - 3:00 hours) Brazil, Buenos Aires, Falkland Is.</option><option value="-2">(GMT - 2:00 hours) Mid-Atlantic, Ascention Is., St. Helena</option><option value="-1">(GMT - 1:00 hours) Azores, Cape Verde Islands</option><option value="0">(GMT) Casablanca, Dublin, London, Lisbon, Monrovia</option><option value="1">(GMT + 1:00 hours) Brussels, Copenhagen, Madrid, Paris</option><option value="2">(GMT + 2:00 hours) Kaliningrad, South Africa</option><option value="3">(GMT + 3:00 hours) Baghdad, Riyadh, Moscow, Nairobi</option><option value="3.5">(GMT + 3:30 hours) Tehran</option><option value="4">(GMT + 4:00 hours) Abu Dhabi, Baku, Muscat, Tbilisi</option><option value="4.5">(GMT + 4:30 hours) Kabul</option><option value="5">(GMT + 5:00 hours) Ekaterinburg, Karachi, Tashkent</option><option value="5.5">(GMT + 5:30 hours) Bombay, Calcutta, Madras, New Delhi</option><option value="5.75">(GMT + 5:45 hours) Kathmandu</option><option value="6">(GMT + 6:00 hours) Almaty, Colombo, Dhaka</option><option value="6.5">(GMT + 6:30 hours) Yangon, Naypyidaw, Bantam</option><option value="7">(GMT + 7:00 hours) Bangkok, Hanoi, Jakarta</option><option value="8">(GMT + 8:00 hours) Hong Kong, Perth, Singapore, Taipei</option><option value="8.75">(GMT + 8:45 hours) Caiguna, Eucla</option><option value="9">(GMT + 9:00 hours) Osaka, Sapporo, Seoul, Tokyo, Yakutsk</option><option value="9.5">(GMT + 9:30 hours) Adelaide, Darwin</option><option value="10">(GMT + 10:00 hours) Melbourne, Papua New Guinea, Sydney</option><option value="10.5">(GMT + 10:30 hours) Lord Howe Island</option><option value="11">(GMT + 11:00 hours) Magadan, New Caledonia, Solomon Is.</option><option value="11.5">(GMT + 11:30 hours) Burnt Pine, Kingston</option><option value="12">(GMT + 12:00 hours) Auckland, Fiji, Marshall Island</option><option value="12.75">(GMT + 12:45 hours) Chatham Islands</option><option value="13">(GMT + 13:00 hours) Kamchatka, Anadyr</option><option value="14">(GMT + 14:00 hours) Kiritimati</option></select>Daylight Savings Time?<input type="radio" name="dst" value="yes" /> Yes<input type="radio" name="dst" value="no" /> No</p><p style="font-size: 8pt;">DST can be changed in Account Settings at any time.</p><input type="submit" name="submit" value="Sign Up" /></div></form>EOT;

Link to comment
Share on other sites

Which one is better? Meaning more efficient and less likely to break at any point in time? I have it set up like Wander's now, but I'll gladly change it. I've only got like 5 or 6 pages that use echo so it's not like it'll be a big deal. I just want efficient and correctly written pages. I'll be going to college for this stuff after high school so yeah. Going with as much knowledge and good habits as possible is my goal.

Link to comment
Share on other sites

So using heredoc, the code looks like this:

<?php//php scripts and codes and suchecho <<< EOT<!------Regular HTML-------->EOT;//more PHP to end the page (clearing sql and closing connections and such)?>

Like that? And you said I can embed variables. You mean like {$variable} <---- that type. Or what?And I would use this for large chunks of output, but just echo little bits? Is this slower than echoing? Or is the difference so small it doesn't matter?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...