Does PHP Include make your code faster? - php

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.

Related

Difference in loading time PHP and HTML file?

I'm currently working on a website in which some pages are written in PHP, but not all of them.
I'm considering including the menu as a PHP file (so when the menu has to be changed I only have to change it in one file, instead of all my pages). But that requires converting my HTML pages into PHP.
Aside from the fact that changing for example the menus will be easier, will it make a difference in loading time at the clients side?
Just curious if it will make a noticeable difference.
It won't make any noticeable difference unless you add very heavy calculation or bad code inside. For include only and maybe some appearances of if and echo it won't make any difference that you could notice.
The load times will be slightly longer as each of the PHP files needs to be processed in order to generate the HTML which the browser can render. It would also need to load each included file for the page too.
The "slightly longer" won't amount to anything noticeable, it will be fractions of a second for the server to respond.
Will there be difference? Yes.
Noticeable by human? No.

MODx - Php code isn't updating

I recently have been using snippets to power a "server status" page for my MinecraftServers, and it was working fine for quite a while, however now for some reason the php code is not updating! (It became very clear when our servers went down, and sadly the server status snippets were not updating, and quite a few of our users were getting confused!)
If I could receive any help, that would be awesome-
Problem:
Php Snippets are not updating (Not even after 24 hours)
Desired Result:
Is there a way to make it update every 2-3 minutes when being used, however if no one goes to the page, not update it at all..?
Snippet Code: on
PasteBin
MODx Version - Revolution 2.2.6-pl
This is most likely due to caching.
Caching in Modx means that the system creates an individual file for each resource in your site. These files are built up by all the snippets, chunks and placeholders you may have in your template and elements being parsed.
If you chose to cache these snippets or chunks, Modx will not call the code again, but just output the content that was generated the very first time the cache was created.
These are cached:
[[mySnippet]]
[[$myChunk]]
These are uncached:
[[!mySnippet]]
[[!$myChunk]]
Please note that you want to use as much caching as possible, but the snippet you are describing (different output without removing the cache) would require uncached tags.

Requesting long PHP scripts with AJAX

I'm building a website which loads dynamically from a SQL database. To do that, I've created a PHP file that handles ALL AJAX and Post and Get requests (and every page has a couple of php include).
The PHP is not very long yet (250 lines), but it could get much longer eventually.
Everything is wrapped in <?php **** ?> tags, and is clearly and methodically composed of switch and case. So I only need a couple of lines each time.
My question is: Does every include request load/download all the file, or just the corresponding part? Rephrasing, will a hypothetically 10,000 line long script slow down the browser, or just the response time from the server?
I have concerns about all this.
Thanks in advance.
PS: This idea of unifying sql requests comes from a computer engineer friend that's always insisting on Multititer Architecture.
When you include a file, the entire files contents are inserted/executed into the script at that point. Depending on what is going on with the includes, you could be slowing down the response if you are including files that are not necessary for the response.
http://us3.php.net/manual/en/function.include.php
I have a great solution! (And this was my own question)
Instead o parsing a variable $option to enter a switch case case case .... case case endswitch I thought I could just split the PHP into a lot of different PHP's with the name of their corresponding case.
So, instead of using case('sports'), I will now use a <?php include('some_folder/'.$option.'.php');?> which will avoid converting to binary the whole file every time is called.
Since PHP is processed on the server, the included file will come all along and it will just have to deal with 20 lines of code instead of 400 (and, eventually, many more).
Definitively, thanks

Argument for PHP vs. DWT

