Jump to content

Recommended Posts

Are either of these OK depending on circumstance or stupid things I should never do? Is one or the other sensible/idiotic? Is there an obvious 'better' way?

 

I think all the php tags opening and closing within the DIVs is untidy but it's static HTML therefore if there's a LOT of it it's easier on the server right/wrong?

On the other hand, maybe all the open/close of php tags defeats the object.

I'm applying for a web design apprenticeship (I know, I need one) so I'm trying to appear less stupid as much as make nice php.

 

Many thanks in advance, I know I'll end up better off by asking here :)

<?php
 
// php in here

?>
    <div class='content header'>
        <?php include("includes/header.php"); ?>
    </div>
    <div class='content content1'>
        <?php include("includes/intro.php"); ?>
    </div>
    <div class='content content2'>
        <?php include("includes/quals.php"); ?>
    </div>
    <div class='content content3'>
        <?php include("includes/experience.php"); ?>
    </div>
    <div class='content content4'>
        <?php include("includes/hobbies-and-interests.php"); ?>
    </div>
<?php

// More php here

?>

Or this one:

<?php
    print("<div class='content header'>");
        include("includes/header.php");
    print("</div> \r\n <div class='content content1'>");
        include("includes/intro.php");
    print("</div> \r\n <div class='content content2'>");
        include("includes/quals.php");
    print("</div> \r\n <div class='content content3'>");
        include("includes/experience.php");
    print("</div> \r\n <div class='content content4'>");
        include("includes/hobbies-and-interests.php");
    print("</div> \r\n");
?>

test.zip

If you're going to use PHP as a template engine, then open and close your tags as necessary as in the first example. That way the HTML is clearly separate and it will be easier to deal with not only as a developer but also for your tools such as the IDE's syntax highlighting, error checking, auto-suggest, etc.

 

If you want to go better, then employ a true template system to separate the PHP code and the HTML code even further. Twig is a nice one that I would recommend.

 

Your second example is poor code in pretty much any situation.

If you're going to use PHP as a template engine, then open and close your tags as necessary as in the first example. That way the HTML is clearly separate and it will be easier to deal with not only as a developer but also for your tools such as the IDE's syntax highlighting, error checking, auto-suggest, etc.

 

If you want to go better, then employ a true template system to separate the PHP code and the HTML code even further. Twig is a nice one that I would recommend.

 

Your second example is poor code in pretty much any situation.

Interesting... I think I am using php to help me standardise my html which might be a template engine. Thinking of it like that might help me a lot, thank you.

What I'm doing now is a single page thing but I'd usually have, in each index.php file, only ONE include for content unique to that page, preceded by one named opener.php and followed by one named closer.php.

opener.php has everything that appears before the content unique to that page, closer.php has everything that comes after it.

So I'm using php to include content in the index.php files AND using php to include all the stuff that makes up the rest of the page structure.

The question of whether the 2nd example is OK came up just because I had to put like 8 includes one after the other.



I kinda like that the 2nd example is not so good,  it makes for tidy html when view source in browser.

By using php includes  you do standardize your scripts and your html pages since you will be using the same code in all places.  As long as the html code in those included files is well-written I suppose you could say you are standardizing. :)

Edited by ginerjm

Ah yes, I am using exactly the same script in all index.php files.

<?php 
	include $_SERVER['DOCUMENT_ROOT'].("/inc/structure/decs.php");
	include $dRoot . ("inc/structure/opener.php");
	include("content.php");
	include $dRoot . ("inc/structure/closer.php"); 
?>

decs.php starts with doctype then defines $dRoot so i have shorthand for $_SERVER['DOCUMENT_ROOT']

 

I also put my during-development tools in there temporarily and I've added the error_reporting bit (in your sig). I'm thinking of renaming it to config.php

 

Does that sound sensible & any further suggestions?

 

Edit - just realised they should probably be require_once rather than include

Edited by appobs

So similarly, this JS is bad also? It appears JS has necessary restrictions on stuff similar to include or get_file_contents.

 

I'm writing a CV for view in browser, trying to keep it in one file. base64 images is handy for coloured bullet points, JS is new to me but also very useful for this purpose.

 

