Performance with PHP reading - php

I actually ran into a problem today. I have got a site where multiple pages have the same layout. Today I had to change a thing on this layout and had to change every single page. This made me think about solutions for this.
So, my question:
Would the performance and loading speed of the website be affected if I had the layout HTML in one single file and read it using PHP on every page? This would make it a lot easier for me, since I only had to change the layout in that single file.
Also, how should I read this file. At the moment, I would use the following code:
for ($count=0; $count < $dirAmount; $count++) {
$path = " //path\\ ";
$fileText = split("--", file_get_contents($path));
echo " //code\\ "
unset($fileText);
}
But would there be a faster way?
BTW, if this is too trivial, please note. I couldn't find much other information that actually was clear enough to help.

Simply use php's include or require to include the file.
It will affect performance a little bit, but that tiny little performance cost is insignificant compared to the ease of having one file you can use in multiple places.
One suggestion would be to use full file paths on include/require statements. Normalizing a relative file path can be expensive; giving PHP the absolute path (or even “./file.inc”) avoids the extra step. - Source

I would suggest you consider using smarty or twig if you want to start using templates for your website. Those engines optimize page loads by pre-caching pages and optimizing them to load as quickly as possible.
As for your original question, no, especially if the file was called repeatedly by the entire website, it would most likely get cached into RAM and load pretty fast since it was being called often. As Cerbus mentioned, using include or require would probably be the fastest way to process the files.

Related

Removing HTML duplicated code: Monolithic file vs Separate files

