How to cache part of the page only - php

I need a code to cache just part of the page, in fact i want to cache the result of a function.
Example :
CODE HTML
<? my php code ?> <!- I want to cache this only -->
CODE HTML
I found a few incomplete codes but functions are missing and it's not working.
Thanks.

I assume you mean server-side caching for a function that takes awhile to run but has the same output for many users.
If so, check out Memcached. http://memcached.org/
http://php.net/manual/en/book.memcached.php
Hash the parameters for your function, use that as a key. Then stick the result in memcached and check for it the next time that function is called.

Related

Disable Cache in TYPO3 in a USER_INT function

I am working on a TYPO3 project where I have to dynamically disable caching based on a condition. It is a very specific usecase, that will not happen a lot.
I planned to use a USER_INT function, where I would perform the check and disable the cache if necessary. The USER_INT function works flawlessly, it is being called on every page load.
The thing is, I can not disable the cache, or at least I do not know how.
The code, I have right now:
page = PAGE
page {
typeNum = 0
adminPanelStyles = 0
11 = USER_INT
11.userFunc = [COMPANY_NAMESPACE]\PageHandler->checkCache
And in the function I perform the check:
public function checkCache($content,$conf){
global $TSFE;
$id = $TSFE->id;
if($this->checkIfDisableCache($id)){
//$TSFE->set_no_cache(); // <---- first I tried this one
$TSFE->no_cache=true; // <-----after a while I got despoerate and tried to disable it directly
}
}
I also tried to play with the config, it did not work.
The funny thing is, if I set it directly in typoscript:
config.no_cache = 1
it works, but since the check is rather complex, I want to use PHP to determine, if the cache should be disabled.
I know I am doing something wrong, I just don't know what. Any help would be appretiated :)
I don't think either of the previous answers really explain the situation. You have sort of a catch-22 here, in that your USER_INT is executed after the page cache entry has been generated. The way it works internally is everything that can be cached gets rendered first, and every USER_INT then outputs a marker in the HTML source which gets replaced afterwards. This way the cache can contain the version with markers and those can be rendered without having to render the whole page.
So what you need to do in this case if you want the page cache to be disabled only in some conditions, is to use a custom TypoScript condition that is capable of setting config.no_cache = 1 only under special circumstances. That way you prevent generating a cache entry if the condition is met, but preserve full caching and cached output for every other request.
https://docs.typo3.org/typo3cms/TyposcriptSyntaxReference/TypoScriptParserApi/CustomConditions/Index.html
Note that it is still recommended that you instead create the parts of your page that must not be cached, as USER_INT objects. Having a use case where you in some cases need to disable the entire page cache indicates a possible misunderstanding of how the caching framework and/or USER_INT works. Hopefully the above explains those parts a bit.
if you look at the pibase (AbstractPlugin) code you will see that probably setting $conf['useCacheHash']and $conf['no_cache'] should be done.
https://api.typo3.org/typo3cms/current/html/_abstract_plugin_8php_source.html#l00190
If you create this object as USER_INT, it will be rendered non-cached, outside the main page-rendering.
https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/UserAndUserInt/Index.html

Are there any limitations on where PHP code can go inside a file?

Can you put PHP anywhere in a file? Inside tags and quotes? For example, is something like this guaranteed to work (even though it isn't always recognized by an IDE's syntax highlighter):
<tr><tbody <?php if(!$row) echo "style='display: none;'"; ?>>
<!-- stuff that we only want to show if $row exists -->
</tbody></tr>
Or for example:
<a href="http://www.google.com/search?q=<?= echo $searchTerm; ?>"</a>
I know I can test this sort of thing on my machine, but I'm wondering if it is guaranteed/defined behavior and if there are any edge cases that don't work that I've missed.
Also, is there good reason not to do this? Is it dangerous because the next person looking at the code might miss it? Should I put a comment in? Does having to add a comment defeat the purpose of this method - succinctness?
Yes you can put the php tags anywhere in the page (html) there is no stopping you on that.
If we go under the hood, your web server sends the code to the php interpreter via a handler and merges the output with your static html file and sends the merged file as the response.
To add to my answer, developers usually go for MVC based frameworks so that the php code inside html page is restricted to only printing the variables and the business logic is performed in the controllers. I personally prefer CakePHP. Apart from that you might not want to put code that manipulates session or performs redirection between html tags else you will recieve the headers already set error as you have already printed certain html code before modifying the headers.

Is it bad practice to dynamically change a value with an infinite while loop?

I'd like a section of text that is already dynamically changing every 10 minutes to do it without refreshing the page. I was thinking something along the lines of:
<?php
while (1 < 2) {
echo $value;
sleep(60);
}
?>
I realize that's a dumb way to make a while loop run and I would think it would work with just "while(){}" but I just wanted to make sure, that will be corrected when I actually write this thing as long as this isn't terrible to do. If there is a better way I'd love to hear it! thanks!
Edit: I just noticed it would echo the value after the first, any cleaver ways to make it replace it?
Edit2 Here's the php function I already written to retrieve the changing value:
<?php
function getTotal($basePrice){
$dogeValue = file_get_contents("https://www.dogeapi.com/wow/?a=get_current_price");
$postage = .49/$dogeValue;
return round($sellAmount = $basePrice/$dogeValue - $postage - ($basePrice*0.1/$dogeValue));
}
?>
The short answer: yes, that is bad practice.
Reasons include:
You tie up your server (will probably time out)
Unless you play around with the buffering, things will not be reflected at the time you want
You never send the close tag to the browser (or anything else that happens later).
It is tricky to overwrite what was already there, so you end up with the output increasing instead of changing.
Recommendation:
Use client side code (javascript, AJAX) - don't try to do this server side.
You can see an example of periodic AJAX at https://stackoverflow.com/a/6378771/1967396 .
For periodic JavaScript, see many good answers at Is there any way to call a function periodically in JavaScript?
This script will never show you anything, because until processing the php script is not done, web server doesn't send anything to output, considering your infinite loop, it will never happen.
instead of this not-working idea, use Ajax, cron jobs, or even pure javascript, its very simple and more rational certainly.

Manually determine the last thing PHP does before it renders a page?

I'm trying to figure out the best way to unset a php session variable, after all pages have loaded and the page will be rendered to the browser. I have a page that includes & requires several pages to be rendered. I want to know if there is a built in php function that will tell php to do something right before the page is completed. Or what would the best way/practice to do this?
EDIT##
Here's what I added...
function unsetHIST_ID(){unset($_SESSION['Hist_CID']);}
register_shutdown_function('unsetHIST_ID');
Am not sure why you want this but if you want a function to be executed after script execution finishes or exit() is called then you should look at register_shutdown_function
Example
function shutdown() {
echo "Am dead anyway";
}
register_shutdown_function('shutdown');
echo "<pre>";
echo "Hello am Alive",PHP_EOL;
Output
Hello am Alive
Am dead anyway <---------------This would always run last
There's the .ini directive auto_append_file, which is parsed last by PHP if specified. It's basically treated as if you'd put require('somefile.php') as the very last command in a file yourself.
You need something like
register_shutdown_function ('my_atexit_function');
or maybe you can do this with
ob_start('content_handler');
The first function will be called immediately before exiting, which is not exactly what you asked for; and the second just before output, but that allows you to do something with an output that's already made static.
I'd go with register_shutdown_function though.

Suppress echo from PHP include file

I have a file PHP01.php which:
- performs a function
- creates an array
- echo's some message
I need to include this file in another php script, say PHP02.php as I need access to the array it created. But when I jquery POST request to PHP02.php, the data it returns also has the echo from PHP01.php
How can I suppress the echo from the first file?
You can output buffer it if editing or otherwise restructuring is not possible:
ob_start();
include "PHP02.php";
ob_end_clean();
If you can, you should look at refactoring the code in the original PHP file. If it's performing a function, it should do that. Then, the code that called the function should decide if they want to echo a message.
As you've just learned, this is an important part of orthogonal design. I'd recommend re-writing it so that it performs what you want it to, and let the code that calls the function, decide what they want to output. That way you won't have to worry about these things again.
You can also look into using output buffers. See ob_flush in PHP: http://php.net/manual/en/function.ob-flush.php
Try adding a conditional to PHP01.php that checks to see where it is being called from, this will ensure that you only echo it out if the file making the call is PHP01.php
Additionally it is better if you place functions in their own file to be included if needed so as to keep certain features that are present from being included for example in PHP01.php you can add include 'function01.php'; and it will have that function shared across the two files.
create a new function without the echo

Categories