How can i cache the result of rand()? - php

I want to cache the result of rand() for 5 minutes.
<?php
$sec = 300;
$expires = gmdate("D, d M Y H:i:s", time() + $sec) . " GMT";
header("Expires: $expires");
header("Pragma: cache");
header("Cache-Control: max-age=$sec");
echo "Test " . rand(1, 10);
Unfortunately, i don't know why my code doesn't work. Everytime i call the php file in my browser the random number is different.
Does anybody has an idea what the problem is?
Edit:
The headers are sent correctly, but everytime I reload the page, the Expires header changes.
When i print $_SERVER, The HTTP_CACHE_CONTROL header says no-cache.
Could that be the problem?

Ok, everyone here suggesting alternatives, including javascript, cookies, etc but that does NOT answer the question.
The question is to cache using headers for that explicitly a 304 NOT Modified response exists...
<?php
$sec = 300;
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
$if_modified=time($_SERVER['HTTP_IF_MODIFIED_SINCE']);
if($if_modified>time()-$sec)
{
Header("HTTP/1.1 304 Not Modified");
exit();
}
}
$expires = gmdate("D, d M Y H:i:s", time() + $sec) .' '. date_default_timezone_get();
$modified= gmdate("D, d M Y H:i:s", time()) . ' '.date_default_timezone_get();
header("Expires: $expires");
header("Last-Modified: $modified");
header("Pragma: cache");
header("Cache-Control: max-age=$sec");
echo "Test " . rand(1, 10);
There you go.
Caching random numbers with headers.

I want to cache the result of rand() for 5 minutes.It can be possible throw javascript code. But it store in cookie
// this fun call after every 5 miniute
setInterval(function(){
generate_and_cookie_random_fun();
}, 5000);
// this fun generate random number and sotre it to cookie
function generate_and_cookie_random_fun(){
var random_number = Math.floor(Math.random() * 6) + 1 ;
setCookie('name_of_cookie',random_number ,7); // here 7 mean seven days
}
// below code for cookie
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;';
}

The simple way is to store it into cookie and check that if cookie exists to show the stored number, otherwise generate new.
Something like this:
<?php
setcookie("random_number", rand(1, 10), time() + 300);
if(isset($_COOKIE['random_number'])) {
echo $_COOKIE['random_number'];
} else {
setcookie("random_number", rand(1, 10), time() + 300);
}

Related

Force download of ics file created with php with POST data send from AJAX request collected from user input

I am trying to create a downloadable .ics-file from user input.
The point I am struggling with is the download part.
Code:
jQuery
function sendOnSuccess(){
var name = jQuery('.member.selected .name').text();
//day - only the number
var day = jQuery('.member.selected .calendar .date').text().replace(/\D+/g, '');
var month = jQuery('.member.selected .calendar .month').text();
var year = jQuery('.member.selected .calendar .year').text();
var time = jQuery('.member.selected .slots .selected').text();
//get everything before :
var hour = jQuery('.member.selected .slots .selected').text().substring(0, time.indexOf(":"));
//get everything after :
var minutes = jQuery('.member.selected .slots .selected').text().split(":").pop();
var number = jQuery('.member.selected .form input[name="tel"').val();
jQuery.ajax({
url: 'download_ics.php',
type: 'POST',
data: {
name : name,
day : day,
month : month,
year : year,
time : time,
hour : hour,
minutes : minutes,
number : number
},
success: function(output){
// output works
}
});
}
download_ics.php
<?php
require_once("ICS.php");
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename.ics');
$name = $_POST["name"];
$day = $_POST["day"];
$month = $_POST["month"];
$year = $_POST["year"];
$time = $_POST["time"];
$minutes = $_POST["minutes"];
$hour = $_POST["hour"];
$number = $_POST["number"];
$date = strtotime("$year-$month-$day $hour:$minute$timeofday");
$ics = new ICS(array(
'description' => $name,
'dtstart' => $date,
'dtend' => $date . '+ 30 minutes'
));
echo $ics->to_string();
if($number){
//die(' Success');
die();
}else{
die("failed to create");
}
Everything is triggered with this line of html:
<a class="download" href="#" target="_blank" onclick="sendOnSuccess();">Download .ics</a>
So everything works fine - just I cannot figure out how to download the file after it has been created. Everything I get back is just the content of the file.
Inspired by this project: https://github.com/jakebellacera/ics
Could you show us ICS.php? Does is have documentation anywhere?
I would start by changing
header('Content-Disposition: attachment; filename.ics');
to
header('Content-Disposition: attachment; filename="filename.ics"');

