Continuously updating php page - php

I have created a php page to display a image from a set of five images. The image is displayed based on the data read from a text file.Another application is continuously updating data in that text file.So my php page need to read data from that file whenever the file is updated and display image based on that data. I created a infinite loop to read data. But when i tried to access the php page from a browser , it is not loading because of the infinite loop.
$myfile1 = fopen("readfile.txt", "r") or die("Unable to open file!");
$readJsonData = fread($myfile1,filesize("readfile.txt"));
fclose($myfile1);
$obj = json_decode($readJsonData);
$urllogo = 'tatalogo.png';
if(($obj->{"FrontLeft"}) == "TRUE")
{
$url = 'images/FrontLeft.png';
}
else if(($obj->{"FrontRight"}) == "TRUE")
{
$url = 'images/FrontRight.png';
}
else if(($obj->{"RearLeft"}) == "TRUE")
{
$url = 'images/RearLeft.png';
}
else if(($obj->{"RearRight"}) == "TRUE")
{
$url = 'images/RearRight.png';
}
else
{
$url = 'images/Normal.png';
}
// infinite loop
while(1)
{
//reading from the file and refreshing the page.
}

In PHP Set header like this to refresh the php page
header("Refresh: 5;url='pagename.php'");
In HTML Head tag
<html>
<head>
<meta http-equiv="refresh" content="5;URL='pagename.php'">
</head>
</html>
<?php
Your php script here..
?>
Using Javascript
<script type="text/javascript>
window.setInterval(function(){
reload_page();
}, 5000);
//Here 5000 in miliseconds so for 5 seconds use 5000
function reload_page()
{
window.location = 'pagename.php';
}

The most reasonable way to do it would be to use the client side to refresh the page.
Get rid of all that infinite loop stuff on the PHP side. PHP will only output the image as it stands at the moment it was generated.
On the client side you could do something as simple as:
<META http-equiv="refresh" content="5;"> to force a refresh every 5 seconds.
If you only want to update when the file is updated you have to get more advanced. You could do an ajax call that checks if the file has changed and if so it refreshes. Websockets would be another option.
You could possibly do some nasty hack on the PHP side to make it work using ob_flush and sleep and header within a loop that checks to see if the file has changed but this will cause you to lose sleep once you realize what you've done. As pointed out below, this would never work.

Related

PHP site problems

