Fatal error cannot redeclare phpmailerautoload

I am using PHPMailer to send emails from my local host. I have written a function which is supposed to send emails to registered users who have chosen the option to receive them. (i.e. newsletter

I am using PHPMailer to send emails from my local host.

I have written a function which is supposed to send emails to registered users who have chosen the option to receive them. (i.e. newsletter subscription, etc)

function email_users($subject, $body) {
    include('core/db/db_connection.php');
    $sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1";
    $query = mysqli_query($dbCon, $sql);
    while (($row = mysqli_fetch_assoc($query)) !== false) {
        $body = "Hello ". $row['first_name'] . ", <br><br>" . $body;
        email($row['email'], $subject, $body);
    }
}

The code that is calling the function:

if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
        ?>
            <h3 class="email_success">Emails have been sent</h2>
            <a href="admin.php" class="email_success_a">Go back to the admin page</a>
        <?php 
        } else {
            if (empty($_POST) === false) {
                if (empty($_POST['subject']) === true) {
                    $errors[] = 'A message subject is required.';
                }
                if (empty($_POST['body']) === true) {
                    $errors[] = 'A body message is required.';
                }
                if (empty($errors) === false) {
                    echo output_errors($errors);
                } else {
                    email_users($_POST['subject'], $_POST['body']);
                    header('Location: email_users.php?success');
                    exit();
                }
            }
// generate email form otherwise

Any idea why I’m getting this error?

Fatal error: Cannot redeclare PHPMailerAutoload()

I would also like to point out that even with this error, the function still works and the emails are being sent…

EDIT: As requested, please see below the function using PHPMailer:

function email($user, $subject, $body) {
    require 'phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;

 /* $mail -> Host,username,password and other misc stuff
    $mail->Subject = $subject;
    $mail->Body    = $body;
    $mail->AltBody = $body; etc */
}

Содержание

  1. Fix PHP Fatal error: Cannot redeclare “function name”
  2. Where was the first function defined?
  3. OK, so how do I fix this error?
  4. Rename the other function to something else.
  5. Check if the function name has already been used.
  6. Fatal error: Cannot redeclare Classname::function.
  7. Opencart 2: ошибка Fatal error: Cannot redeclare
  8. Модуль Заказ в 1 клик Opencart 2
  9. php fatal error cannot redeclare class – How to fix?
  10. Why does PHP fatal error occur?
  11. 1. Error while coding
  12. 2. Cannot redeclare class error in WordPress
  13. Conclusion
  14. PREVENT YOUR SERVER FROM CRASHING!

Fix PHP Fatal error: Cannot redeclare “function name”

This is a short guide on how to deal with the following PHP error:

Fatal error: Cannot redeclare function name (previously declared in /path/to/file.php:3) in /path/to/other-file.php on line 9

The fatal error above will appear if your code contains two or more PHP functions that have the exact same name. Unlike other programming languages such as Java and C++, PHP does not support Method Overloading. Instead, you must use default / optional function parameters.

Where was the first function defined?

If you read the error carefully, you should be able to see what the issue is. In the example above, the function name in question was already previously declared on LINE 3 in file.php. This led to a fatal error when we attempted to create another function with the exact same name on LINE 9 in other-file.php

Take a look at the following example:

If you attempt to run the code snippet above, a fatal error will be thrown and the script will be killed. This is because I created two separate functions with the name test.

OK, so how do I fix this error?

The fix depends on your PHP application and what you are attempting to achieve.

Rename the other function to something else.

If you do not need a function called test, then you could rename the second function to something else.

In the case above, we could do the following:

As you can see, I simply renamed the second test function to myTest.

Check if the function name has already been used.

If you find yourself in a situation where the function name may or may not exist, then you can check to see if the name of the function has already been defined.

An example of this approach being assigned to the problem that we had above:

In the code snippet above, I used the function_exists function to check if test already exists as a function. Because it does exist in the example above, the second function is never created.

Fatal error: Cannot redeclare Classname::function.

Note that PHP class methods / functions must also abide by the same rule:

If you run the code above, it will result in the following error:

Fatal error: Cannot redeclare Test::test() in /path/to/file.php on line 14

This is because a PHP class cannot have two functions with the exact same name. Note that I used public on the first function and protected on the second function because I wanted to demonstrate how the visibility of the method does not matter in this case.

Hopefully, you found this guide to be informative!

Источник

Opencart 2: ошибка Fatal error: Cannot redeclare

Если после установки модуля или модификации на Opencart 2 вылазит ошибка Fatal error: Cannot redeclare . — это значит, что php-функция или php-класс, который указан в ошибке, дублируеться. Вам нужн оставить только одну функцию или класс с таким названием. Все очень просто, ищите проблемный файл (контроллер или модель, скорее всего модифицированный через vqmod или ocmod), который указан в функции, в этом файле ищите функции или класы с одинаковыми названиями и если они дублируються полностью — тогда один из них удаляете, если они разные — переименовывайте и исправляйте всю цепочку обращений к этой функции или классу.

Пример ошибки:
Fatal error: Cannot redeclare ModelCatalogProduct::editList() in /home/site/public_html/www.site.com/vqmod/vqcache/vq2-admin_model_catalog_product.php on line 164
Решение ошибки:
Нужно открыть файл vqmod/vqcache/vq2-admin_model_catalog_product.php и сделать поиск «public function editList», вы найдете две функции с таким названием. Далее нужно определить: эти функции одинаковые или разные? Затем вам нужно найти в каком модификаторе добавляеться дублирующая функция, для этого открываете папку vqmod/xml/ и ищите файл в котором добавляеться эта функция. Когда уже нашли: если функции были одинаковые — тогда удаляете эту операцию из модификатора, если разные — переименовывайте и исправляйте цепочку обращений к этой функции в модуле.

Если такая ошибка возникает в папке system/modification/ или в system/storage/modification/ — процедура та же самая, только добавление дублирующейся функции нужно искать в модификаторе модуля ( файл с расширением *.ocmod.xml или файл install.xml ), затем удалить старый модификатор в админке и установить новый отредактированный.

Модуль Заказ в 1 клик Opencart 2

Модуль Быстрый заказ в 1 клик Opencart2 — очень удобное дополнение для вашего магазина.Позволяет упр..

Источник

php fatal error cannot redeclare class – How to fix?

by Keerthi PS | Dec 7, 2019

Receiving an error ‘PHP fatal error cannot redeclare class’? Here’s how we fix it.

A few days ago, we came across this error message due to which our customer was not able to continue with coding for a long time.

At Bobcares, we often get requests to fix PHP fatal errors, as a part of our Server Management Services.

Today, we’ll have a deep look into PHP fatal errors and see how our Support Engineers fix them.

Why does PHP fatal error occur?

We’ve seen many of our customers experiencing this error. Usually, this error causes an immediate termination of the script.

Basically, ‘PHP fatal error cannot redeclare class’ indicates that the class name already exists.

Mostly, this error shows up while the user is adding some new PHP codes. But WordPress sites also show the same error due to plugin or theme conflicts.

Let’s see both these instances in detail.

1. Error while coding

PHP fatal error is quite common while coding. Developers often get the error message when trying to declare an already existing class. The error message appears as:

At this point of error, the script terminates.

Recently, one of our customers approached us with this error. So we suggested him to avoid using already existing class in further coding.

But the new class created by our customer was also giving the same error. So, we provided him the below command to fix the problem.

Here XXXX is the new class name.

2. Cannot redeclare class error in WordPress

Sometimes, WordPress sites show fatal error cannot redeclare class.

Usually, PHP based WordPress site shows this error after installation of new plugins or themes. A typical error message in WordPress looks like:

When our customers approach us with this error message, our Support Team checks for the reason for the error.

In most cases, the error will be with the usage of the same class in function.php and plugin files. So, to fix this error we disable the plugin and install the latest version.

[Need help in fixing PHP fatal errors? – We’ll help you.]

Conclusion

In short, PHP fatal error cannot redeclare class occurs due to reuse of an already existing class name, or plugins in WordPress sites. Today, we saw how our Support Engineers fix this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Источник

470 votes

2 answers

Get the solution ↓↓↓

PHP Fatal error:  Cannot redeclare PHPMailerAutoload() (previously declared in /home2/epsilonbr/ticket/PHPMailer/PHPMailerAutoload.php:24) in /home2/epsilonbr/ticket/PHPMailer/PHPMailerAutoload.php on line 24

Hello guys this was working till yesterday, suddenly today someone tried to send me a ticket and I received this error.
I am using the default mailer autoload I haven’t changed anything

function PHPMailerAutoload($classname)
{
    //Can't use __DIR__ as it's only in PHP 5.3+
    $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
    if (is_readable($filename)) {
        require $filename;
    }
}

if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
    //SPL autoloading was introduced in PHP 5.1.2
    if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
        spl_autoload_register('PHPMailerAutoload', true, true);
    } else {
        spl_autoload_register('PHPMailerAutoload');
    }
} else {
    /**
     * Fall back to traditional autoload for old PHP versions
     * @param string $classname The name of the class to load
     */
    function __autoload($classname)
    {
        PHPMailerAutoload($classname);
    }
}