I was having a "discussion" with my manager today about the merits of using PHP includes and functions as a template to build websites more quickly and efficiently. He has been using Dreamweaver templates for years and sees it as really the best way to go. I would like to start using some different and more efficient methods for web creation, because we need to get through our projects faster. I would like to know in detail what would make Dreamweaver dwts better than using code to accomplish the same task, or vice versa.
His reasoning is:
When you change links on the dwt file, it changes links for every page made from that dwt.
Even if you move pages around in directories, it maintains links to images
Everyone in the company should do it one way, and this is the way he chose (there are two of us, with someone who's just started who needs to learn web design from the beginning, and he plans to teacher her the dwt method)
If you edit a site made with a dwt, you can't change anything in the template (it's grayed out), making it safer
If he's building sites with dwt, and I'm doing it with PHP includes, we can't edit each others' sites. It gets all over the place. When we have new employees in the future, it will get all crazy and people can't make changes to others' sites if they're out of the office.
I've been studying PHP these days, and am thrilled with how powerful it is for creating dynamic pages. The site in question which sparked this "discussion" is more or less static, so a dwt would work fine. However, I wanted to stretch my wings a bit, and the code was getting REALLY jumbled as the pages grew. So I chopped off the header, footer, and sidebar, and brought them in to all the pages with a php include, as well as dynamically assigned the title, meta data, and description for each page using variables echoed in the header.The reasons I like this better are:
It's cleaner. If every page contains all the data for the header and footer, as well as the extra tags Dreamweaver throws in there, then I have to sift through everything to find where I need to be.
It's safer. It's sort of like the above reason dwts are safe, except I do all my code editing in a text editor like Coda. So on occasion I have accidentally deleted a dwt-protected line of code because those rules only apply within dreamweaver. I can't chop off part of the header if I can't see it. Incidentally, this makes it easier to identify bugs.
It's modern. I look through source when I see great pages made by designers and design firms I admire. I've never seen dwt tags. I believe by using PHP to dynamically grab files and perform other tasks that keeps me from having to go through and change something on every page, life becomes easier, and keeps things streamlined and up-to-date with current web trends and standards.
It's simple. This should be at the top of the list. Like I said we have to train a new person in how to create for the web. Isn't it much better for her to learn a simple line of PHP and get an understanding for how the language works, rather than learn an entire piece of (not exactly user-friendly) software just for the purpose of keeping her work the exact same as everyone else's? On that note, I believe PHP is a powerful tool in a web designer's arsenal, and it would be a sin to prevent her from learning it for the sake of uniformity.
It's fast. Am I mistaken in my thought that a page build with header and footer includes loads faster than one big page with everything in it? Or does that just apply when the body is loaded dynamically with AJAX?
I did extensive searching on Google and Stack Overflow on this topic and this is the most relevant article I could find:
Why would one use Dreamweaver Templates over PHP or Javascript for templating?
The answer is helpful, but I would really like to understand in more detail why exactly we shouldn't switch to a new method if it's simpler and has more potential. My manager insists that "the result is the same, so if there isn't something that makes me say, 'oh wow that's amazing and much better!', then we should just stay how we are now."
(I do apologize for the length of this question, but the guidelines asked that I be as specific as possible.)
Like I said in comments, without knowing what exactly sites you are working with it's hard to tell which PHP features are most important to showcase. However, I can try and describe the most simple kind of sites I was dealing with, and where and how PHP came in handy. If you work with something more complicated, the need of programming language may only increase.
The simple website may have a few different pages with text and images. I'm assuming nothing interactive (i.e. no inquiry form), no large amount of structured data (i.e. no product catalog), only one design template which is used by every page with no differences whatsoever. Here's the typical structure:
One PHP file (index.php) for handling all sorts of php-ish stuff
One design file (template.php for example) for storing everything html-ish (including header, footer and more. Basically all html with placeholders for text and menu)
One CSS file for, well, the site CSS
Most of the texts are stored in database or (worst case) just txt files. Menu (navigation) is stored in database as well
Images folder with all the needed images
The key features here are:
Simplicity. You only have as many files and code as you really need to keep things organized and clear
Reusability. You can basically copy/paste your php code with little to no changes for a new similar website
No duplicates whatsoever.
Data and design separation. Wanna change texts, fix typos? You do it without as much as touching design (html) files. Wanna make a completely brand new design for your website? You can do it without even knowing what those texts are or where they are kept.
like deceze said, no lock-ins. Use whatever software you like. (Including Dreamweaver)
PHP is responsible for taking texts, menus, design and rendering them all into a web page. If website is in more than 1 language, PHP code choose the right texts for the language of visitors choice.
If texts are stored in database, you don't even need notepad and ftp. You just need, i.e., phpMyAdmin (stored in server) so you can connect directly to database and edit any text you like using only web browser; from anywhere in the world. (I am assuming no real CMS). If you need to add one more page, you connect to database using myAdmin and browser, enter the page name (for menu) in 1 or more languages, enter the text for new page (in 1 or more languages), done! new page created, name placed in the menu, all hyperlinks generated for you. If you need to remove a page, you connect to database and click delete. If you need to hide a page for a while (i.e. for proof reading before publishing), you connect to database and uncheck "published" box.
All this doesn't come with just using database ofcourse, you need to program these features with PHP. It may take about 1 - 3 hours depending on experience and the code is fully reusable for every similar website in the future. Basically you just copy/paste php file, copy/paste database tables, enter new text and menu into database, put placeholders into your html file and done! brand new site created.
Which immediately makes most of the reasoning for DWT irrelevant. You don't move files around because you have only one html file and no directories, you don't need grayed out template because texts/images (content) and template are not even in the same file, there's no such thing as changing links in dwt file because it's PHP that generates them on the fly (these are not real links to real html files but rather links with parameters to tell PHP which exactly page must be rendered.. because remember we have just 1 file). The bottom line is, comparing features of the two side by side is like comparing features of a sword vs machinegun. Sharpness and length of the blade concepts are meaningless in a case of machinegun; while lifetime sword user won't really get the meaning of velocity and caliber before he tries and uses machinegun. And yet, while you can't compare their features one by one, no one brings sword to a gunfight for a reason :)
As for #3, currently there are many more people working with PHP than DWT (in a case you will need more employees in the future, or if other people will need to work with your websites later, etc.) As for #5, you can edit PHP websites with Dreamweaver as fine as DWT websites.
That's just off the top of my head. I wrote this in my lunch break so I likely forgot or missed quite a few things. I hope you will get a proper answer with detailed DWT vs PHP comparison too.
You simply can't compare PHP vs. DWT.
PHP is a programming language, where templating is just one of it's numerous features, and DWT is just a silly proprietary system to build simple web pages.
there is actually nothing to compare.
I would say that using DWT templates over PHP do have some advantages.
It does not need any extra server-side process, like PHP to process the files at the server.
You can serve all files to the user as .html files rather than .php files, though I suspect that it is possible to hide the .php extension. Why should any user see anything other than .html?
You don't have to learn PHP syntax/programming. It is true that you can do more with PHP that plain .dwt files but for plain templating the .dwt files can be just as clean.
It is not true that .dwt files are a lock-in technology. The feature is also implemented by other web editors, e.g. Microsoft Expression Web.