(PHP) setcookie get error "Premature end of script headers"

I created a PHP script that reads the data from mysql database and returns an output in json format.
The script works fine, but now I want to save the output in my cookie.
When I add the function setcookie("Messages",base64_encode(serialize($messages)),157680000000);
I have a Server Error 500 : Premature end of script headers.
How can I save the array $messages in the cookie?
----------------- PHP CODE -------------------
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
include_once("include/common.php");
if (empty($uname)){
$uname = (!empty($_GET['u'])) ? $_GET['u'] : "";
$uname = (!empty($_POST['u'])) ? $_POST['u'] : $uname;
}
if (empty($limit)){
$limit = (!empty($_GET['limit'])) ? $_GET['limit'] : "";
$limit = (!empty($_POST['limit'])) ? $_POST['limit'] : $limit;
}
$isonline = is_online();
$user_obj = new User();
$user_info = $user_obj->getUserInfo($uname);
$msg_obj = new Message();
$msg_array = $msg_obj->getMessages($user_info[_USERID_COLUMN],$limit);
$messages = array();
$i = 0;
[...]
foreach( $msg_array as $id => $val ){
$messages[$i]['id_message']=$val['id_message'];
$messages[$i]['user']=$val['user'];
$messages[$i]['user_image']=$val['user_image'];
$messages[$i]['posted_time']=time2str($val['posted_time']);
if($options['link'] == "off"){
$messages[$i]['message']=htmlspecialchars_decode(cleaner($val['message']));
}else{
$messages[$i]['message']=htmlspecialchars_decode($val['message']);
}
$messages[$i]['mediatype']=$val['mediatype'];
$messages[$i]['mediaurl']=$val['mediaurl'];
$i++;
}
array_reverse($messages);
if(ceckCookie()){
setcookie("Messages",base64_encode(serialize($messages)),157680000000);
}
if( !$isonline && !empty($_COOKIE["Messages"]) ){
echo($_COOKIE["Messages"]);
}else{
echo(json_encode($messages));
}
is the data you are trying to save is huge ??
$_COOKIE can store under 4000 bytes...(Includes date, name, value, expiry) ..

Ajax cannot cache

I want to cache the data in broswer so that broswer don't need to query the server in several minutes. I added php cache header but seems it doesn't work. Here is my ajax code and php code:
Ajax code:
function myAjax(name, callback) {
var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';
jQuery.getJSON(url, function(data) {
callback(data);
jQuery.ajaxSetup({ cache: true });
});
}
PHP code:
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
$lm = gmdate("D, d M Y H:i:s", time() - $seconds_to_cache/2) . " GMT";
header("Last-Modified: $lm");
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: public, max-age=$seconds_to_cache");
include_once('getData.php');
$output = $_GET['name'];
echo $_GET['callback'].'('.$output.')';
Thanks for MitchS and lenzai's help. This issue is solved. The cache:true option should be set before any ajax querying and old jquery libraries don't support caching. So make sure you are using the newest jquery library
For people who want a working example:
Ajax code:
var callback = function(data) {
alert("callback");
}
function myAjax(name) {
var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';
jQuery.ajaxSetup({ cache: true });
jQuery.getJSON(url, function(data) {
callback(data);
});
}
PHP code:
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
$lm = gmdate("D, d M Y H:i:s", time() - $seconds_to_cache/2) . " GMT";
header("Last-Modified: $lm");
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: public, max-age=$seconds_to_cache");
$output = '{"eventList":["event1","test event"]}';
echo $_GET['callback'].'('.$output.')';
You are setting the Last-Modified header to an hour ago and setting the max-age to be an hour.
This means at the point you send this data, it is already at the maximum age allowed for a cache and any subsequent requests must be resent.
I wrote a test project adapted from your on your code.
http://test-lenzai.rhcloud.com/index.html
Each time you press the button, it launches a new ajax request...
The query is sent twice then the browser cache is used!!!!
This is caused by JQuery :
the first query is appended &_=s135227990... ( some timestamp probably)
subsequent queries don't have this extra argument and all identical queries are effectively using cache.
Now the question is how to tweak jquery so that 1st and second ajax queries are identical

my php if statement doesn't work

