How To Make a PHP Script Synchronously Update From Terminal Values - php

Using a Raspberry Pi I created a script which loads the CPU Temperature of the Pi through an Apache Server onto the Browser.
<?php
$temp = exec('vcgencmd measure_temp');
$temp = str_replace('temp=','',$temp);
$temp = str_replace('\'C','',$temp);
echo $temp;
?>
Using the code above I have to manually refresh the page to see the latest value.
It works fine but I'd like to know how I could set this up without having to refresh the browser all the time.
Within the Terminal on the Pi I was able to use the "watch" command which will give me the current value every 0.1 seconds.
But by executing this script, the browser will give me a blank page.
<?php
$temp = exec('watch -n 0.1 vcgencmd measure_temp');
$temp = str_replace('temp=','',$temp);
$temp = str_replace('\'C','',$temp);
echo $temp;
?>
Is there any way to make the script using the "watch" command work with the PHP Script? If not, is there any other way to make it refresh everytime the value changes in the terminal?
Note: I am new to programming and using the Pi.
I would really appreciate any helpful information!
Thank you in advance!

Watch wont work in your case, you can call jquery cdn from official website and then do this function. Do not forget to open console to see what comes back. F12
Add this into your php file.
if(isset($_GET)){
$temp = exec('vcgencmd measure_temp');
$temp = str_replace('temp=','',$temp);
$temp = str_replace('\'C','',$temp);
echo $temp;
}
Then into your index.html
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh,1000); // 1000 represents 1 second, free to change
$.get('index.php', function(data) { // i assume your index.php in same folder with your html file.
console.log(data);
});
}

I actually found a easier way to set this up.
What I wanted to do was not having to manually refresh the page in order to get the current temperature values.
The answers above were correct but I wasn't able to set it up by myself so I figured out I can add a header and refresh into my PHP script which will make the page refresh every second (or whatever timeframe is needed).
The code looks like this now:
<?php header('refresh: 1');
$temp = exec('vcgencmd measure_temp');
$temp = str_replace('temp=','',$temp);
$temp = str_replace('\'C','',$temp);
echo $temp;
?>
Thank you to everyone who was trying to help me!

Related

PHP - Saving array to file - Not stacking up

Really stumped on this one and feel like an idiot! I have a small PHP cron job that does it's thing every few minutes. The client has requested that the app emails them with a daily overview of issues raised....
To do this, I decided to dump an array to a file for storage purposes. I decided against a SQL DB to keep this standalone and lightweight.
What I want to do is open said file, add to a set of numbers and save again.
I have tried this with SimpleXML and serialize/file_put_contents.
The issue I have is what is written to file does not correspond with the array being echo'd the line before. Say I'm adding 2 to the total, the physical file has added 4.
The following is ugly and just a snippet:
echo "count = ".count($result);"<br/>";
$arr = loadLog();
dumpArray($arr, "Pre Load");
$arr0['count'] = $arr['count']+(count($result));
echo "test ".$arr0['count'];
dumpArray($arr0, "Pre Save");
saveLog($arr0);
sleep(3);
$arr1 = loadLog();
dumpArray($arr1, "Post Save");
function saveLog($arr){
$content = serialize($arr);
var_dump($content);
file_put_contents(STATUS_SOURCE, $content);
}
function loadLog(){
$content = unserialize(file_get_contents(STATUS_SOURCE));
return $content;
}
function dumpArray($array, $title = false){
echo "<p><h1>".$title."</h1><pre>";
var_dump($array);
echo "</pre></p>";
}
Output View here
Output File: a:1:{s:5:"count";i:96;}
I really appreciate any heads up - Have had someone else look who also scratched his head.
Check .htaccess isn't sending 404 errors to the same script. Chrome was looking for favicon.ico which did not exist. This caused the script to execute a second time.

php script longer than max execution time (progress bar)