My code of file.php:
<?php
if(!isset($_GET['filename']) OR $_GET['filename'] == NULL) {
print("Error!");
exit();
}
$_GET['filename'] = htmlentities($_GET['filename'], ENT_QUOTES, "utf-8");
session_start();
include_once("/var/www/html/get.php");
for($i = 0; $i < $GLOBALS['files']['ile']; $i++) {
if($GLOBALS['files'][$i]['name'] == $_GET['filename']) {
if($GLOBALS['files'][$i]['priv'] == NULL OR $GLOBALS['files'][$i]['owner'] == $_SESSION['id'] OR (isset($_SESSION['privs']) AND in_array($GLOBALS['files'][$i]['priv'], $_SESSION['privs']))) {
if(file_exists($GLOBALS['files'][$i]['loc'])) {
header("Content-length: ".filesize($GLOBALS['files'][$i]['loc']));
header("Content-type: ".mime_content_type($GLOBALS['files'][$i]['loc']));
readfile($GLOBALS['files'][$i]['loc']);
} else {
print("Can't find that file!");
}
}
}
}
?>
In get.php file, I loads (from database) information about files I wanted to have access using that file above in site.
$_SESSION['privs'] //it's an array that holds privileges, i.e: site.priv.mess
$GLOBALS['files'] //holds info about all files that user can load, i.e: $GLOBALS['files'][0]['name'] is a name of first file in array
$GLOBALS['files'][0]['loc'] //holds info about first file localisation
$GLOBALS['files']['ile'] // holds sizeof($GLOBALS['files'])
With pictures that works well, but if I try to load larger file, i.e. video that weights 300MB, then file loads, all looks good, but if I reloads site, it won't work anymore...
I tried to delete my cookies in browser (to change my session ID) and it works... But what can I do to make it works better?
EDIT: On Firefox all looks good, only freezes on Chrome :(
EDIT2: Closing session with: session_write_close(); before reading file fixed my curse :P Thanks y'all
Check your php.ini or use phpinfo() to check your values for upload_max_filesize, post_max_size and memory_limit. Maybe also check the max execution time of the php script.

How to check an IF statement every 5sec in PHP?

I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/

View full site with cookies, javascript and mobile redirect

I have a website(www.website.com) and a mobile site (m.website.com) and I'm trying to allow users to "View Full Site" if they want from mobile. Currently I am using some Javascript to check screen width on full site then redirecting to mobile.
if (screen.width <= 699) {
document.location = "http://m.website.com";
}
This works fine. On the mobile site there is a "View Full Site" button. When you click this it redirects you to my script "force_desktop.php" which sets a cookie and then sends you to the main site.
<?php
setcookie("force_desktop", "1");
header("Location: http://www.mywebsite.com");
?>
Now that we set a cookie and redirected to the main website we need to check for the cookie instead of just checking for the screen width.
Logic
If Cookie force_desktop is found
Then exit
Else
run screen size test
Here is the code I attempted to use but doesn't work. This code is placed in my head.php file which will be run on every page and is placed between the script opening and closing tags.
Attempt 1
if($_COOKIE['force_desktop'] == '1' {
exit;
} else if($_COOKIE['force_desktop'] != '1' {
if (screen.width <= 699) {
document.location = "http://m.website.com";
}
};
Attempt 2
if(isset ($_COOKIE["force_desktop"])){
exit;
else
if (screen.width <= 699) {
document.location = "http://m.mywebsite.com";
};
Alternative logic that could work
IF Cookie force_desktop is not found AND screen.width <= 699
Then redirect to m.myseite.com
Else
Exit
Note
I have run the following script to make sure a cookie is being placed, and it is.
<?php
print_r($_COOKIE);
?>
I've run out of ideas and know my coding isn't correct, especially the If/Else statement within the If/Else statement. I also am not sure if it is better to use the "isset" to see if the cookie is being used or ($_COOKIES['variable'] == "#"). I'd really appreciate some good feedback on this one.
Thanks in advance for your help and suggestions,
Matt
You're mixing JavaScript and PHP. You're trying to use screen.width in your PHP script, which doesn't make sense. You need to use an echo statement to output the JavaScript into the page. It'll then check the user's screen resolution and do the redirect.
Try this:
if(isset ($_COOKIE["force_desktop"])){
exit;
}
else
{
echo '<script>
if (screen.width <= 699) {
document.location = "http://m.mywebsite.com";}
</script>';
};
you should do this test at the top of the php page, and for sure you cannot mix php and java script like this
u can alter this code like
<?php
$flag = 0;
if(isset($_COOKIE['force_desktop']))$flag++;
?>
later in the page use the code as soon as <head> tag starts
..
..
<head>
<?php
if(!$flag){
echo '<script>
if (screen.width <= 699) {
document.location = "http://m.mywebsite.com";
</script>';
}
?>
You cannot mix javascript and PHP, javascript is front end and PHP is back end. Try something like this:
if( $something ){
Header("Location: somewhere.php");
}

getting javascript error object required

Iam getting offsetwidth of an div tag. Below is code.
<body>
<div id="marqueeborder" onmouseover="pxptick=0" onmouseout="pxptick=scrollspeed">
<div id="marqueecontent">
<?php
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// List your stocks here, separated by commas, no spaces, in the order you want them displayed:
$stocks = "idt,iye,mill,pwer,spy,f,msft,x,sbux,sne,ge,dow,t";
// Function to copy a stock quote CSV from Yahoo to the local cache. CSV contains symbol, price, and change
function upsfile($stock) { copy("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=sl1c1&e=.csv","stockcache/".$stock.".csv"); }
foreach ( explode(",", $stocks) as $stock ) {
// Where the stock quote info file should be...
$local_file = "stockcache/".$stock.".csv";
// ...if it exists. If not, download it.
if (!file_exists($local_file)) { upsfile($stock); }
// Else,If it's out-of-date by 15 mins (900 seconds) or more, update it.
elseif (filemtime($local_file) <= (time() - 900)) { upsfile($stock); }
// Open the file, load our values into an array...
$local_file = fopen ("stockcache/".$stock.".csv","r");
$stock_info = fgetcsv ($local_file, 1000, ",");
// ...format, and output them. I made the symbols into links to Yahoo's stock pages.
echo "<span class=\"stockbox\">".$stock_info[0]." ".sprintf("%.2f",$stock_info[1])." <span style=\"";
// Green prices for up, red for down
if ($stock_info[2]>=0) { echo "color: #009900;\">↑"; }
elseif ($stock_info[2]<0) { echo "color: #ff0000;\">↓"; }
echo sprintf("%.2f",abs($stock_info[2]))."</span></span>\n";
// Done!
fclose($local_file);
}
?>
<span class="stockbox" style="font-size:0.6em">Quotes from Yahoo Finance</span>
</div>
</div>
</body>
below is the javascript function which will be called onlaod of the page.
<script type="text/javascript">
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// Set an initial scroll speed. This equates to the number of pixels shifted per tick
var scrollspeed=2;
var pxptick=scrollspeed;
function startmarquee(){
alert("hi");
// Make a shortcut referencing our div with the content we want to scroll
var marqueediv=document.getElementById("marqueecontent");
alert("marqueediv"+marqueediv);
alert("hi"+marqueediv.innerHTML);
// Get the total width of our available scroll area
var marqueewidth=document.getElementById("marqueeborder").offsetWidth;
alert("marqueewidth"+marqueewidth);
// Get the width of the content we want to scroll
var contentwidth=marqueediv.offsetWidth;
alert("contentwidth"+contentwidth);
// Start the ticker at 50 milliseconds per tick, adjust this to suit your preferences
// Be warned, setting this lower has heavy impact on client-side CPU usage. Be gentle.
var lefttime=setInterval("scrollmarquee()",50);
alert("lefttime"+lefttime);
}
function scrollmarquee(){
// Check position of the div, then shift it left by the set amount of pixels.
if (parseInt(marqueediv.style.left)>(contentwidth*(-1)))
marqueediv.style.left=parseInt(marqueediv.style.left)-pxptick+"px";
// If it's at the end, move it back to the right.
else
marqueediv.style.left=parseInt(marqueewidth)+"px";
}
window.onload=startmarquee();
</script>
when iam running the above code on server, iam getting javascript error as "object required" at line 46 also the alert("marqueediv"+marqueediv); is "marqueedivnull" after that alert iam getting the javascript error.
Here my question is, did the div tag is not getting recognized?why?
so that only it is getting as null object, how can i resolved this?
Thanks.
You are calling startmarquee immediately and trying to assign its return value (undefined) to window.onload.
Presumably the script appears in the <head> and this the div does not exist at the time you run it.
Assign the function to onload, not its return value.
window.onload=startmarquee;
You could copy the script and put it before the body closing tag and remove window.onload=startmarquee(); thus making sure all elements have been loaded and accessible
Just like #Quentin said, that element with the id might not have been loaded into the DOM when you referenced it

Refresh Page after update php

i need a javascript to help me refresh my page after i update the data. i have coded out t
he update function all i need to refresh the page after the data is updated how do i do that.
This is what i have done so far
<?php
mysql_connect("localhost","fbappsadmin","dbP#ssw0rd") or die(mysql_error()) ;
mysql_select_db("jetstardatabase") or die(mysql_error()) ;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$options = array(
'1' => 1,
'2' => 2,
);
if (isset($_POST['list'])) {
$value = (int)$_POST['list'];
} else {
$value = 0; // default value;
}
$cmeter = $cmeter - $value;
mysql_query("INSERT orders SET quantity='$value',fbId='$fbme',fbName='$fbName', email ='$fbEmail', dealName='$dealName'" );
mysql_query("UPDATE stardeal SET cmeter='$cmeter'WHERE dealId='$dealId'");
}
?>
Just put this PHP at the end of your update logic, it must be before any HTML output;
header("Location: /mypage.html");
Web pages work like this:
page (client) -> request (made in url) (server) -> new page (client)
By sending a request to the server, the server generates the new page and serves it back to the browser. You have the middle part, you need the entry and exit pages.
Like blake said, ajax or PHP would probably be prefered. Otherwise, to answer your question, you can use:
document.location = window.location.href
If you need javascript, then use this code:
<script>window.top.location='mypage.html'</script>
You cannot refresh your browser page using PHP. You have to use either META or Javascript.
Using Meta tag inside <HEAD> and </HEAD>:
<meta http-equiv="refresh" content="0; url=http://example.com/">
Using Javascript:
location.reload(true)

Categories