This is my first time asking a question in this website so please bear with me. I got a script from another website for testing internet connection speed and added if else statement. If the speed is more than 500, it will redirect to a specific page. For some reasons, I can't make it to work. I have added the ob_start(); before the <html> tag and also added ob_end_flush(); after the </html> tag. I have added the code below in between my body tags.
$kb=512;
flush();
$time = explode(" ",microtime());
$start = $time[0] + $time[1];
for($x=0;$x<$kb;$x++){
echo str_pad('', 1024, '');
flush();
}
$time = explode(" ",microtime());
$finish = $time[0] + $time[1];
$deltat = $finish - $start;
$intspeed = round($kb / $deltat, 0);
echo $intspeed; //just to check if $intspeed has a value
if ($intspeed > 500) {
header("Location: test.php");
exit();
} else {
header('Location: falcons/index.php');
exit();
}
Remove the flush(); calls. Also, ensure that this code is between ob_start() and ob_end_flush(), not before or after (and also that nothing else is output before this code).
$kb=512;
$time = explode(" ",microtime());
$start = $time[0] + $time[1];
for($x=0;$x<$kb;$x++){
echo str_pad('', 1024, '');
}
$time = explode(" ",microtime());
$finish = $time[0] + $time[1];
$deltat = $finish - $start;
$intspeed = round($kb / $deltat, 0);
echo $intspeed; //just to check if $intspeed has a value
if ($intspeed > 500) {
header("Location: test.php");
exit();
} else {
header('Location: falcons/index.php');
exit();
}
You can only redirect via header() if output has not started yet. If there is already non header output (like in your for loop), setting the "Location" header has no effect.
I recommend using headers_sent() before setting a "Location" header and have a fallback in case some debug information or something else already started output.

xmlhttprequest onlys gets to status 3

I have a simple search form with a search box and a result box.
When I type a search word a request is created like: http://www.site.com/php_handler.php?s=hello
In the php script and a result is given back to the script this way:
<?php return $s; ?>
The problem is that my htmlrequest stops at readyState 3 it doesn't get to 4.
The javascript looks like this:
var xmlhttp = sajax_init_object();
function sajax_init_object() {
var A;
try {
A=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
A=null;
}
}
if(!A && typeof XMLHttpRequest != "undefined")
A = new XMLHttpRequest();
if (!A)
sajax_debug("Could not create connection object.");
return A;
}
function getSearchItem()
{
gs=document.forms.mainform.resultsfield;
var searchword=document.forms.mainform.searchform.value;
if (searchword.length>=3)
{
setWaitCursor();
clearResults();
var uri = "http://site.com/ajax_handler.php?s="+searchword;
console.log(uri);
xmlhttp.open("GET", uri, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
processResults(xmlhttp.responseText);
removeWaitCursor();
}else{
console.log(xmlhttp.readyState);
}
}
xmlhttp.send(null);
}
else
{
alert("please add at least 3 characters .");
}
}
Can someone tell me why it stops at 3?
edit: here is also the php code:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
session_start();
//include main file
require_once($_SESSION["FILEROOT"] . "xsite/init.php");
//check if formulier is posted
$zoekterm = C_GPC::getGETVar("s");
$s="";
if ($zoekterm != "") {
$query="SELECT number,name,city,zib,zip_annex FROM articles WHERE version='edit' AND (naam LIKE '%$school%' OR brinnummer='$school') ORDER BY name";
if ($rs=C_DB::fetchRecordSet($query)) {
while ($row=C_DB::fetchRow($rs)) {
if ($row["plaats"]!="") {
$s.=$row["name"].", ".$row["city"]."|".$row["number"]."\n";
} else {
$s.=$row["name"].", ".$row["zip"].$row["zip_annex"]."|".$row["number"]."\n";
}
}
}
}
return $s;
?>
edit:
I missed a semicolon in my php script and now the ready state only gets to 2
edit:
The problem is even different. It gets to 4 but it doesn't show the result text.
1> Don't send Cache-Control: post-check=0, pre-check=0. These don't do what you think they do, and they're entirely unnecessary.
2> Your AJAX results page needs to send a Content-Length or Connection: Close header.
3> Try adding a random to your request URL to ensure you're not looking at a stale cache entry.
ReadyState 3 => Some data has been received
ReadyState 4 => All the data has been received
Maybe the XMLHTTPRequest object is still waiting for some data.
Are you sure your php script ends correctly ?
Is the content-length alright ?
To debug this you have two options, type the URL directly into the browser [since you are using a GET] and see what is happening.
OR
You can use a tool such as Fiddler and see what is exactly happening with the XMLHttpRequest

Categories