(forget what's IN the code, just the fact that JS is writing the whole thing similar to the original question)

document.write("<link href=\"css/1-bare-minimum.css\" rel=\"stylesheet\" type=\"text/css\" /> \
<link href=\"css/devBorders0.css\" id=\"devBorderStylesheet\" rel=\"stylesheet\" type=\"text/css\" /> \
<div class=\"theDeveloperArea\" style=\"background: #f4fef4; border: 1px solid green\"> \
 \
    <span>devBorders: </span> \
        <a href=\"#\" onclick=\"devBorders('css/devBorders1.css');return false;\" >ON</a> \
        <a href=\"#\" onclick=\"devBorders('');return false;\" >OFF</a> \
 \
        <a style=\"float:right;\" href=\"http://validator.w3.org/check?uri=referer\">HTML</a> \
        <a style=\"float:right; margin-right: 3px;\" href=\"http://jigsaw.w3.org/css-validator/check/referer\">CSS</a> \
        <br /> \
 \
        <a href=\"#\" onclick=\"swapStylesheet2('');return false;\" >0 - No stylesheet</a> \
        <a href=\"#\" onclick=\"swapStylesheet2('css/1-bare-minimum.css');return false;\" >1-bare-minimum.css</a> \
        <a href=\"#\" onclick=\"swapStylesheet2('css/2-cv5-style.css');return false;\" >2-cv5-style.css</a> \
        <br /> \
 \
        <span>Note: No cross-browser testing yet!</span> \
    </div>");

To include js you just add the script tag and it's src

<script src="javascript-code.js"></script>

I happen to use a similar php templating as you do in a cms I created.

 

There is dynamic content through the header,toolbars,sidebar and content area.

 

I use an actions and page controller to determine what loads. ( Whitelisting approach)

 

Additionally the individual pages are blocked from direct access.

Providing you do not call a session_start(); on individual pages but only through your index page...Place this the top of each included page.

if(!session_id()){
header("Location: http://".$_SERVER['HTTP_HOST']);
exit;
}

index.php

<?php
//define
$server_host    = "http://" . $_SERVER['HTTP_HOST'];
$document_root  = $_SERVER['DOCUMENT_ROOT'];
$directory_path = dirname(__FILE__) . DIRECTORY_SEPARATOR;
$site_url       = filter_var("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);
if (!empty($_SERVER['QUERY_STRING'])) {
    $query_string = filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_STRING);
    $site_url .= "?" . $query_string;
}
require_once($directory_path . "/includes/session.php");
require_once($directory_path . "/header.php");
require_once($directory_path . "/topbar.php");
?>
   <div id="page-wrap">
        <div id="inside">
        <div id="header">
<!--tabs--> 
<?php
require_once($directory_path . "/actions.php");
?>
       </div>   
<!--sidebar-->
            <div id="right-sidebar">
<?php
require_once($directory_path . "/sidebar.php");
?>
           </div>
<!--main-content-->
            <div id="main-content">               
                       
<?php
require_once($directory_path . "/controller.php");
?>
           </div>
</div>
</div>
            <div style="clear: both;"></div>
<!--footer-->           
            <div id="footer"></div>

<?php
require_once($directory_path . "/footer.php");
?>
           <div style="clear: both;"></div>
       
<p id="spacer"></p>
<br />
</body>

</html>

actions.php

<?php
//page navigation tabs and actions control

//unwanted tabs shown
$unwanted_tabs = array(
    "users_active"
);

//standard tabs
$action_array = array(
    "services",
    "articles",
    "help"
);

//user logged in tabs
$user_action_array = array(
    "account",
    "messages"
);

//admin tabs
$admin_action_array = array(
    "users",
    "users_active"
);

//user tabs if logged in
if ($session->logged_in) {
    $action_array = array_merge($action_array, $user_action_array);
} else {
    $action_array[] = "register";
}

//admin only
if ($session->isAdmin()) {
    $action_array = array_merge($action_array, $admin_action_array);
}

//static tabs
echo "<a class='glass' href='" . $server_host . "'>Home</a>";

//dynamic tabs
foreach ($action_array as $actions) {
    if (!in_array($actions, $unwanted_tabs)) {
        echo "<a class='glass' href='" . $server_host . "/?action=" . $actions . "'>" . ucfirst($actions) . "</a>";
    }
}
?>

controller.php

<?php
/*
actions and page controller
parameter and page inclusion protection
*/

//only allow these GET paramters to pass in code
$allowed_get = array(
    "action",
    "user",
    "id",
    "page"
);

//loop get requests and remove any unwanted ones
if (isset($_GET)) {
    foreach ($_GET as $key => $value) {
        if (!in_array($key, $allowed_get)) {
            unset($_GET[$key]);
        }
    }
}

//default page displayed if all else fails
$page = "home.php";

/*
loop through action array to determine destination
$action_array located in actions.php, if action value is not in the array it won't load
*/
if (isset($_REQUEST['action'])) {
    if (in_array($_REQUEST['action'], $action_array)) {
       
        switch ($_REQUEST['action']) {
            case "home":
                //$page = "home.php";
                header("Location: ".$server_host);
                exit;
                break;
            case "services":
                $page = "articles.php";
                break;
            case "articles":
                $page = "articles.php";
                break;
            case "help":
                $page = "articles.php";
                break;
            case "register":
                $page = "register.php";
                break;
            case "account":
                $page = "account.php";
                break;
            case "messages":
                $page = "message.php";
                break;
            case "users":
                $page = "users.php";
                break;
            default:
                //$page = "home.php";
                header("Location: ".$server_host);
                exit;
        }
       
       
    }
}

//include the page only if it exists
if (file_exists($page)) {
    require_once($page);
} else {
    header("Location: ".$server_host);
    exit;
}
?>

FWIW: I've found that the easiest way to make the code clean when mixing HTML and PHP is to keep the entire page in PHP and echo the output at the bottom:

<?php
// includes, sessions, etc.
// some logic here. call functions, db, set variables, etc.
$a = some text result;
$b = some other div or something;
$c = blah blah;

echo '
<html>
  <div>This is the greatest website ever because ' . $a . ' and yada. ' . $b . '</div>
  <div>Some text div</div>
  ' . $c . '
</html>
';
?>

For me, it makes things much easier to read because there's just one HTML blob. The downside of this of course is inserting all the strings into the blob. The alternative is similar, where you get all the variables at the top and then put raw HTML below the closing PHP, with some <?php echo $a ?> type tags in that. Of course if you're actually using includes as you displayed then using variables isn't as helpful.

If you're going to do a single page with both the HTML and the processing, then the way to structure it would be:

<?php

//All your processing

?>
<html>
 <body>
   <p>Only basic template stuff like <?php echo $variables; ?></p>
 </body>
</html>
All your processing goes at the top. Then you exit PHP mode and have your HTML at the bottom. Within the HTML you do only basic view-relates things like echoing variable, simple conditionals and loops, etc.

 

Enter and exit PHP mode as necessary, don't just echo massive strings of HTML. The only time you might do a string of HTML is if you just need a small tag between two variables, such as <?php echo $name.'<br>'.$email;?>.

 

There is no good reason to be using massive strings of HTML within your code at any point. Keep the HTML separate and out of PHP mode. This makes it much easier to work with both from a developers perspective and a development tool's perspective.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.