Requesting long PHP scripts with AJAX - php

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

Related

Should I remove temporary file send from form in PHP

I'm playing with various ajax uploaders. When analyzing their server-side code, I see something like this:
#unlink($_FILES['file']['tmp_name'])
It is either muted one (like above), so does nothing (in my case) or unmuted one, so throws a warning, that access to temporary folder is prohibited (in my case) and breaks execution of a script.
What am I missing? I was always told, that we should not touch temporary files transmited via PHP form. Because this is unnecessary (and somethimes prohibited, like in my case). PHP will do all the cleaning, when script ends -- i.e. remove all uploaded temporary files.
What is the reason in code like above? Is it for the case, when script breaks, PHP is halted with some critical error and thus isn't able to remove temporary files? Or there is another reason?
Edit: It is quite pity, that I found this kind of mistake even in Plupload example code.
As per comments - there's nothing you've missed. Unlinking shouldn't be done by the user-code, such things might not be permitted and can fail due to various reasons.

how is already loaded php script processed by server if there is another request from the same page

I real beginner and try to understand how things work more then to develop stuff, and now i can't move forward till someone gives me an accurate answer about a little detail of following issue.
Let's assume there's a page with php code http://example.com/blablabla and link on it like http://example.com/blablabla?file=number_1 which's used to modify some parts of this page
What i really don't know is what happens with the already loaded script from http://example.com/blablabla when there's a request from this page -http://example.com/blablabla?file=number_1
The questions actually are:
Is code from the already loaded page processed every time when requesting ?file=number_1?
For me it seems very strange, 'cause if with the first http://example.com/blablabla via php i selected for example a huge size of data from database and only want to modify small part of page with ?file=number_1 and why do i need server to process request to the database one more time.
My experience says me that server do process again already loaded code,
BUT according to this i have a very SLIGHT ASSUMPTION, that i'm not really sure about this, but it seems very logical:
The real trick is that the code in the first page has one VARIABLE and its value is changed
by the second request, so i assume that server see this change and modifies only that part of the code with this VARIABLE - for example the code in http://example.com/blablabla looks like this
<?
/* some code above */
if (empty($_GET['file'])) {
/* do smth */
} else {
/* do smth else */
}
/* some code below */
?>
with the request http://example.com/blablabla?file=number_1 the server processes only part of the original code only including changed $_GET['file'] variable.
Is it totally my imagination or it somehow make a point?
Would someone please explain it to me. Much appreciated.
HTML is a static language. There is php and other similar languages that allows you to have dynamic pages but because it still has to send everything over as html you still have to get a new page.
The ?file=number_1 just gives a get request to the page giving it more information but the page itself had to still be rerun in order to change the information and send the new static html page back.
The database query can be cached with more advanced programming in PHP or other similar languages so that the server doesnt have to requery the database but the page itself still had to be completely rerun
There are more advanced methods that allows client side manipulation of the data but from your example I believe the page is being rerun with a get request on the server side and a new page is being sent back.
i believe this is what your asking about.
Yeah, thanks you guys both. It certainly clarified the issue that every script (clean html or generated by php) runs every time with each request, and only external types of data like image files and, even as it follows from the previous answer, mysql results can be cached and be used via php to output necessary data.
The main point was that I mistakenly hoped that if the page is loaded and consequently cached in computer memory, the appended QUERY STRING to this URL will send, of course, new get request, but retrieved respond will affect this page partly without rerunning it completely.
Now i have to reconsider my building strategy – load as much data as it’s required from each requested URL.
If you are looking for a way to edit the page dynamically, use JavaScript.
If you need to run code server side, invisibly to the client, use PHP.
If you need to load content dynamically, use AJAX, an extension of JavaScript.
I hope that helps.

Performance vs modularity: Integrate JS into PHP or separate custom.js

I am new to Javascript and development in general and have an absolute beginner's question: I would like to know more about the advantages and disadvantages of the following two constellations, especially regarding execution speed and server load/requests.
Put all custom JS code inside PHP code and call it from there
Put all custom JS code inside a custom.js and just call the JS functions in PHP
On the one hand I prefer to keep all my JS code separated to have things tidy and clean but on the other hand I imagine that it takes longer to load the page due to an additional server request. Will there be a noticeable speed difference when I put all code in a custom JS file? Are there any specific scenarios where it's recommend to put the JS inside the PHP or keep it separated?
Thanks
Http requests run in parallel, so loading a js file may not be noticeable at all, assuming you have to wait for images and other assets to load as well. The benefits outweigh the potential drawback.
As an added bonus, js files are normally cached, while html is reloaded each time a page is requested.
NOTE: If you have a significant number of scripts, you will have problems with load speed since browsers have limits of how many requests can be made in parallel. In this case you should be looking into minifying and combining them. Try code.google.com/p/minify for automatic minification using php.
Last: Having js code in php is terrible for maintainability.
JS in separate file - additional request. But I would not say that is a problem because it will be cached by browser. If you have a lot of js files - collect them into a single file to avoid multiple requests (there are special tools to compile separate JS files into one file and minimize its size).
Placing it into PHP code is just terrible. It should be in separate file.
On the one hand I prefer to keep all my JS code separated to have things tidy and clean but on the other hand I imagine that it takes longer to parse the whole code.
Why? JS is executed on client side. Not on server side. PHP will not parse JS files. At the same time - if you will put a JS code in PHP file - PHP will need to echo it to browser and that is additional work for PHP engine. Plus, in PHP code it will be sent to browser any time when PHP is executed.
Always err on the side of clean readable code, lest you fall into the premature optimization trap.
You can always refactor underperforming code to make it faster, it's much harder to move from low-level optimizations to a more abstract design, than the other way around (abstract to low-level)

Simplify PHP files - PHP compression

I know JavaScript or CSS for expample can be "compressed", "simplified" in order to be loaded faster. After simplifying they are difficult to be read by humans... and this is exactly what I need.
Is there anyway to make it automatically? Rename all variables to short random strings and make it all hypercompressed. I don't think it is a fool thing because I have seen this lot of times in javascript. The idea is to conserve the original source and upload the minified one.
There is no need for doing this. The Server reads the file, and the file never gets transferred to the user.
Therefore, compression is useless because there is no bandwidth saved.
CSS & JavaScript does however get transfered to the user, and therefore they can see it. A user can never see PHP unless you've done something wrong on your server. But then you need to worry about totally different things than compression.
If you want to compress it, this is basically useless, since you have it on the server and only the output gets transferred to the client.
If you want to make the code more difficult to read for other human beings, you're looking for something which is called an obfuscator.
There are a few php obfuscator engines out there, p.e.
http://www.codeeclipse.com/
http://www.truebug.com/
http://www.raizlabs.com/softwarephpobfuscator/

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.

Categories