Get Linux System Last Boot Time - php

From a PHP script I need to get the last system boot time, preferably in the UNIX time stamp format.
Are there any files that are created or modified at boot time? I could read the modified time of the file.
The system type is CentOS.

/proc/uptime
This file contains two numbers: the uptime of the system (seconds), and the amount of time spent in idle process (seconds).
<?php
function get_boottime() {
$tmp = explode(' ', file_get_contents('/proc/uptime'));
return time() - intval($tmp[0]);
}
echo get_boottime() . "\n";

Try this:
Method 1
<?php
$uptime = trim( shell_exec( 'uptime' ) );
// output is 04:47:32 up 187 days, 5:03, 1 user, load average: 0.55, 0.55, 0.54
$uptime = explode( ',', $uptime );
$uptime = explode( ' ', $uptime[0] );
$uptime = $uptime[2] . ' ' . $uptime[3]; // 187 days
?>
Method 2
<?php
$uptime = trim( file_get_contents( '/proc/uptime' ) );
$uptime = explode( ' ', $uptime[0] );
echo $uptime[0];//uptime in seconds
?>
Hope it helps.

who -b # in command-line
Gives you the last boot time (http://www.kernelhardware.org/find-last-reboot-time-and-date-on-linux/)
exec ( $command , $output ); // in PHP
Executes a shell command
strtotime(); // in PHP
Parse about any English textual datetime description into a Unix timestamp
So this will give you the Linux System last boot time :
// in PHP
exec('who -b',$bootTime);//where $bootTime is an array, each line returned by the command is an element of the array
$result = strtotime($bootTime[1]);

Related

Calculating RSI from Poloniex PHP

I'm trying to calculate the RSI using the Poloniex API and PHP Trader EXtension. Here is what i have so far.
date_default_timezone_set( 'UTC' );
$api = new poloniex( 'xxxxxxx', 'xxxxx' );
$data = $api->getChartValues( 'BTC_LTC', strtotime( "-21 hours" ), time(), 300 );
print_r( $data);
$rsi = array();
foreach ( $data as $a )
{
$rsi[] = $a['close'];
}
$rsi = trader_rsi( array_reverse($rsi) , 14 );
The getChartValues calls the returnChartData API Function from Poloniex API.
After running the script, the output RSI is completely different than the valid one.
What i'm doing wrong?
maybe there is no need to reverse, here is my code that works fine
$rsi = array();
foreach ( $data as $a )
{
$rsi[] = $a['close'];
}
$rsi = trader_rsi( $rsi , 14 );
print_r( $rsi );
According to the RSI definition:
The relative strength index is calculated using the following formula:
RSI = 100 - 100 / (1 + RS)
Where RS = Average gain of up periods during the specified time frame / Average loss of down periods during the specified time frame/
[...]
The default time frame for comparing up periods to down periods is 14, as in 14 trading days.
Are you sure that the RS parameter in your computation is exactly the same than in "the valid one" ? And according to you what is "the valid one" source ?

How can I get the time of a remote server?

I am currently working on a websever that will create a quick diagnose dashboard of other servers.
My requirement is to display the time of these remote servers, it seems that the NTP create some issues and I would like to see that.
I currently have a bat file on my desktop that simply send
net time \\SRV*******
I have also tried:
echo exec('net time \\\\SRV****');
=> result is '0'
But I would like to find a better solution in PHP so anybody of a team can read it on a webpage.
Any idea what I would do?
Note: this is not related to How to get date and time from server ad I want to get the time of a REMOTE server and not local server
You can use NTP protocol to retrieve datetime from a remote server.
Try this code:
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
date_default_timezone_set("Europe/...");
function query_time_server ($timeserver, $socket)
{
$fp = fsockopen($timeserver,$socket,$err,$errstr,5);
# parameters: server, socket, error code, error text, timeout
if ($fp) {
fputs($fp, "\n");
$timevalue = fread($fp, 49);
fclose($fp); # close the connection
} else {
$timevalue = " ";
}
$ret = array();
$ret[] = $timevalue;
$ret[] = $err; # error code
$ret[] = $errstr; # error text
return($ret);
}
$timeserver = "10.10.10.10"; #server IP or host
$timercvd = query_time_server($timeserver, 37);
//if no error from query_time_server
if (!$timercvd[1]) {
$timevalue = bin2hex($timercvd[0]);
$timevalue = abs(HexDec('7fffffff') - HexDec($timevalue) - HexDec('7fffffff'));
$tmestamp = $timevalue - 2208988800; # convert to UNIX epoch time stamp
$datum = date("Y-m-d (D) H:i:s",$tmestamp - date("Z",$tmestamp)); /* incl time zone offset */
$doy = (date("z",$tmestamp)+1);
echo "Time check from time server ",$timeserver," : [<font color=\"red\">",$timevalue,"</font>]";
echo " (seconds since 1900-01-01 00:00.00).<br>\n";
echo "The current date and universal time is ",$datum," UTC. ";
echo "It is day ",$doy," of this year.<br>\n";
echo "The unix epoch time stamp is $tmestamp.<br>\n";
echo date("d/m/Y H:i:s", $tmestamp);
} else {
echo "Unfortunately, the time server $timeserver could not be reached at this time. ";
echo "$timercvd[1] $timercvd[2].<br>\n";
}
You can use a powershell script along with WMI (assuming your servers are windows machines)
This will be way faster than the old net time style.
The script needs to be executed with a Domain-Admin (or any other user that has WMI-query permissions)
$servers = 'dc1', 'dc2', 'dhcp1', 'dhcp2', 'wsus', 'web', 'file', 'hyperv1', 'hyperv2'
ForEach ($server in $servers) {
$time = "---"
$time = ([WMI]'').ConvertToDateTime((gwmi win32_operatingsystem -computername $server).LocalDateTime)
$server + ', ' + $time
}
You can achieve this with a scheduled task every 5 minutes.
If you want to display the time "with seconds / minutes" (I wouldn't query each server too often, as time does not change THAT fast), you could add a little maths:
When executing the script, don't store the actual time, but just the offset of each server, compared to your webservers time. (i.e. +2.2112, -15.213)
When your users are visiting the "dashboard" load these offsets and display the webservers current time +/- the offset per server. (Could be "outdated" by some microseconds then, but do you care?)
Why so complicated?
Just found that this is working:
echo exec('net time \\\\SRV****, $output);
echo '<pre>';
print_r($output);
echo '</pre>';

Php microtime() is not working on live site. Looking for workaround

I have Zend Server 6.3 and Php 5.4 on Windows. And system works very well. Now I moved code to live site, which runs Php 5.3.29 on Ubuntu Server with DirectAdmin. All other website are running well there. But my current website gives me this error (the site is on WordPress 4.3):
Warning: mysql_connect(): Headers and client library minor version mismatch.
Headers:50541 Library:50623 in /home/cheapauto/domains/*DOMAIN*/public_html/wp-includes/wp-db.php on line 1482
Parse error: syntax error, unexpected '[' in /home/*USER*/domains/*DOMAIN*/public_html/wp-content/plugins/*MY-PLUGIN*/includes/final.class.NRSBooking.php on line 101
The line is this:
$now = explode(' ', microtime())[1];
And my whole plugin function is this:
private function getIncrementalHash($length = 5)
{
//$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$charset = "ABCDEFGHIJKLMNPRSTUVYZ"; // fits LT & EN, O is skipped to similarity to Zero
$charsetLength = strlen($charset);
$result = '';
$now = explode(' ', microtime())[1];
while ($now >= $charsetLength)
{
$i = $now % $charsetLength;
$result = $charset[$i] . $result;
$now /= $charsetLength;
}
return substr($result, -$length);
}
Any ideas how to make it work on live site?
As per Php reference http://php.net/manual/en/function.microtime.php
it says:
microtime() returns the current Unix timestamp with microseconds. This
function is only available on operating systems that support the
gettimeofday() system call.
And I use that function to generate unique new booking code:
$newBookingCode = "R".$validNextMySQLInsertId."A".$this->getIncrementalHash(5);
Thank you!
Array dereferencing, i.e. getting results from function which returns array like:
$now = explode(' ', microtime())[1];
is available since php5.4
For php5.3 and older use:
$now = explode(' ', microtime());
$now = $now[1];

Appending multiple entries to an output file with a crontab using php?

I am writing a script in PHP in which I had to write the system uptime, the current time, and the amount of users logged in the system into a log file, and be updated continually via a crontab.
What I need help with is that I would like the updates to accumulate within the file and be added continually. So far, whenever my script gets executed, the newest update overwrites the previous update.
What I've done is that I tried to declare an array of entries and as I iterate through the array push the contents of the update into the array (It might be a bit of half-baked logic on my part).
My Code:
$fileName = '../so-and-so directory/output.log';
$dt = date('m/d/y');
$time = date('h:i A');
$data = shell_exec('uptime');
$uptime= explode(' up ', $data);
$uptime = explode(', ', $uptime[1]);
$uptime = $uptime[0].','.$uptime[1];
$users = system('w', $who);
$array = new SplFixedArray(3);
$fileLog = fopen($fileName, 'w');
$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n".
"System uptime ". $uptime ."\n" ."Users " . $users;
foreach ($array as $entry) {
array_push(file_put_contents($fileName, $fileString));
}
fclose($fileLog);
I feel that the solution is very simple but I'm missing it. Would somebody please clue me in?
The "w" filemode truncates the file on open. "a" appends to the end instead. See fopen(3) or the PHP documentation for details.
Also, file_put_contents() is destroying the file. Try fwrite() instead.
drop fopen; simply use
file_put_contents($fileName, $fileString);
file_put_contents will overwrite the existing file by default.
In short:
$fileName = '../so-and-so directory/output.log';
$dt = date('m/d/y');
$time = date('h:i A');
$data = shell_exec('uptime');
$uptime= explode(' up ', $data);
$uptime = explode(', ', $uptime[1]);
$uptime = $uptime[0].','.$uptime[1];
$users = system('w', $who);
$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n".
"System uptime ". $uptime ."\n" ."Users " . $users;
file_put_contents($fileName, $fileString);
So it turns out that I needed to edit my crontab file as such:
* * * * * such-and-such-script.php >> ../so-and-so directory/output.log 2>&1
To make them append without the previous one being overwritten by the new one. I also lost the fopen() and instead of doing file_put_contents, I did fwrite() into the file. It works great now. Thank you!

php slow lag when login

i am developing a new section on my site and ive notice a small latency when login. on my computer it works great but when i put it to th eserver it is slower. the login process is slower on the server and not on my cmoputer.
half second to 1 second slower
i have doubt on my hosting that is not as fast as they say since on my computer its fast.
is there a way i can monitor the speed of the server command line or php script i can run to find out what's wrong?
Put these three lines of code in various places in your script (replacing "foo" with a description of where you place it in the code):
$h = fopen('log.txt', 'a');
fwrite($h, 'foo: ' . microtime(true));
fclose();
Then, run your script, and you can see which part is slow.
At the top of the script, put
<?php
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$start_time = microtime_float();
and at the end
$exec_time = microtime_float() - $start_time;
echo 'Page loaded in: ' . $exec_time . 'seconds';
?>
Compare your local copy with the remote copy.

Categories