What renders the HTML?

In PHP you can write html along with PHP, like:
<html>
<head>
<?php echo "HTML Title from PHP "; ?>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>
I would like to know what is this, and how it is working, and in what was written, and how deep do I need to go to understand it?
Nowadays I hear about template engines, but there are lots of template engines for PHP too, so it sounds stupid(for me) to write a template engine on a template engine also as I understood, a template engine parses the whole file just to replace the commands, then it starts to output the file contents too, so it doesn't feels to me that it would be the part of the system, thus loosing performance. ( Maybe I'm totally wrong but seriously this is what I feel when I hear it :P )
EDIT
Guys, when I say what renders HTML I mean what renders HTML in PHP? In a node.js file you can't write any HTML because nothing is processing it.
Trying to avoid too much information, but here is the full cycle of PHP when used with Apache on Linux.
Prerequisities
A common server setup is called the LAMP stack which stands for Linux, Apache, Mysql, and PHP. Generally you can find dozens of ready to use LAMP stack setups along with guides for using them so in context of your question, all you need to focus on is Apache and PHP.
Stage 1 - Delegation
When a web browser contacts a web server running Apache with PHP, the first step is for Apache to find the desired content. Say you go to www.mywebsite.com/hello.php, Apache is going to see you're looking for a file called hello.php. At this point, because of the suffix (.php) , Apache knows that this file needs to be interpreted by PHP so it delegates processing to the PHP interpreter.
Stage 2 - Setup
The hand over from Apache to PHP includes a slew of headers that tells PHP the following: what kind of transaction is being processed ( GET/ POST/ PUT/ DELETE ), the IP address of the incoming request, the browser's user agent ( Firefox, MSIE , IPhone, etc ), if there are cookies. More importantly, Apache hands to PHP the path to hello.php file on the server.
Stage 3 - Processing
Depending on configuration, PHP might need to do some basic house keeping ( setting itself up ) but under ideal conditions its ready to go and opens hello.php Part of PHP is a module called a lexer which looks at hello.php and figures out how to deal with the file. With the example provided a very simple example might look like:
T_STRING = "<html>\n\t<head>\n\t"
T_OPEN_TAG;
T_ECHO;
T_STRING = "HTML Title from PHP ";
;
T_CLOSE_TAG;
T_STRING = "\t</head>\n\t<body>\n\t<h1>hello world!</h1>\n\t</body>\n</html>"
Note, I've made up most of the T_ codes, but they're pretty close to what is real.
Line 1 - PHP knows it's outside of what called scope, so it immediately passes this entire string to Apache, the webserver. Apache will most likely then pass this entire string onto the web browser.
Line 2. - T_OPEN_TAG tells PHP it's entering into the PHP scope and waits it's first instruction.
Line 3 - T_ECHO tells PHP it's going to make an echo statement, so it's rules then kick in to look for an expression or string to output.
Line 4 - As luck would have it, the next token is a string, so PHP now knows it's going to echo "HTML Title from PHP "
Line 5 - The ; tells PHP that the echo statement is complete and more importantly this is syntactically correct... so PHP hands the string "HTML Title from PHP" to Apache which passes this onot the browser.
Line 6 - The Close ?> tag tells PHP that it is leaving the PHP language scope, so it goes back to a much simpler set of rules
Line 7 - Like line 1, the entire string is passed to Apache to be passed to the web browser
At this point, PHP reaches what's called EOF or end of file and knows it's done processing the file hello.php. It does cleanup work and then tells Apache it is done.
Finalization
At this point the request has been mostly fulfilled, Apache will most likely hang up on the web browser, sending notification that all content is complete.
Let me know if you have any questions or need any pointers on where to go next. Also note there is a LOT of details left out of here for brevity/sanity sake, but for just understanding how birds eye view of PHP's relationship to the web browser & web server, this should be enough to get started.
Demonstration script
$test = 'Hello world <' . '?' . 'php echo \'this is in scope\'; ?' . '> and we\'re done';
$tokens = token_get_all($test);
print_r($tokens);
The output will be real world token string PHP generates. Each token can be either a string or a three element tuple/numeric array where index 0 == the Token ID, index 1 == raw string, and I can't for the life of me remember what the third element is. Use token_name if your curious what each token's name is.
First off, PHP IS a template engine, when you use it like in your example.
You really don't need anything more, if you want to keep it simple.
anything inside the <? ?> braces is php code - it's executed on the serverside, and then it outputs the plain HTML to the client, at which point the client's web browser renders it.
Have a look at this diagram.
Your browser is only ever the thing that renders HTML. Whether its written via PHP, javascript or asp, in the end, the thing that works out what the text means (as html is only text) is your browser.
the rendered final product is handled by your web browser. (FF is written in C/C++)
before transmission, apache runs all php scripts thru PHP (preprocessor) written in C
if you use a PHP template engine (eg: Smarty) that is written in PHP itself
if you're really concerned with performance, then switch to another language. PHP template engines are not about conserving CPU cycles, or even speed, instead they boost productivity and maintainability, furthermore they empower front-end developers with the ability to maintain more complex templates without knowing PHP, which increases the value of their work, while free developers to do more serious coding.
Well, you need to understand the history of web development
to give you an "answer" to your question.
In the 199x when Web development started a lot of people uses
Perl. In these days you often have written code like this:
print "<html>";
print " <head>";
print " <title>", get_site_name(), "</title>";
print " </head>";
print "<body>Hello, World!</body>";
print "</html>";
As you can see in this example, in these days you often end
up writing a lot of HTML, and just include some little dynamic stuff.
Like a counter, a clock that shows time, or other little
things. In these days PHP was born to make this process a lot
easier. Instead of writting Code that prints a lot of HTML,
PHP was/is a templateing Engine that allows you to write
HTML and just include your code. In these days you probably
end up writting 90% HTML and 10% of you logic. In these days,
that was oft everything what you needed and it was a lot easier
this way.
But time changed. Today web development got a lot complexer
as in the earlier days. Today you probably write 90% logic and just
10% HTML. Today nearly everything gets
automatically generated, and comes from a database. Because of
the complexion that raised, today you often write your PHP
Application like
<?php
echo "<html>";
echo "<head>";
echo "...";
echo "</html>";
?>
Well as you can see, evolutions goes backwards. And is not
a big difference as in the days before. PHP programs
most ended in starting the php Tag and generating everything
and echo out everything what is needed like in the old days
with Perl.
But, that is still not enoug, you end where you started. Because
today you have a lot more logic to write in your application,
it is a good idea to seperate your application into many peaces.
You seperate your application intp logic and how you should display
your data.
The logic itself get written in PHP, but to display the
data people tend to use other templating engines, that are much
more modern today and fits the needs better.
Yes, it seems a little awkward to have a Templating Engine
that raised to a general purpose language, where Templating
Engine is written in, but that is how it is.
The question how HTML get rendered, well you have a "php" interpreter often directly embedded in Apache (mod_php) that do all the stuff, but for this description there already exists better answers.

Categories