i currently work on a small project, where some data is gathered from the web and the system creates some relations between these. Of course it was not perfect from the beginning, so i needed to make a script which updates all the connections and relations with the updated scripts i made.
Basically the script works, but as there shall be a nice looking backend afterwards, its not really what i want.
The script needs around 10 minutes and because i didnt just want to set up the max_execution_time from php i thought of another method. Instead of loading 1000 sql entries at once i stripped it down to 200 at one time and just repeat it with the next 200 when the first round finished. Therefore i used php http_request. I just show you a stripped down version of the script:
require_once 'HTTP/Request.php';
$max = $db->query("SELECT COUNT(id) as max FROM db_table");
$lower = $_POST['lower'] ? $_POST['lower'] : 0;
$plus = 250;
$entries = $db->query("SELECT * FROM db_table LIMIT {$lower},{$plus}");
foreach($entries as $entry){
DO SOME STUFF TO UPDATE THE RELATIONS BETWEEN THE DATA
}
$lower = $lower + $plus;
if($lower <= $max) {
$request = new HTTP_Request("path to the script");
$request->setMethod(HTTP_REQUEST_METHOD_POST);
$request->addPostData("lower", $lower);
$result = $request->sendRequest();
}
This is it. As i said it works, because it's a new request so that it's not affected by the max_execution_time. But the browser is just loading and loading and loading and after a while it finishes. But of course i cannot show any refreshed data for something like a progress bar.
I saw many entries using php flush(), but that didnt work for me because of the (i guess) stupid way i used to solve my problem.
How would you do this if you need to install something on a webspace and you dont have the possbility to change the max execution time or install http_request?
As i said it should look like a progress bar later on. I guess i have to use ajax, and simply push the round the script is at every round and update the progress bar via javascript.
Can you help me?
You are still having trouble with max_execution_time because the page you requested from web browser is always active one, it doesn't finish until the HTTPRequests finishes. Try locating the page to another with the parameter lower.
header("Location: myscript.php?lower=$lower");

After 60 seconds on website, popup

Well, i was trying to reach a solution and i thought this might work:
On the PHP file:
$liguem = getdate();
$liguemoff = $_COOKIE['liguemoff'];
$liguemon = $_COOKIE['liguemon'];
if(empty($liguemoff)){
setcookie('liguemoff',$liguem[0],time() + (50000));
}
setcookie('liguemon',$liguem[0],time() + (20000));
$body->assign("COOKIE2", $liguemoff);
$body->assign("COOKIE3", $liguemon);
This has some body assign because I'm working with XTemplate, but the PHP is just PHP.
Now on the index file, some JavaScript:
var cookie2 = {COOKIE2};
var cookie3 = {COOKIE3};
if( cookie3-cookie2 > 60){
alert('alerta');
};
Truth is that it works! People might not be navigating, but it is what i want, the pop up will only open after the visitor sees at least 2 pages (Server-side thing).
The main problem is, that i CAN'T make the function popup(); to trigger where i have the ALERT displaying. The ALERT is working alright though.... Any hints?
PS:
This is the popthat(); function:
function popthat(){
$("#darkside").css('opacity','0.3').fadeIn('slow');
$("#darkside").click(function () {
$(this).css('opacity','1').fadeIn('fast');
$("#liguem").hide();
});
$("#liguem").corner();
$("#liguem").hide();
$("#liguem").delay(200).css('visibility','visible');
$("#liguem").fadeIn('fast');
}
You can set a timeout to display your popup after a specified amount of time. This amount of time can be dicated by your PHP since the server-side code will be able to track the amount of time on the site through page-views. This way the popup can display after 60 seconds on the site even if the user is not navigating to another page.
Something like:
setTimeout(popthat, <?php echo $_COOKIE[...]; ?>);
Your PHP would echo the number of milliseconds until the popup should display.
A note: when you replace your alert() with the popthat() function the DOM may not be ready and popthat() won't be able to work because it won't find any elements that match your selectors. Try running your code on document.ready ($(function() {});).
Browsers automatically block popups initialized on page load, because nobody likes these sorts of popups.
When you do an alert(), execution of your script stops. alert() is a blocking function, and nothing will happen until it has moved on.
I don't know if you just made a typo, but your function is called popthat(), and in your statement you said you called the function popup(). You need to change popup(); to popthat(); for this to work, unless as I said that was a mistake.

