These day's I'm working into a New's Website ,and the back-end I'm writing from scratch without using any PHP Framework's.
My concern is unreasonable periodic query's against MySQL("What does it mean !:)")
On the first Page user would see only updated Posts ,so i thought when Page Administrator insert's a Post i will Render a .html File with updated newest Post's and User's will get redirected there where all Posts are there and everything is fine(no php execution no MySQL Query's against a large Database).
So far Index.php was Executed ,did a Select at MySQL and present the data ,now i want to Execute Index.php get it's content and save it as Index.html
So is there a way to call a .PHP file ,Execute it Localy and save the Output into an HTML File ,just like User's will Execute.
Yes. What you can do is by using Curl library, call your index.php with full url. (eg. http://127.0.0.1/index.php). So, you take output of executed index.php instead of its code. Then, by using file_put_contents function, you can save output to an index.html file.
The easiest way to do it would be to use PHP's output buffering and store the output buffer in a file.
ob_start();
// process page here
$buffer = ob_get_flush(); // this will display the contents of the output buffer and return the contents into $buffer
file_put_contents('index.html', $buffer);
Just a short hint:
Your php file gets data from a database and save the output of it via the output buffer and safe everything to a html file. You script just have to check whether the .html file exists or not. If not > create it; else > include it / print the content.
Rally simple and you don't have to query the db all the time.
I suggest you look into something like Varnish which sits in front of your web application and provides a caching layer.
Because it sits between the user and your application, it is language / framework agnostic, thus integration effort tends to be lower.
(I realise this doesn't answer your question exactly in terms of implementation detail, but I want to point out that caching internal to your application isn't the only option for reducing database load)
Some statements to think of:
Databases intended to be queried. Nothing essentially wrong with "periodic query's against MySQL".
On the real-world website there will be not only one dynamical part: there will be things like banners, number of comments, fresh blog posts and such.
Stackoverflow is using such way of caching. It turns out to be expremely annoying when you are trying to refresh the page to get new data and it returns nothing.
Premature optimization is a root of all evil.
Related
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.
I am creating some kind of custom CMS (home automation).
Well I am not a PHP developer - just hobbyist.
What I am trying to achieve is:
In my index.php page I have something like:
"<?php echo $pageBody; ?> "
PageBody I am fetching from Database, well it works well for HTML, JS. But it doesn't work with PHP code source.
I done some research I believe this is related to PHP security restrictions.
My question: Does anybody would be able to provide safe sample (cannot find any samples like this) - how I should do this.
I am trying to insert some php code and render it eventually via browser:
<div id="outer">
<div id="inner">
***PHP Code should go here***
</div>
</div>
At the minute - it is being rendered as text. However I can render properly HTML and JS.
My preferable way would be - as much as possible secure.
Many Thanks Guys!
When you retrieve PHP code from a database text field, the PHP interpreter does not "know" that it should parse the data as a PHP script. To the PHP interpreter, the data in that field is no different from any other data -- it is all strings without any special significance.
You could use eval (docs) to accomplish this if you're dealing with pure PHP scripts. Be forewarned: eval is considered "evil" because using it comes with risks, especially if your users will have any input as to the content of the database.
In your case, it sounds like you want to parse mixed PHP and HTML that is stored in a database field. In order to do this, you'd need to write the database data into a file, then include it so the PHP interpreter can do its thing. You should implement some kind of caching mechanism in this process, otherwise it might become heavy on your server with many users. You may also want to use output buffering (docs) to capture the output instead of immediately sending it out.
Briefly, you'd want to do something like this:
$content_from_db = "<h1>Hello <?php print 'Clarisse'; ?></h1>";
$identifier_from_db = '12'; // like the primary key from the table
$file_handle = fopen('cached_content/CACHE_'.$identifier_from_db.'.php', 'w');
fwrite($file_handle, $content_from_db);
fclose($file_handle);
// here is where you'd start output buffering, if you're going to do that (optional)
include('cached_content/CACHE_'.$identifier_from_db.'.php');
// and then here you retrieve the output buffer's content (optional)
Please note that this is not a "traditional" way of including dynamic content, and the above code is not production-ready. Without knowing your use case, I can't say for certain, but this idea of storing PHP code in the database is a rather unusual way to proceed.
Another alternative to rolling your own is the smarty template library. Check it out here: http://www.smarty.net. With smarty, you can write a resource plugin to pull the templates from the database. It would look something like the code above (more info)
Documentation
fwrite - http://php.net/manual/en/function.fwrite.php
include - http://php.net/manual/en/function.include.php
PHP basics on theopensourcery.com - http://theopensourcery.com/phpbasics.htm
Server-side scripting on Wikipedia - http://en.wikipedia.org/wiki/Server-side_scripting
eval - http://php.net/manual/en/function.eval.php
Output Control (buffering) - http://php.net/manual/en/book.outcontrol.php
Smarty - http://www.smarty.net
to execute PHP that you store in a string (or database) you can use the eval function, but be careful it could be somewhat dangerous.
You can't render (probably you mean execute) php code in the browser, because php scripts execute on the server and then the output is sent to the browser. By the time the browser recieve the response, script has already finished execution.
You can fetch the code from database and use eval() before sending the output. But you must be aware of drawbacks from this approach.
Browser cannot render (execute) PHP code. PHP is something that the server executes and sends to the browser as plain HTML to display.
For testing purposes you can download and install WAMP thats the most hassle free one stop solution for development.
link : http://www.wampserver.com/en/
I've got a simple caching system that works like this:
1. Editor goes to the admin panel,
2. Enters the data,
3. The data is saved to MySQL (for good measure) and put in the HTML template.
The template itself is a part of my page where the article is presented (its like <article>...</article>). Saved in HTML as {id}.html
When user enters the page /articles/22/ I just include() the corresponding HTML page to the main template. Super simple.
But it's a little primitive IMO. And I started to wonder wouldn't it be better to store JSON with fields like title, content, tags and stuff and then parse this with PHP and put to template. It gives me a few benefits (like the possibility to put the data in other places in the template), but my first priority is speed.
So - my question would be: would it be noticeable slower to get JSON (pre-saved in text files), parse it with PHP and put into template than including pre-saved HTML file. I know there is nothing to wonder here if we talk about 100 request in the same time, but what if we talk about more? Or maybe my approach is not mature at all and I should stick to popular "user gets to the page, you check how long ago the cache file was created, you include it or get from SQL if it expired"? I don't like that. I just don't think there is any reason user should be involved in creating the cache files. The only time they change is when the editor makes some changes, so let him be the one who creates cache files.
Using read through caching will get you a long way. Basically, if an object (could be rendered HTML, json or whatever works in your flow), does not exist in the cache, you would read through to the database to build it, once built, you would store it in the cache.
If changes were made to the object, you could delete the cache and it would be rebuilt the next time it is requested.
As for a cache, you would probably want to use something like memcached, although apc could work pretty well too.
I'm developing a web application where an html page is created for the user. The page could include anything that the user puts in it. We take these pages and add a little PHP at the top to check some things before outputting the actual html. It would look kind of like this:
<?php
require 'checksomestuff.php';
// User's html below
?>
<html>
<!-- user's html -->
</html>
Is there a way to stop PHP from parsing anything after my require? I need the html to be outputted, but, since the user can add anything they want to the html, I don't want any user-added PHP to be executed. Obviously that would be a security issue. So, I want the user's html to be outputted, but not parse any PHP. I would rather not have to put the user's html into another file.
One sensible way would be to offload the user created content to another file and then you should load this file (in your main php file) and output it as is - without parsing it as PHP.
There are many other ways to do this but if creating another file does the job for you then thats probably the best way forward.
UPDATE: Really must read last line of question!
You could encode the html into a variable using base64 encoding which you then just print out the decoded string.
If you don't store the file data in a php file, say n a txt or html file, the php won't be evaluated.
Alternatively you could read the file via file_get_contents() or by some other means which doesn't involve evaluating php.
Though I'm still tempted to ask why you want to do this (particularly this way), it sounds to me like one of the only things that can help you is the special __halt_compiler() function...
That should prevent it from executing the rest of the page, and may or may not output the rest of it. If not, well, read the first (and currently only) example in the PHP's manual for that function (linked above) for how to do it manually.
The only trouble I see with this method is that you'd probably have to have that code in every file you want to do this for, after your require.
I'm creating a graph that does some database queries then builds the graph using GD functions then also puts the info from the database into an array that is stored in $_SESSION['my_data']. This graph is displayed on the web page using img tags.
<img src="my_graph.php?time=$time">
<?
print_r($_SESSION['my_data']);
?>
The problem is when I print_r() the array from the session variable it doesn't print the current graphs data; it prints the data that was in the graph last time the page was loaded. It's acting like a cookie.
I have tried putting session_write_close() immediately after I store the array in the session because I thought $_SESSION might have been locked until my_graph.php finished loading the image. That did not work.
I also tried putting sleep(10) before I print the array and that did not work.
Why this would happen?
I suppose, when your web server executes PHP code, which draws our page, it already has $_SESSION array initialized. And this array is not updated in current script runtime. When browser finds image tag, it makes another request to web server, which executes image generation script, which updates $_SESSION array in another runtime.
You may:
either make all calculations in your web page generation code
or reload page after image generation script completes calculations and sets all necessary data in $_SESSION array
If you are setting $_SESSION['my_data'] in mygraph.php, you will never see your $_SESSIONchange until your browser requests mygraph.php. This will never occur until the output is flushed to the browser (which will be AFTER you've already print_r() the $_SESSION).
You may be able to try flush() and hope the browser requests the image before you are done executing, I've never tried that (not sure if it will work). Though, sometimes you have to pad output with whitespace until it is about 2k (if I'm not mistaken). I wouldn't recommend this, though.
Another solution would be to request the page you have your code in above in the src. So if your code above is in test.php you could put <img src="test.php?img=true&time=$time">. Then if you get $_GET['img'], display an image, otherwise execute some code. Does that make sense?
Sequence of events:
Browser requests the main web page.
PHP runs the main page and sends the contents to the browser.
Browser receives the page.
Browser looks at the page and sends requests to load the graphics, etc.
PHP runs graph.php and sends the graphic to the browser.
Browser inserts the graphic into the page.
The important thing to note is that the whole of point 2 occurs before any of point 5 happens. This means that anything that graph.php does with $_SESSION will not be visible to the code in the main page, leading to the effect you're seeing.
This is the nature of a web page: the graphic files are separate from the main PHP program.
You cannot get around this using a separate graphic file the way you're doing it.
There is one way I can think of achieving it, but it would be a complete rewrite (it's up to you to decide whether it's worth it!)
It is possible to create a graph using Javascript. If you generate the javascript code to do this in the main page, you could then set $_SESSION during the graph generation code, and it would be available later in the program.
If you do decide to do this, you should look into the gRaphael library to help you out.
Hope that helps.