where to place the php code? - php

i would like to know your point of view on where to position the PHP code on .php page and why?
a) top of the document
b) just above the html elements where i am going to use it.
thank you.

c) In a different file and use a template engine such as smarty
http://www.smarty.net/
Your life will be beautiful and awesome after smarty.
EDIT : I won't downvote other solutions , but it's a very ugly anti-pattern to mix html code with php, you have good, stable and easy solutions to avoid that, use it now or your website will be a big mess of spaghetti code.

Depends on the purpose.
Database query related posts that determine the contents within the part, I call it before there is any input. Also any type of PHP commands that contain raw header information should be presented before any output is made.
Any content related stuff can be positioned anywhere on the page. PHP code is really everywhere - where ever, and however you want to create the HTML from your PHP dynamically.
My pages usually take this structure:
<?
include 'start.php';
$pagetitle = 'the services we offer (branding, web, print etc.)';
$metatitle = 'Our Creative Services (branding/logo, web, print)';
$scriptinclude = 'whatwedo.js';
include 'header.php'; // contains the <body><head></head><body> and a few more elements to start the header/menubar etc.
?>
<div class="full_grid" id="index_slide">
// content here, mixed with PHP if you like...
</div>
<?
include 'footer.php'; // contains the footer HTML, as well as </body></html> etc. to wrap things up.
?>

I put as much code as I can at the top. And only use php withi HTML where I need loops or output data.
This gives me a better overview of the code and it's easier to work with.

Keep your code and HTML as separate as possible. Have them in entirely separate files where you can.
Your HTML should be as much pure HTML as possible, and your PHP code should contain as little HTML as possible.
Obviously, you're producing a web page, so there will have to be some mixing, but keep it as limited as possible: The only code you should mix in with your HTML should be the one-liners to place specific bits of PHP-generated code into your HTML template.

It completely depends what you're doing with it. Personal preference for me is to create any functions I need at the top and then scatter inline php throughout the document calling the functions at the top of the page.
If something needs calculating and it can be done at the top, it's much easier to read and debug if you keep it all in one place. And keeping this the same throughout all your files will help too. What you could do is just include a config file at the top of the page with any site-wide functions you need too, so you don't have to copy and paste through all your files.

If you are only using one PHP file then definitely put all PHP code at the top, then the HTML below with variables where necessary.
For example, $title = 'Page title'; at the top of the page, then <h1><?=$title?></h1> in the HTML portion of the page.
However a better solution is to have two (or more) files. The main one contains all the PHP logic to grab/process data, while the second one is a "view" file containing mostly HTML. The simply include your view file from the main PHP file.

Related

Best way of loading content that should appear on every page

Until now, I've been using the <iframe> tag to load things like headers/footers/navbars into my webpage. These cause so much hassle though and as I'm about to start building a new site I thought I'd get it sorted now.
I was thinking of having all the html code in a php file and just loading it in dynamically.. Ideally I'd like the code to become a part of the page. So it appears inline. But I also want to be able to edit one single file if I need to change one bit rather than editing the same file 100 times.
<iframe>'s did this well until recently and I don't want to use workarounds to solve my problems. Could someone please post some code I could adapt or post a link to something that tells me how to do this? Cheers
You can use PHP's include() function to include elements like headers and footers in your pages.
So:
include('header.php');
. . . will look for a file called header.php in the same directory and include it in your page. Then you just need to write this at the top of your pages.
That said, this isn't really a very good way to go about designing your site. How about looking for a content management system, that allows you to keep the design and content of your site separate?
Are PHP includes what you're looking for ? http://php.net/manual/en/function.include.php

How to structure php that generates html