php refresh on 2nd page refresh

i have this function that gives me an output of a number. (the number is my total amount of downloads from my iphone themes.)
because the code has to make so many requests, it loads the page very slowly.
what would be the best way for me to go about the code loading into a variable and than calling it on the second page refresh. so it dosnt take so long to load?
or any other method will do. i just want it to not take so long to load!
also this isnt on my server so i cant use $.ajax
<?php
function all_downloads() {
$allThemes = array(
'com.modmyi.batterytheme',
'com.modmyi.connectiontheme',
'com.modmyi.icontheme',
'com.modmyi.percenttheme',
'com.modmyi.statusnotifiertheme',
'com.modmyi.cnote',
'com.modmyi.iaccescnotekb',
'com.modmyi.cnotelite',
'com.modmyi.multibrowsericon',
'com.modmyi.changeappstoreiconwithinstallous'
);
$total = 0;
foreach($allThemes as $com_modmyi){
$theme = file_get_contents( "http://modmyi.com/cstats/index.php?package=".$com_modmyi.'&output=number');
$theme = str_replace(",","", $theme);
$almost_done += $theme;
$rock_your_phone = 301; //From c-note and Multi Lock Screen Theme on Rock Your Phone
$total = ($almost_done + $rock_your_phone);
}
echo number_format($total);
}
?>
call the function with AJAX !
Th basic idea of using ajax is to to help make web applications function more like desktop applications
most actions that an end-user takes in his or her browser send a request back to the web server. The server then processes that request, perhaps sends out further requests, and eventually responds with whatever the user requested. <--whats your problem is ** **(slow !)
with AJAX you can call a PHP function with out reloading a page
please go though this tutorial which is really simple

Crazy buffer from Ajax and php script

I have a PHP web crawler that just checks out websites. I decided a few days ago to make the crawlers progress show in real time using AJAX. The php script writes to a file in JSON and AJAX reads the tiny file.
I double and triple checked my PHP script wondering what the hell was going on because after I finished the simple AJAX script the data appearing on my browser leaped up and down in strange directions.
The php script executed perfectly and very quickly but my AJAX would slowly increase the values, every 2 seconds as set, then drop. The numbers only increase in PHP they do not go down. However, the numbers showing up on my webpage go up and down as if the buffer is working on multiple sessions or reading from something that is being updated even though the PHP stopped about an hour ago.
Is there something I'm missing or need to keep clear like a buffer or a reset button?
This is the most I can show, I just slapped it together a really long time ago. If you know of better code then please share, I love any help possible. But, I'm sort of new so please explain things outside of basic functions.
AJAX
//open our json file
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//display json file contents
document.form.total_emails.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test_results.php", true);
ajaxRequest.send(null);
PHP
//get addresses and links
for($x=(int)0; $x<=$limit; $x++){
$input = get_link_contents($link_list[0]);
array_shift($link_list);
$link_list = ($x%100==0 || $x==5)?filter_urls($link_list,$blacklist):$link_list;
//add the links to the link list and remove duplicates
if(count($link_list) <= 1000) {
preg_match_all($link_reg, $input, $new_links);
$link_list = array_merge($link_list, $new_links);
$link_list = array_unique(array_flatten($link_list));
}
//check the addresses against the blacklist before adding to a a file in JSON
$res = preg_match_all($regex, $input, $matches);
if ($res) {
foreach(array_unique($matches[0]) as $address) {
if(!strpos_arr($address,$blacklist)){
$enum++;
json_file($results_file,$link_list[0],$enum,$x);
write_addresses_to_file($address, $address_file);
}
}
}
unset($input, $res, $efile);
}
The symptoms might indicate the PHP script not closing the file properly after writing, and/or a race condition where the AJAX routine is fetching the JSON data in between the PHP's fopen() and the new data being written.
A possible solution would be for the PHP script to write to a temp file, then rename to the desired filename after the data is written and the file is properly closed.
Also, it's a good idea to check response.status == 200 as well as response.readyState == 4.
Tools like ngrep and tcpdump can help debugging this type of problem.

Categories