Error showing past time of multiple PHP posts

Asked

Viewed 113 times

2

<?php
function timeAgo($time_ago){
$cur_time   = time();
$time_elapsed   = $cur_time - $time_ago;
$seconds    = $time_elapsed ;
$minutes    = round($time_elapsed / 60 );
$hours      = round($time_elapsed / 3600);
$days       = round($time_elapsed / 86400 );
$weeks      = round($time_elapsed / 604800);
$months     = round($time_elapsed / 2600640 );
$years      = round($time_elapsed / 31207680 );
// Seconds
if($seconds <= 60){
    echo "$seconds segundos atrás";
}
//Minutes
else if($minutes <=60){
    if($minutes==1){
        echo "um minuto atrás";
    }
    else{
        echo "$minutes minutos atrás";
    }
}
//Hours
else if($hours <=24){
    if($hours==1){
        echo "uma hora atrás";
    }else{
        echo "$hours horas atrás";
    }
}
//Days
else if($days <= 7){
    if($days==1){
        echo "ontem";
    }else{
        echo "$days dias atrás";
    }
}
//Weeks
else if($weeks <= 4.3){
    if($weeks==1){
        echo "à uma semana";
    }else{
        echo "$weeks semanas atrás";
    }
}
//Months
else if($months <=12){
    if($months==1){
        echo "um mês atrás";
    }else{
        echo "$months meses atrás";
    }
}
//Years
else{
    if($years==1){
        echo "um ano atrás";
    }else{
        echo "$years anos atrás";
    }
}
}

?>
<?php
  $curenttime=$date_uploaded;
  $time_ago =strtotime($curenttime);
  echo timeAgo($time_ago);
?>

Whereas $date_upload is equal to (dd-mm-yy hh:mm:ss) in the database.

This is the code, when I pull only one post it works, but when I pull several posts gives this error:

error: Cannot redeclare timeAgo() (Previously declared in C: xampp htdocs site poster.php:520) in)

  • 1

    It seems that in the file poster.php has a function with the same name as the one you posted (timeAgo), but can also be problem with adding files via include. Try to rename this function, and if you are using include, try to change to include_once.

1 answer

2


The error says that there is two or more times a function with the same name in your file or in the call of a include.

To solve the problem, I suggest you have at least two files, one with normal code processing and the other with only a small library functions, thus avoiding the collision of function names. Another alternative from php5.3 is to use name espaces.

There are some tools that identify code duplication and copy & Paste as the php mess dectector, also helps in identifying such collisions.

Example - simulated error.

Example - solution with namespaces.

  • 2

    manage rsolver thank you very much I created a function file called data.php and then I gave a include at the top of the include page ('data.php'); then I just did an echo on the <?php $curenttime=$date_uploaded; $time_ago =strtotime($curenttime); echo timeAgo($time_ago); ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.