Hey guys am really a noob in php...I just want to make a redirect after the session ends..So i have came to know that without js this cant be implemented..So i have modified the code with the help of my friends
<html>
<body>
<?php
session_start();
$_SESSION['logintime'] = time();
echo 'this page needs to be redirected in a minute'
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
$(function(){
var loginTime = <?php echo $_SESSION['logintime']; ?>
var testSession = setInterval(function(){
var currentTime = Date.now() * 1000;
if((currentTime - loginTime) > 60) { //here 60 denotes a minute
<?php session_start();
session_unset();
unset($_SESSION);
session_destroy();
?>
window.location.href = 'www.google.com'; // redirecting process
}
}, 1000);
});
</script>
</body>
</html>
The code runs without errors ..but it isnt redirecting after 60 seconds..
Any guides to make this code work correct would be really appreciated..Thanx
Try this, it goes in the section of your html:
Using html only
<meta http-equiv="refresh" content ="5; url=http://www.target.com/">
5 is the number of seconds. Now you can replace 5 with some PHP generated value.
<meta http-equiv="refresh" content ="<?php echo $limitTime(); ?>; url=http://www.target.com/">
If you want to do it in Javascript use following syntax
setInterval(function () {window.location.href = 'http://www.google.com'}, 60000)
In php you can use header method to redirect url
header("Location: http://www.google.com")
Related
I check all documants about setinterval from forum but.. I couldnt find what I want... Here is my question.:
my code is below:
<?php
include('database_connection.php');
$sorgu = $baglanti->query("select * from makale");
while ($sonuc = $sorgu->fetch_assoc()) {
?>
MY TABLE CODE HERE.. ( codes like : <?php echo $sonuc['proje_ismi'] ?> )
<?php } ?>
I call datas to my table from mysql.. But I change database from admin panel..
And What I want is when I change some data from adminpanel... My users will see it immediatly in few sec with setInterval code without refreshing page...
How can I do that in my documants?
The simplest thing you can do is to refresh the page automatically after few seconds:
<script>
// Auto-refresh the page after 5 seconds:
setTimeout(function() {
document.location.reload(true);
}, 5000);
</script>
currently I am working on a online quiz platform and I want to show a quiz timer.first I use javascript to show timer but problem is that when user refresh a page or goes back the quiz timer start again form start so I want to use session variable time to show quiz timer. and I set this session variable when user start the quiz. but my code is not working properly. here is my code:
`<?php
include_once 'dbConnection.php';
session_start();
if(!(isset($_SESSION['email']))){
header("location:login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
// timer will start when document is loaded
$(document).ready( function () {
startTest();
});
var si;
function timer(){
<?php $_SESSION['time']-= 1000; ?>
var count="<?php echo $_SESSION['time']; ?>";
var min = Math.floor(count / (60 * 1000));
var sec = Math.floor((count - (min * 60 * 1000)) / 1000);
min = (min < 10)?'0'+min:min;
sec = (sec < 10)?'0'+sec:sec;
if (count <= 0){
document.getElementById('duration').innerHTML ="Time Up";
clearInterval(si);
// submit my quiz.
}
else {
document.getElementById('duration').innerHTML = "00:" + min + ":" + sec;
}
}
function startTest(){
si = setInterval( "timer()", 1000);
}
</script>
</head>
<body>
<p id="duration" >show time</p>
</body>
</html>`
this code is giving some unexpected error or doesn't work properly.
Remove the double quotes if its an integer
var count=<?php echo $_SESSION['time']; ?>;
What i understand from your description is that you need time duration from server side. so that if any one refresh the browser don't restart the timer from the beginning .
You need to calculate the time duration on server side. That can be achieved by using ajax call.
<?php
session_start();
$_SESSION['start_time'] = time();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// timer will start when document is loaded
$(document).ready( function () {
setInterval(() => {
$.ajax({
url:"timer.php", //path to your file
success:function(data) {
// do your code here
$('#duration').text(data);
}
});
}, 1000);
});
</script>
</head>
<body>
<p id="duration" >show time</p>
</body>
</html>
Create new php file for calculating time timer.php
<?php
session_start();
$start_time = $_SESSION['start_time']; // start time;
$from_time = time(); // current time;
$minutes = round(abs($start_time - $from_time) / 60);
$seconds = abs($to_time - $from_time) % 60;
echo "$minutes minutes & $seconds seconds";
?>
I have a code that is meant to refresh the page on the hour, every hour but it doesn't seem to execute...
This is the code:
<?php
date_default_timezone_set('Australia/Sydney');
$date = date("i:s");
list($cur_min, $cur_sec) = explode(':', $date);
$mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
$secs_left = 60 - $cur_sec;
$time=($mins_left*60+$secs_left)*1000;
?>
<script type="text/javascript">
setInterval("refresh()",<?php echo $time; ?>);
function refresh(){
window.location = location.href;
}
</script>
I need it to run off the server clock too and not from when the user lands on the page.
Idealy, would be awesome if it could just refresh the content of every div labeled with the class named "locality"...
I would use DateTime in PHP and for easy convertion use timestamps.
$date = new \DateTime(strtotime(time()), new \DateTimeZone("Australia/Sydney")));
$date->add(new \DateInterval('PT1H'));
$time = $date->format('U') % 3600;
And for JS:
var time = (Math.round((new Date()).getTime() / 1000) % 3600);
if(time > <?= $time ?>){
var rtime = time - <?= $time ?>;
} else {
var rtime = <?= $time ?> - time;
}
setInterval(function(){
window.location.reload(1);
},rtime * 1000);
But im not sure why:
<meta http-equiv="refresh" content="3600">
Will not suffice as it will just refresh an hour later (and so on) of when the user enters the page, doesn't really matter what timezone.
Try this code for the JavaScript part:
function refresh(){
window.location.reload();
}
setTimeout(refresh, <?php echo $time; ?>);
I'm not sure if it will solve your problem, but I tried a few changes:
window.location.reload() is more explicit than window.location = location.href (which, by the way, could be simplified to window.location = window.location)
setTimeout instead of setInterval because if the refreshing fails again for some reason, you don't want to try refreshing again in
put the setTimeout call after the definition of the function to be sure that there isn't a problem with the function not being defined yet
Try it. If that code still doesn't work for you, try looking at your generated HTML and seeing what value for $time was printed. Also check the browser console for any errors.
By the way, the code would be clearer if you renamed the variable $time to $ms_until_start_of_hour.
I am using a pure JavaScript count down timer that I shared below to redirect to a URL after some time and show the left time to visitor also.
DEMO: JSFiddle
<form name="redirect" id="redirect">
You Will Be Redirected To Next Page After <input size="1" name="redirect2" id="counter"></input>Seconds.
</form>
<script type="text/javascript">
var countdownfrom=5
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=0){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
}
else{
showIt()
return
}
setTimeout("countredirect()",1000)
}
countredirect()
function showIt() {
window.location.href = "http://jsfiddle.net/";
}
</script>
Now I want the same function and features and work in pure PHP as you know that many old mobile browsers still does't not support JavaScript and many are using JavaScript blocker. So Is this possible to do the same in Pure PHP, no <script> tags.
UPDATE:
I know the below codes but I want a count down timer too to show to the visitor.
<?php header('Refresh: 5; URL=http://jsfiddle.net/'); ?>
<meta http-equiv="refresh" content="5;url=http://jsfiddle.net/">
Answer:
This can't be done only with php you will need to use jquery or javascript with it. PHP is a server side scripting language you have to use client side language for this task.
Tip:
For redirecting purpose Just use header() function in php to redirect the php file in some time.Your code should look like this
<?php
header( "refresh:5;url=http://jsfiddle.net" );
?>
Hope this helps you...
Well if you want some output, you can't use header(). Alternatively, you could do something like this:
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 0;
while($x <= 4) {
$x++;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
PHP is a server-side language. You cannot control how the browser behaves from PHP without some quite complex setup. And even that, you cannot guarantee the behaviour of showing a countdown without JavaScript. For browsers who restrict JavaScript execution, the Refresh header will work just fine. However, for those having JavaScript enabled (which is the majority of browsers nowadays, desktop and mobile alike), a simple header will not give any UI feedback and is frustrating for users who expect responsive applications and web pages.
For this reason, JavaScript can be added, if available, to enhance the automatic, delayed, redirection and give the user some feedback of what's going on. Those with JavaScript disabled will just see a static page, telling them that the page will be redirected, and how long they have to wait for it.
PHP
<?php
$redirectTimeout = 5; // seconds
header('Refresh:' . $redirectTimeout . ';url=http://jsfiddle.net');
// ...
// inside your <head>, add this
echo '<meta http-equiv="refresh" ' .
'content="' . $redirectTimeout . ';url=http://jsfiddle.net">';
// ...
// inside your <body>, add this (or something similar)
echo '<div>' .
'You will be redirected to next page after ' .
'<span id="redirectCountdownLabel">' .
$redirectTimeout .
'</span> seconds' .
'</div>';
// ...
// add JS below
JavaScript
For this part, I recommend you use jQuery. It will not only write safer and cross-browser JS, it will also make your code smaller and prettier. This part can be put anywhere in your HTML, or inside a .js file that you add with a <script> tag. For convenience, you can even add jQuery using a CDN.
!function() {
$(function () {
var meta = $('head meta[http-equiv="refresh"]');
var label = $('#redirectCountdownLabel');
var loadTime;
var refreshTimeout;
if (meta.length && label.length) {
loadTime = window.performance.timing.domComplete;
refreshTimeout = parseInt(meta.attr('content'), 10); // seconds
new Timer(refreshTimeout * 1000, loadTime).start(200, function (elapsed) {
// "elapsed" ms / 1000 = sec
label.text(refreshTimeout - parseInt(elapsed / 1000));
});
}
});
function Timer(maxTime, startTime) {
var timeout;
var callback;
startTime = startTime || Date.now();
function nextTimer(delay) {
timeout = setTimeout(function () {
var curTime = Date.now();
var elapsedTime = curTime - startTime;
callback(elapsedTime);
if (elapsedTime < maxTime) {
nextTimer(delay);
}
}, delay);
}
this.start = function start(ms, cb) {
stop();
callback = cb;
nextTimer(ms);
};
this.stop = function stop() {
if (timeout) {
clearTimeout(timeout);
}
};
};
}();
(Note: here's a jsfiddle of the Timer class.)
scusate per prima, ho postato male, sono ali inizi, sorry
<?php
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
To do the countdown, so it seems to work or am I wrong?
<?php
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh"content="0;url=http://jsfiddle.net/">';
?>`
I have 2 files.
Home.php
some_func.php
I am setting a session variable in home.php and I am having an ajax call to some_func.php on button click.
Issue:
When I load the page for the first time, the session variable is set in home.php but the same is not reflected in some_func.php and if I reload home.php and then after that the session variable value is reflected in some_func.php.
I don't know why the session variable value is not getting reflected when I load home.php for the first time.
I have found that this is happening only on my live server and not on my localhost.
Please help.
<?php
//home.php file
session_start();
include 'db.inc.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die('Unable to connect. Check connection parameters');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
//Checking what is the latest session id available available in my db.
$query = "SELECT max(ses_id) as max_ses_id FROM `dyn_sess` ";
$result = mysql_query($query, $db) or die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$_SESSION['curr_sess'] = $row['max_ses_id']+1;
}
echo '<script> alert("Your Session ID : '.$_SESSION['curr_sess'].'");</script>';
?>
<html lang="en">
<head>
</head>
<body>
<meta charset="utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function call_some_func()
{
$.post('some_func.php');
}
</script>
<input type="button" value="PREV" onClick=call_some_func()>
</body>
</html>
<?php
//some_func.php
session_start();
require_once('lib/something.php');
// some php code here.
// No sessions variable are set. But the session variable curr_sess is used to call an api and that goes as blank for the first time.
//If I reload home.php it works fine then after from the second time.
?>
<html>
<script> alert(<?php echo $_SESSION['curr_sess'] ?>); </script>
</html>