Continuing this question What is the best way to manage duplicate code in static HTML websites ...
I'm starting to create PHP variables for each chunk of duplicated HTML code. My website is divided into themes and each theme has its duplicated code. I have the option to:
save all variables into a single PHP file, and then include it at the beginning of each HTML page (even if the page only uses one or two of those variables);
create a PHP file for each "theme" and include at least two PHP files at each HTML (one with the common variables and other with the specific variables.
Which one is faster? Including several small PHP files increase the page's loading time? I think the "non-monolithic" version is easier to maintain... I just need to know if I'm sacrificing performance.
I just need to know if I'm sacrificing performance.
Except that you don't. This is premature optimization. Go for the one that maximizes maintainability and ease-of-programming.
I'd go with one file including all the necessary files or themes, that makes maintenance a lot simpler. If you mean faster to develop, that's also the one to go for.
I wouldn't worry about the performance. Your site is never going to be as slow including files you don't use as some of the frameworks out there.

Does PHP Include make your code faster?

I have an ad network script like the following
http://cdn.domain.com/ad.php?variables=etc
We have about 10,000 hits a second and we are looking at some improvements for our Pseudo code - this is what I have in mind - my question is - would PHP includes slow down my script like the if else codes and would it be worth minifying the PHP on this page:
<?php
// mysql connect
// get variables from publisher
// if publisher has no ads show advertise here banner
// if resolution from variables is 125x125 show that banner or whatever resolution from the vars
// example www.noadhere.com/image/advertishere_{var}125px.jpg
// if publisher has no ads show advertise here banner and also updated mysql with page views for this publisher
// if publisher has a banner then show it and update mysql with page views
// show also the click code that redirects and updates the record with a hit click
?>
I have updated the code. This is the Phase 1 draft for those who are interested. I think it is so much simpler and I am going to minify this - even though there may not be need - we had 4 mysql actions happening. And now there are 3 - I just made the update views a one liner.
# mysql
$c=mysql_connect("sqlmaster.adserver.com","user","************");
mysql_select_db("adserver", $c);
# vars
$a=mysql_real_escape_string($_GET["z"]);//id
$z=mysql_real_escape_string($_GET["z"]);//zone
$h=mysql_real_escape_string($_GET["h"]);//height
$w=mysql_real_escape_string($_GET["w"]);//width
$d=date("Y-m-d H:i:s");//date
$u=mysql_real_escape_string($_SERVER['HTTP_REFERER']);//url
# constructor
# do we have ads?
$r1=mysql_query("");
if(mysql_affected_rows()==0){
# empty ad code unit
echo 'Blog Empty';
} else {
# we have ads - so show random click code
echo 'Click here .php ? and redirect';
}
# update mysql view table for this ad unit - empty or filled
$r2=mysql_query("");
# end constructor
mysql_close($c);
Any suggestions on improving this would be welcomed. I think the mysql_real_escape is slow.
Using include only slows down your script by the amount of time it takes your server to open the file, which is usually just a fraction of a second. So it wouldn't drastically slow down your script execution.
When using a PHP cache, includes really don't matter that much. However, there definitely is a very minor difference.
My own build scripts automatically replace includes with "normal" code, using a self-made syntax that's backwards compatible with PHP:
/*safeinclude*/ include 'file.php';
My parser then reads the PHP file and notices this include. It grabs the contents of the file.php file and replaces the include with this code (after some cleanup, such as removing the leading <?php tag). It then gets saved to the bin directory, which is where the live files are.
This approach works very well, but you must always check for the <?php and ?> tags. Also, you'd have to split src and bin directories, because you can't change anything that's already live anymore.
Your primary focus area for optimizations should probably be the database though, and other CPU-intensive operations such as loops.
There are lots of ways of making code run faster. Usually splitting code into separate files will not improve performance (selectively including just the code you need instead of a huge library will probably help).
You may have noticed that there aren't a lot of off-the shelf solutions for minifying PHP code - there's a good reason for that. It won't make a lot of difference to the execution time (it does for javascript mainly due to the reduction in network transfer time - not in the reduction in parsing time). PHP code doesn't go across the network. And if you want to reduce parsing time, then using an opcode cache is a much effective solution.
Since this is presumably a significant revenue stream, then you should have the skills to know this already. However a lot of performance improvements come about by trial and error (and careful experiment design and measurement) - you might want to invest some time in developing these facilities.
The good thing about running if and else's is that only the code that is needed to be ran will run. Included pages are loaded in a split of a second and do not really make any difference on the speed. Most big websites have long trails of included files and you don't really notice it.

Any problem if i will have only index.php instead of

i am trying to create a website, a dynamic one.
i wanted to know if is any problem if i will not divide the index.php file, so it will have the header , footer, sidebar etc, in one file. is any thing wrong here? So instead having, header.php, index.php, footer.php, sidebar.php, i will create only index.php..
need some suggestions from experts please
Thank you for reading this post.
absolutely nothing wrong. well. at the start.
you'll have issues with maintainability of that single file later when it gets bit. if you're planning to grow big.
No there is nothing wrong in that approach, it might be a pain to maintain though.
It's almost always a good idea to split things up this. My typical "simple" site layout has a header, a footer, and a body, each with its own files. It's rare for more than a couple pages to have different headers/footers, so almost every page ends up looking like:
<?php include('header.inc'); ?>
body goes here
<?php include('footer.inc'); ?>
And the header/footer files boil down to <html><body> and </body></html> respectively (with all the usual css/javascript/meta/headers, etc... of course).
Nothing wrong with keeping everything in a single file, but then you'd have to hard-code your menus/sidebars/footers/headers/etc... into every PHP file.
You need not any additional files.
This files are used only for easy edit, more obvious struct and having main code in different pages
I think it's great. Since your PHP-processor only needs to interpretet 1 file (instead of 4), it'll probably go a lot faster (when you are not using any OP code compiler).
Segregating your code is good practice as it helps prevent duplicate code. Say you want page2.php and you need the same header, footer, sidebar, etc. Are you going to copy/paste in that code? Just make your template views like they're supposed to and piece together your structure for optimal code redundancy avoidance.
If you NEVER plan on scaling this project, one page is fine.
While there is nothing wrong theoretically, this is by definition a bad practice.
By separating functional / organisational wholes into different files / classes / modules, you achieve decoupling and get a larger control level over your application, it will be much easier to maintain, you wont have to harcode and copy/paste much etc...
Why would you want to put all of your code into a single file?

Approach including a Footer in every page using php

Hey all. i was wondering what is the best practice to include a footer
in all of my pages. i mean i have about 1000 of them. should i use the
php "include" function: include 'static_footer.html' or is it a bad practice ?
If you have 1000 .php file pages, you may want to look into using an Model-View-Controller solution (like storing the page information in a database and using Code Igniter or something similar to display the information), or a Content Management System of some description.
But, as far as I know, your best bet would be to use the include() function.
include 'footer.php';
There is always the option of using the auto_append_file directive in php.ini to automatically include a file rather than modifying every single page
I believe it is perfectly fine to use an include function. This way, you'll be mimicking a sort of template engine, and it is a good way to avoid using the same code over and over again.
I would say that is definitely a good idea, as it helps adhere to the DRY principle.
Depending on your scenario, it might be worth looking at some php_value setting in a .htaccess file (if you're in a web environment). You can auto_prepend a file to the output, which would save you adding an include statement to every file. This might not suit your needs, but for simple applications, it can.

Best way to create a "template interpreter" in PHP

I'm hosting a multi area solution written in PHP, and each customer has its own template in some HTML files. Now I want these users to be able to use some chunks of dynamic content, but they can't be able to use PHP. I thought something like:
In the HTML file, if I put this:
<ul>[menu-list]</ul>
Will output something like:
<ul><li><a[...]>Home</a></li><li><a[...]>About</a></li>[...]</ul>
Is there any better way of doing it than keep parsing and caching files via file_get_contents() and preg_match_all()?
I want to create about 20 entries like [menu-list], and parsing every file for all of them seems quite expensive to me.
I'd appreciate any suggestion. =D
Perhaps you should consider using a template compiler instead of a template interpreter. That is, instead of each time the page is loaded doing this whole replacement procedure you could simply perform the replacement after the template has been modified. During template editing the cost should be negligible. To implement this compilation you could choose to "compile" in some breadcrumbs so you can go backwards, or you can simply save the original template files for later editing.
Alternatively, you could consider using PHP variable naming conventions and running your templates through an eval, but this poses a number of other issues (like security threats) and doesn't come highly recommended.
Why can't you use Smarty and friends? I would not want to write what you suggest myself.

Categories