Any ideas on why this is happening? Line 24 is thefunction PHPMailerAutoload($classname)

2021-12-16

Write your answer


255

votes

Answer

Solution:

The solution was really easy and as @CBroe said.

I had added therequire 'PHPMailer/PHPMailerAutoload.php'; twice in the code, once inside the header.php and the second time was inside the something_in_the_body.php file because I forgot that I had added that inside the header.


360

votes

Answer

Solution:

public function E_mail($name,$from,$to,$title,$message)
{
 $this->email->from($from,$name);
 $this->email->to($to);
 $this->email->subject($title);
 $this->email->message($message);
 if($this->email->send()) 
  echo "Success";
     else 
        echo "Fail";
}


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-12-16

Link To Source

Link To Answer
People are also looking for solutions of the problem: sqlstate[23000]: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

I am using PHPMailer to send emails from my local host.

I have written a function which is supposed to send emails to registered users who have chosen the option to receive them. (i.e. newsletter subscription, etc)

function email_users($subject, $body) {
    include('core/db/db_connection.php');
    $sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1";
    $query = mysqli_query($dbCon, $sql);
    while (($row = mysqli_fetch_assoc($query)) !== false) {
        $body = "Hello ". $row['first_name'] . ", <br><br>" . $body;
        email($row['email'], $subject, $body);
    }
}