I have a php file and a bunch of HTML elements that include:
header
css
a "spacer" element used repeatedly, static
a bunch of templates that will take arguments from the PHP code for what to insert
Basically I'm wondering what the right way to factor all these files in. I'm guessing I should have a file.css in my folder that the php will slurp up into memory and drop in the header information. Should the spacer element be saved as "spacer.html", and the PHP will slurp up one copy of it into a string and drop it into the HTML as necessary? Or should all of these just exist as string constants in the PHP?
It's a little trickier for the dynamic "template" elements because I'm not sure how to separate the HTML and let it have markers that the arguments get dropped into.
You should look into MVC. A popular one right now is CodeIgniter. The idea is you take those HTML "templates" and create (V)iews. PHP uses a (C)ontroller to direct the user and call on (M)odels to fetch data, then send the appropriate variables to the (V)iews for the browser.
I've noticed some of the other answerers (SP) mentioned MVC. MVC is incredibly important because it allows you to separate your business logic from your "view" display/UI layer and your database logic from your business logic.
Like, AlienWebguy, I'd recommend Code Igniter, but there are a number of other good frameworks out there for PHP.
As far as what it appears that you're asking is how you should structure both your view layer and business logic. If I have something common like a header and footer, I'll put them in
view/include/header.php
and
view/include/footer.php
The header file will generally contain the <html> tag, the style sheet link(s), any common javascript script files, and a common header (like the logo and navigation). The footer file will generally contain the copyright info, any footer links, and the </body></html>.
Generally what you should look to do in creating your views effectively is to have them process model objects to display the HTML, and generate absolutely no HTML in your controller layer. E.G.
<table>
<?php
foreach ($users as $user) {
printf('<tr><td>%s</td><td>%s</td></tr>', $user->id, $user->user_name);
}
?>
</table>
Doing that makes things a lot cleaner by avoiding interspersing concerns at the wrong "layer".
The other thing you can do, if you're not interested in writing straight PHP in your views, is you can use a templating engine. Code igniter includes support for (but you don't have to use) a template engine.
I usually suggest using some good ol' php includes to tackle this.
File structure wise, I'd probably have an index.php file -- which (without knowing much about your templates in #4) would outline the page. You could call in the header.html page or put the header right in the index.php file.
The css file would best be named: style.css (this is pretty standard) and you can call that from your header file.
Not sure if you're getting at this, but you can include HTML in a .php file. You'd just name the file something like: index.php and then your code can be:
<p>This is HTML.</p>
<?php echo("This is PHP."); ?>
And intermix them throughout.

HTML VS PHP comparision

Is it better to have HTML files for including as header and footer in a PHP application instead of PHP files?
I usually do something like the following to keep things neat and consistent:
<?php require_once('includes/header.inc.php'); ?>
<!-- Html here -->
<?php require_once('includes/footer.inc.php'); ?>
If your webapp is written in php I see no reason to deviate away from the php extension as you may want to add some dynamic content into the include at a later date.
including as an header and footer in
php application is good
like
index.php
include_once('header.php');
// your code regarding this page
include_once('footer.php');
It depends - if you have static header and footer html is enough. If you need there any kind of dynamic, then php comes to fight.
when you are building just some very simple php web page i suggest using require_once to include basic layout of the page. It doesnt matter if you are including html or other php code and you should know whether you would benefit from php or not.
Also including html is faster then including php code which is just calling many echos or prints.
Provided you use secure PHP code, it does not make a (significant) difference. I would suggest separating the main application concerns from your header and footer files, to avoid placing costly operations which may be unecessarily repeated in these files. Some guidelines to address possible security issues can be found here: http://phpsec.org/projects/guide/.
If you are using kinds of include for inclusion, the file type doesn't matter, the PHP code in it will execute, if there is one. Note that this is also a subtle security concern.
Because of this, I don't think the file type is relevant in this. The real question is what have you got in the footer and the header, e.g. PHP processing, database calls, ...?
I personally think that is better to require_once your php header and php footer. Maybe it is a bit slower thant hmtml (but not very relevant) but this unnecessary "optimization" doesn't worth the certainly needed php functions used in your header like session_start() or mysql_close() in your footer.
My personal point of view though :)
There is nothing better in including HTML
moreover - a real life will tell you that you can't use plain HTML anyway.
I've answered similar question recently, with strong reasoning: Using PHP include to separate site content
This is what I do
index.php
<?php
include_once('header.php');
//Your code goes here
include_once('footer.php');
?>
and yes it is a better practice to use php files as header and footer.

HTML coding and mixing of PHP or JavaScript code

