Unexpected T_ELSE [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I've got a piece of code that I created and I've been 'requiring_once' in to my PHP code for quite a while now. It works fine on my local PC, but when I upload it to my server it's coming up with the following error:
Parse error: syntax error, unexpected T_ELSE in /home/makequiz/public_html/nitpicker/func.php on line 47
Here's the function:
function howLongAgo($unix_time) {
// This function shows the unix time stamp
// as number of seconds, minutes, hours, days, months, years ago
// Get the time difference between time specified and the current unix time
$time_difference = time () - $unix_time;
$seconds_ago = $time_difference;
$minutes_ago = $time_difference / 60;
$hours_ago = $time_difference / 3600;
$days_ago = $time_difference / 86400;
$months_ago = $time_difference / 2629743;
$years_ago = $time_difference / 31556926;
if ($time_difference < 60) {
// Seconds Ago
return round ( $time_difference ) . ' Seconds Ago';
} else if ( ($time_difference >= 60) && ($time_difference < 3600) ) {
// Minutes Ago
if (round ( $time_difference / 60 ) == 1) {
return round ( $time_difference / 60 ) . " Minute Ago";
} else {
return round ( $time_difference / 60 ) . " Minutes Ago";
}
} else if ($time_difference >= 3600 && $time_difference < 86400) {
// Hours Ago
if (round ( $time_difference / 3600 ) == 1) {
return round ( $time_difference / 3600 ) . " Hour Ago";
} else {
return round ( $time_difference / 3600 ) . " Hours Ago";
}
} else if ($time_difference >= 86400 && $time_difference < 2629743) {
// Days Ago
if (round ( $time_difference / 86400 ) == 1) {
return round ( $time_difference / 86400 ) . " Day Ago";
} else {
return round ( $time_difference / 86400 ) . " Days Ago";
}
} else if ($time_difference >= 2629743 && $time_difference < 31556926) {
// Months Ago
if (round ( $time_difference / 2629743 ) == 1) {
return round ( $time_difference / 2629743 ) . " Month Ago";
} else {
return round ( $time_difference / 2629743 ) . " Months Ago";
}
} else if ($time_difference >= 31556926) {
// Years Ago
if (round ( $time_difference / 31556926 ) == 1) {
return round ( $time_difference / 31556926 ) . " Year Ago";
} else {
return round ( $time_difference / 31556926 ) . " Years Ago";
}
}
}
This error is coming up, even though I haven't called the function at all in my code.
Can anyone see any errors in the code, cause I can't :(

This would be a lot simpler using a switch/case logic scheme. I have re-coded what you had up there using switch/case and this might be a good intro for you to learn switch/case. You had some extra ( ) in one of the if statements above. I hope this helps, friend:
<?
$unix_time = 6734;
echo howLongAgo($unix_time);
function howLongAgo($time_difference){
// Swtich logic based on the time difference passed to this function, sets the english string and what number the difference needs to be divided by
switch($time_difference){
case ($time_difference < 60):
$string = " second";
break;
case ($time_difference >= 60 && $time_difference < 3600):
$string = " minute";
$divider = 60;
break;
case ($time_difference >= 3600 && $time_difference < 86400):
$string = " hour";
$divider = 3600;
break;
case ($time_difference >= 86400 && $time_difference < 2629743):
$string = " day";
$divider = 86400;
break;
case ($time_difference >= 2629743 && $time_difference < 31556926):
$string = " month";
$divider = 2629743;
break;
case ($time_difference >= 31556926):
$string = " year";
$divider = 31556926;
break;
}
// If a divider value is set during the switch, use it to get the actual difference
if($divider){$diff = round($time_difference / $divider);}else{$diff = round($time_difference);}
// If the difference does not equal 1, pluralize the final result EG: hours, minutes, seconds
if($diff != 1){$pluralize="s";}
// Concatenate all variables together and return them
$final = $diff . $string . $pluralize . " ago";
return $final;
}
?>

I think your problem may come from the difference between elseif and else if (note the space).
From the PHP website:
Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

You have a syntax error in your code at line 47 (I am going to bet you are missing a semi-color or bracket at line 46.
It does not matter if you are calling the function or not, as the php parser will analyze the entire file upfront.

Couple of things..
did you change the file that it's included in when you loaded to your server?
try using include instead of require?

Related

Comparing MYSQL timestamps to retrieve time passed in specific units

Here is a PHP function I have designed, which is supposed to determine the amount of time passed in secs,mins,hours,days,weeks,months, and years - depending upon which bracket it is beneath. However Ive noticed that the values being returned seem to increase faster than actual time (within 30 mins, it outputs "1 weeks ago"). Im wondering if $time is actually in millis? That said, for the first 2 mins it outputs relatively accurate results.
Note: Running on 1and1 host.
Here's the function:
function get_relative_date($conn,$date,$post_id){
#get current timestamp
$q = "SELECT NOW() - INTERVAL 1 HOUR - `timestamp` FROM `posts` WHERE id=".$post_id.";";
# - INTERVAL 1 HOUR added due to server running 1 hour ahead.
$result = mysqli_query($conn,$q);
if ($result != null && $result != false){
$row = mysqli_fetch_array($result,MYSQLI_BOTH);
$time = $row[0]; #time passed since post
$min = 60;
$hour = $min*60;
$day = $hour*24;
$week = $day*7;
$month = $week*4;
$year = $month*12;
if ($time < $min){
return $time." secs ago";
}
if ($time < $hour){
return round(($time / $min))." mins ago";
}
if ($time < $day){
return round(($time / $hour))." hours ago";
}
if ($time < $week){
return round(($time / $day))." days ago";
}
if ($time < $month){
return round(($time / $week))." weeks ago";
}
if ($time < $year){
return round(($time / $month))." months ago";
}
if ($time >= $year){
return round(($time / $year))." years ago.";
}
return false;
}
}
Cheers.
I tried your query out and instead of 2 minutes and 40 seconds (in seconds) I was receiving 240 and instead of 1 hour 3 minutes and 40 seconds (in seconds) I got 10340.
You need this:
SELECT TIME_TO_SEC(TIMEDIFF(NOW(),`timestamp`)) FROM `posts` ...
This will select the time difference in seconds and hopefully give you the desired result.

PHP Last log in script [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I wanted to know a good and efficient way to be able to tell how long ago my users last logged in.
On the users profile I want it for say how long ago their last log in was.
Eg:
User 1
Last login: 2 hours ago
User 2
Last login: 3 minutes ago
User 3
Last login: 2 months ago
I will keep their last login information in a MySQL database but want to know how to do the script.
I just realized that Stackoverflow uses this feature, so that can help you understand what I want.
mysql_query("UPDATE users SET lastactivity = ".time()." WHERE id = ".$userID);
This is how I will update the DB.
Each page request just update their last activity.
<?php
mysql_query("UPDATE users SET lastactivity = ".time()." WHERE id = ".$userID);
to show when they were last online, just select their lastactivity field from database and show it
<?php
$activity = mysql_result(mysql_query("SELECT lastactivity FROM users WHERE id = ".$userID), 0);
echo "Last activity: ".relativeTime($active);
where relativeTime() is function I've been using:
function relativeTime($time, $short = false){
$SECOND = 1;
$MINUTE = 60 * $SECOND;
$HOUR = 60 * $MINUTE;
$DAY = 24 * $HOUR;
$MONTH = 30 * $DAY;
$before = time() - $time;
if ($before < 0)
{
return "not yet";
}
if ($short){
if ($before < 1 * $MINUTE)
{
return ($before <5) ? "just now" : $before . " ago";
}
if ($before < 2 * $MINUTE)
{
return "1m ago";
}
if ($before < 45 * $MINUTE)
{
return floor($before / 60) . "m ago";
}
if ($before < 90 * $MINUTE)
{
return "1h ago";
}
if ($before < 24 * $HOUR)
{
return floor($before / 60 / 60). "h ago";
}
if ($before < 48 * $HOUR)
{
return "1d ago";
}
if ($before < 30 * $DAY)
{
return floor($before / 60 / 60 / 24) . "d ago";
}
if ($before < 12 * $MONTH)
{
$months = floor($before / 60 / 60 / 24 / 30);
return $months <= 1 ? "1mo ago" : $months . "mo ago";
}
else
{
$years = floor ($before / 60 / 60 / 24 / 30 / 12);
return $years <= 1 ? "1y ago" : $years."y ago";
}
}
if ($before < 1 * $MINUTE)
{
return ($before <= 1) ? "just now" : $before . " seconds ago";
}
if ($before < 2 * $MINUTE)
{
return "a minute ago";
}
if ($before < 45 * $MINUTE)
{
return floor($before / 60) . " minutes ago";
}
if ($before < 90 * $MINUTE)
{
return "an hour ago";
}
if ($before < 24 * $HOUR)
{
return (floor($before / 60 / 60) == 1 ? 'about an hour' : floor($before / 60 / 60).' hours'). " ago";
}
if ($before < 48 * $HOUR)
{
return "yesterday";
}
if ($before < 30 * $DAY)
{
return floor($before / 60 / 60 / 24) . " days ago";
}
if ($before < 12 * $MONTH)
{
$months = floor($before / 60 / 60 / 24 / 30);
return $months <= 1 ? "one month ago" : $months . " months ago";
}
else
{
$years = floor ($before / 60 / 60 / 24 / 30 / 12);
return $years <= 1 ? "one year ago" : $years." years ago";
}
return "$time";
}
In addition to what #Martin. said, you can get the current timestamp using time(), and then retrieve the last login timestamp from the database, and subtract it from the current timestamp.
<?php
$date = strtotime("2012-03-08 16:02:35");
$now = time();
$diff = $now - $date;
?>
...then $diff is the time difference in seconds. Then you can calculate whatever you want.

"About a hour ago" logic in PHP / SQL and how it affects performance?

Lately I have been facing websites with "X hours ago", "X days ago" features. (including stackoverflow)
Like,
Anil played a game around a hour ago.
Anil leveled up 2 days ago.
Anil posted this comment just now.
I know it can easily be done with a little function which calculates the old time to the current time, get difference in seconds (or miliseconds) and return a string value accordingly.
What I am trying to ask is;
How can it be done at most professional way? Calculating time difference with PHP or get it calculated on our SQL while querying?
Wouldn't it lower the performance? Imagine a page with 100 comments, the function will work 100 times, hence, the page will load slower.
Ps. I'm not looking for scripts.
The usual approach is to use a normal SQL Query to gather the difference in time as an integer, and then convert it with PHP/Javascript. In other words, nothing fancy. Here is a PHP script used in most Twitter wrappers:
/**
* Formats a timestamp nicely with an adaptive "x units of time ago" message.
* Based on the original Twitter JavaScript badge. Only handles past dates.
* #return string Nicely-formatted message for the timestamp.
* #param $time Output of strtotime() on your choice of timestamp.
*/
function niceTime($time) {
$delta = time() - $time;
if ($delta < 60) {
return 'less than a minute ago.';
} else if ($delta < 120) {
return 'about a minute ago.';
} else if ($delta < (45 * 60)) {
return floor($delta / 60) . ' minutes ago.';
} else if ($delta < (90 * 60)) {
return 'about an hour ago.';
} else if ($delta < (24 * 60 * 60)) {
return 'about ' . floor($delta / 3600) . ' hours ago.';
} else if ($delta < (48 * 60 * 60)) {
return '1 day ago.';
} else {
return floor($delta / 86400) . ' days ago.';
}
}
?>
This is generally so fast that it should take little time more than usual. If you have less than 300 or so calculations from this on a page you shouldn't see a performance drop.
I think the performance implication is ignorable. Also you could do this on the client side, by sending normal timestamps to the client, e.g. for the web there is a jquery plugin that does this: jquery-timeago.
I would recommend to do this on the client side, because here the client can refresh it as wished (e.g. when the page stays open longer). Also the absolute data is available to the user, if needed.
It would almost certainly be best to do as a standalone function after the data have been fetched from the database.
It will, of course, incur a small overhead… But when that overhead is compared to the overhead of everything else you're doing to render the page, I expect it won't even be possible to measure (unless your algorithm is incredibly inefficient).
Additionally, since the database is often the bottleneck, not the app server's CPU, it's generally a good idea to do this kind of work on the app server instead of the database.
100 times almost nothing is still almost nothing. Don't worry about it. One simple check as in:
if time > day
write time.in_days + " days"
if time > hour
write time.in_hours + " hours"
if time > minute
write time.in_minutes + " minute"
if time > second
write time.in_seconds + " seconds"
if time > millisecond
write time.in_seconds + " milliseconds"
will only take you a few clock cycles. You will have 3 billion clock cycles at your disposal a second so a 100 calls to such a function would reach a millisecond of computational effort.
In sql the calculation will cost you time to build because of the language.
the choice for me would be php or javascript.
I've also heard of jquery solutions for this problem.
Javascript would press the calculation cost entirely to the client.
My suggestion goes to calculating differences with PHP.
What you could do is having a timestamp (consider a neutral timezone) in your db, and then make the query so that you dispay whatever fits your interval (IE timestamp - now() < N), where N is your time interval.
At that point, you use PHP to translate the event date to a difference from now (which could also be made dynamic client side - IE Javascript - for most recent entries, so to encompass seconds/minutes elapsed as ebay does with expiring actions).
The reason why I wouldn't put logic in the database is because I think that such data is application dependant, rather than db dependant - IE one day you might want to show time differences in another way, and db could not be the most versatile tool you have at hand - not necessarily because of performance (I think the impact can be neglegible anyways).
get the timestamps from SQL,
use simple subtraction to get the difference in seconds
you can implement a simple Ordo log(n) function, rather than an Ordo n, to get the textual timelapse, like the following:
function niceTime($difference) {
if ($difference > 86400)
if ($difference > 2592000)
if ($difference > 30758400) {
$time = round($difference / 30758400);
$unit = 'year';
} else {
$time = round($difference / 2592000);
$unit = 'month';
}
else
if ($difference > 604800) {
$time = round($difference / 604800);
$unit = 'week';
} else {
$time = round($difference / 86400);
$unit = 'day';
}
else
if ($difference > 900)
if ($difference > 3600) {
$time = round($difference / 3600);
$unit = 'hour';
} else {
$time = round($difference / 900);
$unit = 'quarter';
}
else
if ($difference > 60) {
$time = round($difference / 60);
$unit = 'minute';
} else {
$time = round($difference);
$unit = 'second';
}
return $time . ' ' . $unit . ($time != 1 ? 's' : '') . ' ago';
}
The idea here is that you shouldn't iterate through eight steps to find out that a given difference indeed was the worst case scenario (over a year). Rather you split your options in half every time, and you will allways arive at the "correct" time in three comparisons.
In the worst case scenario where you have a page with 100.000 comments that are all two years old, this will reduce the number of comparisons from 800.000 to 300.000, which will be noticable. ;-)
I have altered the code provided by sickle to add allowance for number of months, number of weeks, and years.
function agoTime($time) {
$delta = time() - $time;
if ($delta < 60) {
return 'less than a minute ago.';
} else if ($delta < 120) {
return 'about a minute ago.';
} else if ($delta < (45 * 60)) {
return floor($delta / 60) . ' minutes ago.';
} else if ($delta < (90 * 60)) {
return 'about an hour ago.';
} else if ($delta < (24 * 60 * 60)) {
return 'about ' . floor($delta / 3600) . ' hours ago.';
} else if ($delta < (48 * 60 * 60)) {
return '1 day ago.';
} else if ($delta < (11 * 24 * 60 * 60)) {
return 'about a week ago.';
} else if ($delta < (30 * 24 * 60 * 60)) {
return 'about ' .floor($delta / 604800) . ' weeks ago.';
} else if ($delta < (45 * 24 * 60 * 60)) {
return 'more than a month ago.';
} else if ($delta < (365 * 24 * 60 * 60)) {
return 'about ' .floor($delta / 2592000) . ' months ago.';
} else if ($delta < (550 * 24 * 60 * 60)) {
return 'more than a year ago.';
} else {
return 'about ' .floor($delta / 31536000) . ' years ago.';
}

Convert x hours x minutes ago back into unix timestamp

I'm looking for a function to convert dates presented in "X Hours ago" and "X minutes ago" back into a timestamp in php, anyone have a soulution to this?
strtotime already does this:
$timestamp = strtotime("8 hours ago");
See relative time format specifications for more info.
I helped someone on stackoverflow to write a function that does the reverse of this, here is the code, i'm sure if you deconstruct and reverse it, you will have your answer:
<?
$unix_time = 6734;
echo howLongAgo($unix_time);
function howLongAgo($time_difference){
// Swtich logic based on the time difference passed to this function, sets the english string and what number the difference needs to be divided by
switch($time_difference){
case ($time_difference < 60):
$string = " second";
break;
case ($time_difference >= 60 && $time_difference < 3600):
$string = " minute";
$divider = 60;
break;
case ($time_difference >= 3600 && $time_difference < 86400):
$string = " hour";
$divider = 3600;
break;
case ($time_difference >= 86400 && $time_difference < 2629743):
$string = " day";
$divider = 86400;
break;
case ($time_difference >= 2629743 && $time_difference < 31556926):
$string = " month";
$divider = 2629743;
break;
case ($time_difference >= 31556926):
$string = " year";
$divider = 31556926;
break;
}
// If a divider value is set during the switch, use it to get the actual difference
if($divider){$diff = round($time_difference / $divider);}else{$diff = round($time_difference);}
// If the difference does not equal 1, pluralize the final result EG: hours, minutes, seconds
if($diff != 1){$pluralize="s";}
// Concatenate all variables together and return them
$final = $diff . $string . $pluralize . " ago";
return $final;
}
?>
$hourago= "-1 hour";
$minago = "-2 minute";
$timestamp = strtotime($hourago.' '.$minago);
echo $timestamp;
or
$hourago= "-1";
$minago = "-2";
$timestamp = strtotime($hourago.' hour '.$minago.' minute');
echo $timestamp;

Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon"

Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon" or convert another date to "this afternoon", "next year", "next week wednesday". You get the picture.
Anyone know of a PHP or Javascript library that can do this?
I think you can come a long way with what is said here: Calculate relative time in C#
The logic is there, and it's not too hard to do the javascript equivalent if a solution in a different language suits you.
There might be more elegant solutions out there (look for Natural language formatting), but personally I couldn't find any.
I would suggest calculating the distance from now to the date you're formatting, and using thresholds.
Pseudo solution:
diff = now - date
if (diff < one_day)
format for today
if (diff < two_days)
format for tomorrow
if (diff < one_week)
format using days from now
.
.
.
The comparison will work for both past and future dates, as long as you use compare with the abs value of diff. Display timeunit ago or timeunit from now by checking if diff is positive or negative.
For the morning, afternoon, evening etc. you only need to check for the time of day in the date, and regarding the formatting type you hit, either display the time as numbers (far away), or natural language (recent or near date).
function gett($sam){
$times = time() - $sam;
if ($times == 60){
$times = "a minute ago";
}
if (($times != 1) && ($times < 60) && ($times != 0)){
$times = "$times seconds ago";
}
if ($times == 0){
$times = "less than a second ago";
}
if ($times == 1){
$times = "a second ago";
}
if ($times > 60 && $times < 3600){
$times = ceil($times/60)." minutes ago";
}
if($times == 3600){
$times = "an hour ago";
}
if($times > 3600 && $times < 86400){
$times = ceil($times/3600)." hours ago";
}
if($times == 86400){
$times = "a day ago";
}
if($times > 86400){
$times = ceil($times/86400)." days ago";
}
return $times; }
Usage:
$updated = gett($timestamp);
where $timestamp is pretty self-explanatory..
From this link -> How do I calculate relative time in C#?
function posted(t) {
var now = new Date();
var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
if (diff < 60) { return 'less than a minute ago'; }
else if (diff < 120) { return 'about a minute ago'; }
else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
else if (diff < (5400)) { return 'about an hour ago'; }
else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
else if (diff < (172800)) { return '1 day ago'; }
else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
}

Categories