I usually create modular websites, each part of the website being a .php file which will be included in the main pages.
Is it "better" to output HTML within PHP files using echo or to close each time the php tag ?> and open it each time I need to access a PHP function/variable.
V1:
<?php
$v1=$_POST['name'];
echo "Your name is".$v1;
echo $v1." if you want, you can log out";
?>
V2:
<?php $v1=$_POST['name']; ?>
Your name is <?php echo $v1; ?>
<?php echo $v1;?> if you want, you can log out
The thing is that between the php tags there's much more HTML code (echoed) than actual PHP.
Does it affect the script performance if I close the tags each time? And is it safe to acces variables declared in a previous block of php code?
EDIT1:
When closing the php tags isn't the server clearing some cache for that script, or something like that?
I think you can select whatever you want, but you should use it everywhere. For myself, second one is better
Definitely v2. Plus , you additionally should read this one : http://codeangel.org/articles/simple-php-template-engine.html (archive link: http://archive.is/CiHhD).
Using V2 would be better as it wouldn't break the syntax highlighting or code completion in many IDEs, but both of them are as good as the other.
As far as I know, there is no (considerable) difference in performance.
You could also consider using a template engine, however, that does impact performance. The most popular template engine is Smarty, but there are others (some better, some worse) out there.
Related
This is more of a general information question involving endnotes than a "check my code" one. That's because I can find almost no (useful) information on the subject and don't have the skills to create this myself. But I still think it's useful to create a general brainstorm session / forum thread on the net about this.
The issue: I've written about 60 articles, a dozen of them book-length or near book-length on a site that has been manually designed with HTML5, CSS3, jquery and PHP - the latter two mainly with pre-existing code. I'm very happy with it except for one thing: endnotes! It takes forever to update them.
An average article has 120 endnotes (up to 550). It happens frequently, especially during the writing/proofreading process, that I need to add more information or want an additional endnote. That means anywhere from 2 to 30 minutes of copy-pasting "[113]s", "[114]s" around. It's hopelessly inefficient.
Ordinarily I dislike the uninspirational Wiki CMS platforms, but they have one huge benefit: cite.php plugins. Like this one:
https://www.mediawiki.org/wiki/Special:ExtensionDistributor?extdist_name=Cite&extdist_version=REL1_26&extdist_submit=
Once you have this, you just put an URL between <ref> </ref> and an endnotes gets automatically generated below a {{reflist}} tag. It's explained here:
https://en.wikipedia.org/wiki/Help:Footnotes
Footnotes are created using the Cite.php software extension. This
extension adds the HTML-like elements <ref>...</ref>, <references />
and <references>...</references>. The elements are also used in a
number of templates; for example, it is becoming more common to use
{{reflist}} rather than <references /> as it can style the reference
list.
I've checked out the plugin and it, of course, is much more than just a few lines of PHP.
My main question is if anyone is aware if this type of code has been created for custom designed websites. Or if someone has an idea how to program this manually? If it's not too hard, I might try it myself in the near future or hire a programmer.
P.S. I did study HTML5 solutions for endnotes in the past. Can't remember the details, but they were terrible. It's crucial to have one type of tag, with each one generating a new automatic endnote.
{{ }} is not standard HTML tags, but usually in some modern MVC frameworks they are used as replacement for PHP syntax like echo $foodNote which is the same as {{ $foodNote }}.
A MVC framework like Laravel use it as part of blade template.
But in the provided link you have in your question, the {{reflist}} is just referring to the content inside the tags like <ref>Content of the reference</ref>.
The provided Cite.php helper file is parsing the content inside tags like <ref>...</ref> to variable reflist inside a curly braces with the same content.
It should be not very difficult to program such thing.
Here is a simple PHP script to handle footnotes automatically. The only significant caveat is that your web page file name must end in .php or .phtml (not all web servers support .phtml). This is no problem because the web server will treat the file exactly as a .html file, except it watches for PHP tags so it can process the embedded PHP scripts.
Here is the script.
<?php
function footnote($footnote){
global $Footnotes, $FootnoteCount;
$FootnoteCount++;
$Footnotes[$FootnoteCount] = "$footnote";
print "<sup>$FootnoteCount</sup>";
}
function PrintFootnotes(){
global $Footnotes, $FootnoteCount;
for($i = 1;$i < $FootnoteCount + 1;$i++){
print "<sup>$i</sup>$Footnotes[$i]<br />";
}
}
?>
You can put the script at the top of each page.
Better yet, save the script in a file named FootnoteFunctions.php. Of course, you can name it what you want or put it in a file with other functions. Just change the following include as appropriate. Next, put the following in the head of your HTML document:
<?php include("FootnoteFunctions.php"); ?>
Put this where you want the footnotes to appear at the bottom of the page:
<?php PrintFootnotes(); ?>
To create a footnote insert the following where you want the footnote number in the text (with your text between the quotes):
<?php footnote("footnote text here") ?>
That's it.
You can embellish the script as desired. For example, to pop up the footnote text as a tooltip, add title="$footnote" to the tag. You can also put a table tag, etc, in the printing function to make the footnote numbers and text line up nicely.
Here is my page explaining line by line how the script works. It also has an embellished version with the features mentioned above.
https://vocademy.net/textbooks/WebDatabase/Footnotes/PageSetup.php?Page=3&CourseDirectory=WebDatabase
I am building my website completely in PHP. I am trying to make it as much flexible as possible.
I have seen there are some softwares made in PHP that are able to get a HTML page, and before showing it, the PHP code recognizes the code inside brackets {PHP Code} as PHP code, runs it and only then shows the final page.
<h1>Hi My Name is {echo $name}</h1>
How can I achieve the same? I know there is Smarty Code. But I do not want to learn Smarty, I just want to know how to check a HTML page with PHP, find every bracket and threat that as PHP before showing the page..?
Can you point me somewhere?
Are you looking for PHP's basic syntax?
If you enable short_open_tags (it usually is enabled by default), this will work:
<h1>Hi My Name is <?=$name?></h1>
otherwise, this will always work:
<h1>Hi My Name is <?php echo $name; ?></h1>
PHP is already a templating language - there often is no need to add another layer of templating on top of it.
I want to keep the template files separated from the php engine
In fact, you don't
Your template files would behave as native PHP files in every way.
So, there is asolutely no [logical] reason to prefer such a strange solution over native PHP.
use the php tags for the echo statement.
<h1>Hi my name is <?php echo $name; ?></h1>
Well, just point apache to index.php which includes phtml templates into itself. Use <?php ?> instead of { }.
I have a big page with much spaghetti code. I'm not sure which solution is faster for the server.
The first solution
<div> ... many html code ....
<?
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
echo "<div style=\"cursor:pointer;\">$firstHit </div>";
}
?>
... many html code .... </div>
this solution ( I use ' instead of " )
<?
// many php code
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
}
// one echo with all html code
echo "<div> ... many html code ....
<div style='cursor:pointer;'>$firstHit </div>
... many html code .... </div>";
?>
or this solution
<?
// many php code
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
}
// one echo with all html code
echo "<div> ... many html code ....
<div style=\"cursor:pointer;\">$firstHit </div>
... many html code .... </div>";
?>
Practically, it doesn't really matter. What matters is that your code is maintainable and clean. You should look into using a PHP framework like CodeIgniter or CakePHP to make your code more well-structured.
You should have as little HTML inside PHP echo/print statements as possible; it is good to close PHP tags and just have the natural HTML. This is because the parser won't travel through the echo/print statement and and parse it. Thus, your first solution is certainly the best in terms of speed.
Of the solutions presented, I would say that the first is probably best. General rule is that you should put as much into strait HTML as possible. This is both for the developer's sake as well as the server's. Stuff outside of <?php ?> is basically raw data which, while it still needs to be parsed on some level, can basically be served to the user straight up.
If anything, you may want to refine it further:
<!-- as a note: in all of your examples except the first, this div exists.
In the first it only exists if the isset returns true. -->
<div style="cursor:pointer;">
<php?
if(isset($ubo['day']['xxl']['0']))
{
echo $ubo['day']['xxl']['0']['title'];
} ?>
</div>
You also could probably optimize through storing $ubo['day']['xxl'] in some local variable elsewhere on the page.
Do you have performance problem ? If no don't bother about "better for the server" and do "better for your code" instead.
And i'd say that all this is the same, most of the performance are due to I/O (sql query/web service, hard disk) not syntax details.
So do the best code for yourself you'll see later about performance.
The second solution might be faster than the first, because you are sending the content only once and it also looks a little better (PHP is more separated from HTML).
However performance difference between all 3 solutions will be very small and you really should't put attention to it.
Follow the hint "premature code optimization is evil" :-) I dont think that it makes a (big) difference what you use in your given code. It would be much better to have a clean code separation in mvc. Then you can use a template engine which supports caching for your massive html code and there's no need to output it every time with an echo! Besides this performance optimization has much more effect on DB-issues, your general code structure and the code at client side. For example, avoid inline css styles to reduce transferred html code.
do you use PHP opcode cache?
do you use memcached for generated subpages?
have you optimized your database queries?
do you use icongroup images? do you compress JS and CSS?
have you really run out of all the low hanging fruits?
I am just wondering if its normal to embed PHP in the HTML, or is it considered dirty/unprofessional. For example consider following lines:
<? if($photo == 0) { ?>
<div class ="reminder">Hey <?=$name;?>, You don't have any photo. </div>
<? } else { ?>
<div class ="ok">Do you want to change your photo? </div>
<? } ?>
Is this kind of code ok? How the similar work can be done in a clean/professional way (without PHP frameworks? )
Thanks.
As long as you keep the logic of your program outside the html, it is ok. You need to mix it in your templates, for example. Template-engines like smarty replace the {$myVar} with < ? php echo $myVar; ? > (simply spoken), so it is not possible to avoid it completely. But things like
<?php
include "db.php";
connect_db();
// check login
echo "< html >< head><body>...";
?>
is NOT good practice, because you mix everything together: program logic (login-check, db-stuff) and output (echo html). Just have a look at the MVC and keep the "separation of concerns" in mind.
Your example looks ok because you have only that logic in your html which is needed to control the output directly. But calculating the value of $photo, depending on a db entry for example, would NOT be good in your html, because this is program logic. Output (HTML) and logic should be devided all the time.
It's very normal, whether it's good or not is a completely separate topic. It's really all about the size of your project and your requirements for maintainability/flexibility.
If it's a small project, just do what you have to in order to get it done. However a point exists at which it becomes unwieldy to develop without a framework. This is all very subjective and varies from project to project, but this is the general principle.
It's OK to use PHP in templates but many people prefer to work with a templating language because it forces separation and ensures you don't litter your templatse with loads of PHP. If you do go down the template route Twig and Smarty are quite good since they compile the template into PHP which speeds things up.
If you're writing PHP in your templates try to follow some best practise coding standards to keep things neat. For example:
Use full <?php tags for compatibility.
When writing any loops instead of curly braces use colons. To end the statement you need to explicitly write it as endforeach/endif/endwhile/etc. This makes PHP templates more readable.
If you have a lot of logic move this into an external PHP file to keep the PHP in your template short and readable
If there is only one PHP statement in your PHP tag you don't need to end it with a semi-colon. Again, helps readability
An example:
<?php if ($photo == 0): ?>
<div class ="reminder">Hey <?php echo $name ?>, You don't have any photo.</div>
<?php else: ?>
<div class ="ok">Do you want to change your photo?</div>
<?php endif ?>
See more at:
http://www.php.net/manual/en/control-structures.alternative-syntax.php
http://framework.zend.com/manual/en/coding-standard.overview.html
for that you can use smarty templete .... it improves your coding style and works fast ... visit smarty and try it, it's really awesome
From what I have read either will work, but most people just use the echo statements for small, conditional html.
I try to keep this at a minimum, because i find it harder to debug it with all the
< ? } ?>
flowing around in the code (wordpress theme gurus does this alot)
There will be many opinions about this. Mixing HTML and PHP can become very messy, but this looks fine. Many professionals work just this way. If it works for you, it's good.
To make it more readable, I tend to keep the brackets on separate lines, just so you can be sure to be able to find them all easily, but thats just me.
there was an answer from guy named alexn
Dunno why did he delete it, it's looks best answer to me, so, I am only reproducing it:
I would say that's the way to go. You
have a nice, clean separation of PHP
and HTML.
Here's another option:
<? if($photo == 0): ?>
<div class ="reminder">Hey <?=$name?>, You don't have any photo. </div>
<? else: ?>
<div class ="ok">Do you want to change your photo? </div>
<? endif ?>
I have blocks of HTML code in a MySQL database and my framework needs to print these within a PHP template which will be outputted to the browser. To do so I make this call:
</tr>
<!-- Section 3 -->
<?php echo SIN_SiteView::get('section3') ?>
<tr>
Which gets the code either from the APC or MySQL, now the code it obtains looks like this:
<td height="280" colspan="2" bgcolor="#00abd2">
<a href="#">
<img src="<?php echo SIN_Utilities::l("image", "home_flash.png")?>" width="710" height="280" border="0" />
</a>
As you can see I need to run all images through a method known as "l" which I use to easily change images paths. Now the issue is if I echo that block of code it will simply be echoed as a string and not work.
I tried surrounding the php with '. [code] .' and removing the php but that also did not work. Does anyone have any ideas on how I could properly echo this to the page.
Thanks.
UPDATE: I think I need to be using the eval() command thanks to some of the comments, I simply do not understand how to implement it in my situation. Any simple examples would be greatly appreciated, for example how do I change this line:
<?php echo SIN_SiteView::get('section3') ?>
To echo the entire block featured above, thanks again.
I think you want eval rather than echo. See this slightly different question.
My solution would be to eval '?>'.$myhtml.'<?php'.
Is the marketing team adding the php code to the html you are storing?
If not, maybe you could change your <?php echo FUNCTION() ?> into #FUNCTION() and evolve your SIN_SiteView::get() into your own templating interpreter?
I agree with cHao though; it would probably be easier to adopt one of the templating packages out there and convert your data over.
You'll need to use eval to evaluate the inline PHP. However, this is potentially quite risky (eval is evil, etc.), especially if any of the content that's being fetched is user sourced.
e.g.: At the very least, what's the stop the user inlining...
<?php die(); ?>
...within the content they enter.
As such, you'll need to take a great deal of care, if there's really no alternative to this approach.
Some updates:
If you're new to PHP I'd recommend having a re-think. Chances are there's no need to use eval. (Unless there's a dynamically customised content on a per-user basis then you don't need it.) What are you trying to achieve?
What specific error/problem are you having? (I presume you're using var_dump or print_r for debug purposes, etc.) As the content you need to eval isn't pure PHP (it's HTML with PHP in) you'll need to embed the PHP close and (re-)open tags as #Borealid illustrated.