I am assigned a task to revise a website and at present, I am working on index.html page. the previous coder has mixed a lot of JavaScript and CSS code in between and it is becoming difficult to read.
I want to know whether it is necessary to include <script> tags and CSS code in between? What about PHP code? Where each must reside?
Edited:
If multiple JavaScript and CSS files are to be referenced, how to include in a single <script> or <link> tag?
Keep your JavaScript inside a separate file, keep your CSS inside a separate file and have them both referenced from within your HTML. The order of these referenced files relative to the HTML does not matter. As for the PHP, I wouldn't worry too much about it being mixed in with the HTML (just keep your functions, classes and other scripts in separate files and include them with PHP in the header).
If is the same CSS on each page, having an external file that caches help to save bandwidth. If there are different rules intermixed with the HTML for different element types you may have some conflicts, but if you rewrite it, it will end up being a lot cleaner and easier to maintain later.
I like to keep a file structure like so:
index.php
/css
main.css
othercssfiles.css
/javascript
main.js
otherjsfiles.js
/template
header.php
footer.php
/scripts
functions.php
otherscripts.php
Then in my header file, I would place HTML code referencing the files in the CSS and JavaScript directories. And in the root directory my index.php file would include(); the header at the top and the footer at the bottom.
otherjsfiles.js and othercssfiles.css can be used in cases where a single page may have a specific requirement, requiring a lot of CSS and JavaScript that most other pages don't need. It means other pages do not need to fetch unnecessary data and it keeps page specific code separate from the entire site's code.
I have found this an easy way to keep track of various aspects of the code that makes up an HTML page, but naturally, you will find ways to organize it that makes sense to you.
Edited:
If multiple JavaScript and CSS files
are to be referenced, how to include
in a single or tag?
It would be better to combine them into a single file to conserve HTTP requests (which take time). Then you would just include those CSS and JavaScript files like normal.
<script type="text/javascript" src="/javascript/main.js"></script>
<link rel="stylesheet" href="/css/main.css">
Additionally, it seems like you could use the services of a CSS beautifier for readability, a JavaScript beautifier for readability and a JavaScript minifier for when you are done reading it (keep the readable version) and want to save bandwidth. These tools are especially helpful when you are working on maintaining a website you did not create.
Rarely is there a valid reason for CSS be mixed into the HTML - a separate file is generally best.
With JavaScript: there may or may not be a good reason for it being mixed into the code. E.g. if a piece of script is dependant on running after one element of HTML is loaded and before another. This isn't a particularly good coding practice, but if you're updating an existing site you may be stuck with it.
In the end the only way to really tell is to pull it out and make sure the page still works.
As Sam said, keep JavaScript and CSS external, and reference items in the JavaScript by id rather than onclick= etc. Follow Yahoo, and put the CSS in the <head> and the JavaScript before the closing <body> tag.
For multiple JavaScript or CSS, use multiple <script> or <link> tags.
As for PHP, it's good practice to keep as much of the functionality in a separate include file, and just call functions etc. in the main HTML. This will aid maintainability greatly. Aim for simple loops, if/elses, and function calls, and nothing else.
If multiple javascript and CSS files
are to be referenced, how to include
in a single or tag?
You either reference each file using multiple tags or use a minifier like YUI compressor to create a single CSS and JS file from the originals.
The order of CSS styles is relevant, but only relative to other CSS styles. So, start by moving all CSS styling together (in the head section) in the same order as originally. That will make it somewhat less messy while defenitely not changing how the page works.
Then you can start looking at whether you can rearrange scripts and PHP code. What they output to the page directly is relevant, otherwise they can easily be rearranged.
PHP coding allows you to have HTML/CSS interspersed with PHP code by using server tags like <? -php code here -?>.
This is normal - it is very flexible and easy-to-get-started.
Your JavaScript should ideally be placed into a separate JS file and using the <script> HTML tag to reference it. See the docs.
Your CSS should ideally be placed into a separate CSS file and use a <style> HTML tag to reference it. Again, see the docs.

[HTML/CSS/JavaScript/PHP]: In which order code must be written?

While writing code in a file that would comprise of PHP, HTML, CSS & JavaScript, in what order each must appear? What are the best practices for separating the presentation and the logic?
Sometimes external .js and other files are using in the link tag. Where these link tags must appear?
This doesn't answer the question directly but the article that Rasmus Lerdorf (creator of PHP) wrote has some nice examples to follow.
Clean and simple design. HTML should look like HTML. Keep the PHP code in the views extremely simple: function calls, simple loops and variable substitutions should be all you need
http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
most if not all javascript should be external files linked from either the header (between the tags) or all the way at the bottom near the closing tag depending on how youre enhancing the page.
css should never be inline in my opinion. start with external css files linked from the header, and if you must go to the file level. ie.
<head>
<style type="text/css">
/* CSS CODE HERE */
</style>
</head>
as far as php best practices, dont do a database call in your html templates. keep the templates simple php. if's for's to echo out your database results.
Your tags should (must?) go in the head of your page.
There are a handful of exceptions, but most of the time your CSS will be in an external .css file that you'll link like the .js files you mention. The order you need to load your external scripts may depend on their content. For example, if you're using jQuery plugins, you'll need to load the jQuery library before the plugin file.
PHP and HTML will often be intertwined within a document. There are discussions on SO and elsewhere over how HTML should be displayed within PHP (e.g.
?> <!--html goes here--> <?php
or
echo '<p>This is my html</p>';
..but I've never seen a definitive answer to either method. Use whichever makes you file legible.
All of this must be in different files except of very small portions (for example js in html).
The best place for link tag is in head section of html.

Categories