The code that is calling the function:

if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
        ?>
            <h3 class="email_success">Emails have been sent</h2>
            <a href="admin.php" class="email_success_a">Go back to the admin page</a>
        <?php 
        } else {
            if (empty($_POST) === false) {
                if (empty($_POST['subject']) === true) {
                    $errors[] = 'A message subject is required.';
                }
                if (empty($_POST['body']) === true) {
                    $errors[] = 'A body message is required.';
                }
                if (empty($errors) === false) {
                    echo output_errors($errors);
                } else {
                    email_users($_POST['subject'], $_POST['body']);
                    header('Location: email_users.php?success');
                    exit();
                }
            }
// generate email form otherwise

Any idea why I’m getting this error?

Fatal error: Cannot redeclare PHPMailerAutoload()

I would also like to point out that even with this error, the function still works and the emails are being sent…

EDIT: As requested, please see below the function using PHPMailer:

function email($user, $subject, $body) {
    require 'phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;

 /* $mail -> Host,username,password and other misc stuff
    $mail->Subject = $subject;
    $mail->Body    = $body;
    $mail->AltBody = $body; etc */
}

Download

Today i will explain how to reset your account password using PHPMailer, PHP and MySQL, in this tutorial i will implement Forgot Password Recovery (Reset) using PHP and MySQL. Before moving towards the reset your password first we need a user registration and login script in php, so if you do not know how to register user and login, you can check out my tutorial about Simple User Registration & Login Script in PHP and MySQL.

To implement forgot password recovery, i will suggest you all to download and set up user registration script so that you can add forgot password functionality in it. However, it is not mandatory if you are an advance user and you can integrate it in your project then you do not need to set it up.

In my user registration tutorial there is a table name users, we will use the same table to check is user exist or not. You will add files of this tutorial in user registration and login script folder.

We will send an email using PHPMailer, if you do not know how to user PHPMailer so you can check my PHPMailer tutorial, i have wrote a detailed tutorial about how to send email in PHP using PHPMailer.

We have to follow these steps to implement forgot password functionality.

  1. Create a Temporary Token Table
  2. Create a Database Connection
  3. Create an Index File (Send Email)
  4. Create a Reset Password File
  5. Create a CSS File

Let me give you a quick review of it, first we will create a table to store a token valid for one day for any user. We will also create a form that will take input of email, then we will check either email exist or not, if email is found a temporary token will be generated and email will be sent to the user with the generated token.

Once user clicked on the email token link within one day, user can reset new password. For that purpose we will also create another form that will take input of new password and update it in user table and we will also remove the temporary token from temporary token table once user successfully updated password.

1. Create a Temporary Token Table

We need to create temporary token table, run the following query.

CREATE TABLE `password_reset_temp` (
  `email` varchar(250) NOT NULL,
  `key` varchar(250) NOT NULL,
  `expDate` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I have also attached sql file of this table in the download file of this tutorial.

2. Create a Database Connection

Create a database connection file with name db.php and add the following script in it, don’t forget to change your database credentials in this file.

$con = mysqli_connect("localhost","root","","register");
    if (mysqli_connect_errno()){
	echo "Failed to connect to MySQL: " . mysqli_connect_error();
	die();
	}

date_default_timezone_set('Asia/Karachi');
$error="";

We have also define the date timezone, you can set it as per your location. This helps to store data in the timezone of your location.

3. Create an Index File (Send Email)

Now create an index.php file that will take email input and send an email to the user if user is found in the users table. users table is available in the login and registration script, we are using the same table.

Add the following script in index.php file.

<?php
include('db.php');
if(isset($_POST["email"]) && (!empty($_POST["email"]))){
$email = $_POST["email"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) {
   $error .="<p>Invalid email address please type a valid email address!</p>";
   }else{
   $sel_query = "SELECT * FROM `users` WHERE email='".$email."'";
   $results = mysqli_query($con,$sel_query);
   $row = mysqli_num_rows($results);
   if ($row==""){
   $error .= "<p>No user is registered with this email address!</p>";
   }
  }
   if($error!=""){
   echo "<div class='error'>".$error."</div>
   <br /><a href='javascript:history.go(-1)'>Go Back</a>";
   }else{
   $expFormat = mktime(
   date("H"), date("i"), date("s"), date("m") ,date("d")+1, date("Y")
   );
   $expDate = date("Y-m-d H:i:s",$expFormat);
   $key = md5(2418*2+$email);
   $addKey = substr(md5(uniqid(rand(),1)),3,10);
   $key = $key . $addKey;
// Insert Temp Table
mysqli_query($con,
"INSERT INTO `password_reset_temp` (`email`, `key`, `expDate`)
VALUES ('".$email."', '".$key."', '".$expDate."');");

$output='<p>Dear user,</p>';
$output.='<p>Please click on the following link to reset your password.</p>';
$output.='<p>-------------------------------------------------------------</p>';
$output.='<p><a href="https://www.allphptricks.com/forgot-password/reset-password.php?
key='.$key.'&email='.$email.'&action=reset" target="_blank">
https://www.allphptricks.com/forgot-password/reset-password.php
?key='.$key.'&email='.$email.'&action=reset</a></p>';		
$output.='<p>-------------------------------------------------------------</p>';
$output.='<p>Please be sure to copy the entire link into your browser.
The link will expire after 1 day for security reason.</p>';
$output.='<p>If you did not request this forgotten password email, no action 
is needed, your password will not be reset. However, you may want to log into 
your account and change your security password as someone may have guessed it.</p>';   	
$output.='<p>Thanks,</p>';
$output.='<p>AllPHPTricks Team</p>';
$body = $output; 
$subject = "Password Recovery - AllPHPTricks.com";

$email_to = $email;
$fromserver = "[email protected]"; 
require("PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "mail.yourwebsite.com"; // Enter your host here
$mail->SMTPAuth = true;
$mail->Username = "[email protected]"; // Enter your email here
$mail->Password = "password"; //Enter your password here
$mail->Port = 25;
$mail->IsHTML(true);
$mail->From = "[email protected]";
$mail->FromName = "AllPHPTricks";
$mail->Sender = $fromserver; // indicates ReturnPath header
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($email_to);
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "<div class='error'>
<p>An email has been sent to you with instructions on how to reset your password.</p>
</div><br /><br /><br />";
	}
   }
}else{
?>
<form method="post" action="" name="reset"><br /><br />
<label><strong>Enter Your Email Address:</strong></label><br /><br />
<input type="email" name="email" placeholder="[email protected]" />
<br /><br />
<input type="submit" value="Reset Password"/>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<?php } ?>

This file is simply checking if email is available in database then generate a random token, save that token in temporary table and send an email to the user with link. Once user click on the link user will be able to set new password.

Please note that i have been using https://www.allphptricks.com/forgot-password/ directory URL in the above script, it should be replace with your project URL where you will upload files of this tutorial.

4. Create a Reset Password File

Now create a rest password file, this will check that is token available in database against the user email and it should be less then one day old, once token expired user will need to regenerate token.

So if token is found user can simply set new password, we will update user password and also delete the token from temporary token table.

Insert the following script in reset-password.php file.

<?php
include('db.php');
if (isset($_GET["key"]) && isset($_GET["email"]) && isset($_GET["action"]) 
&& ($_GET["action"]=="reset") && !isset($_POST["action"])){
  $key = $_GET["key"];
  $email = $_GET["email"];
  $curDate = date("Y-m-d H:i:s");
  $query = mysqli_query($con,
  "SELECT * FROM `password_reset_temp` WHERE `key`='".$key."' and `email`='".$email."';"
  );
  $row = mysqli_num_rows($query);
  if ($row==""){
  $error .= '<h2>Invalid Link</h2>
<p>The link is invalid/expired. Either you did not copy the correct link
from the email, or you have already used the key in which case it is 
deactivated.</p>
<p><a href="https://www.allphptricks.com/forgot-password/index.php">
Click here</a> to reset password.</p>';
	}else{
  $row = mysqli_fetch_assoc($query);
  $expDate = $row['expDate'];
  if ($expDate >= $curDate){
  ?>
  <br />
  <form method="post" action="" name="update">
  <input type="hidden" name="action" value="update" />
  <br /><br />
  <label><strong>Enter New Password:</strong></label><br />
  <input type="password" name="pass1" maxlength="15" required />
  <br /><br />
  <label><strong>Re-Enter New Password:</strong></label><br />
  <input type="password" name="pass2" maxlength="15" required/>
  <br /><br />
  <input type="hidden" name="email" value="<?php echo $email;?>"/>
  <input type="submit" value="Reset Password" />
  </form>
<?php
}else{
$error .= "<h2>Link Expired</h2>
<p>The link is expired. You are trying to use the expired link which 
as valid only 24 hours (1 days after request).<br /><br /></p>";
            }
      }
if($error!=""){
  echo "<div class='error'>".$error."</div><br />";
  }			
} // isset email key validate end


if(isset($_POST["email"]) && isset($_POST["action"]) &&
 ($_POST["action"]=="update")){
$error="";
$pass1 = mysqli_real_escape_string($con,$_POST["pass1"]);
$pass2 = mysqli_real_escape_string($con,$_POST["pass2"]);
$email = $_POST["email"];
$curDate = date("Y-m-d H:i:s");
if ($pass1!=$pass2){
$error.= "<p>Password do not match, both password should be same.<br /><br /></p>";
  }
  if($error!=""){
echo "<div class='error'>".$error."</div><br />";
}else{
$pass1 = md5($pass1);
mysqli_query($con,
"UPDATE `users` SET `password`='".$pass1."', `trn_date`='".$curDate."' 
WHERE `email`='".$email."';"
);

mysqli_query($con,"DELETE FROM `password_reset_temp` WHERE `email`='".$email."';");
	
echo '<div class="error"><p>Congratulations! Your password has been updated successfully.</p>
<p><a href="https://www.allphptricks.com/forgot-password/login.php">
Click here</a> to Login.</p></div><br />';
	  }		
}
?>

Please note that i have wrote https://www.allphptricks.com/forgot-password/ in these both files, make sure that you also update it as per your web directory URL. You will write your directory where you will set up user registration and login script.

5. Create a CSS File

Create a file with name style.css and keep it in folder css. Paste the following code in it.

.error p {
	color:#FF0000;
	font-size:20px;
	font-weight:bold;
	margin:50px;
	}

Download

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.

Facebook Official Page: All PHP Tricks

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error cannot recover after last error any further errors will be ignored
  • Fatal error cannot open war3map w3i
  • Fatal error cannot make non static method
  • Fatal error cannot initialize renderer как исправить виндовс 7
  • Fatal error cannot initialize renderer sniper ghost warrior

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии