Pregunta

I created an E-mail class in PHP but it always returns success even when post data is empty. The exceptions clearly aren't working and I'm wondering why it's not sending any email as well. Here's the code:

<?php

class Contact
{
    private $toEmail = 'example@outlook.com', $subject = 'Personal Site - Contact';
    private $name, $email, $message;

public function __constructor(array $arr)
{
    if(!empty($arr['name']) && !empty($arr['email']) && !empty($arr['msg']))
    {
        $this->name = $this->ValidateName($arr['name']);
        $this->email = $this->ValidateEmail($arr['email']);
        $this->msg = $this->SanitizeMessage($arr['msg']);

        $this->SendMail($this->name, $this->email, $this->msg);
    }
    else
    {
        throw new Exception("Please fill all the required fields");
    }
}

private function ValidateName($name)
{
    if(ctype_alpha($name))
    {
        return $name;
    }
    else
    {
        return null;
    }
}

private function ValidateEmail($email)
{
    if(filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        return $email;
    }
    else
    {
        return null;
    }
}

private function SanitizeMessage($msg)
{
    return htmlentities($msg);
}

private function SendMail($name, $email, $msg)
{
    $mailHeader = "From: " . $email . "\r\n"; 
    $mailHeader .= "Reply-To: " . $email . "\r\n"; 
    $mailHeader .= "Content-type: text/html; charset=iso-8859-1\r\n";

    $messageBody = "Name: " . $name . "";
    $messageBody .= "Email: " . $email . "";
    $messageBody .= "Comment: " . nl2br($msg) . "";

    if(mail($this->toEmail, $this->subject, $messageBody, $mailHeader))
    {
        return true;
    }
    else
    {
        throw new Exception('Message couldn\'t be sent');
    }
}
}

try
{
    $obj = new Contact($_POST);
}
catch(Exception $ex)
{
    echo json_encode($ex);
}

echo json_encode('Message was sent succesfully');

?>
¿Fue útil?

Solución

The constructor is __construct(), not __constructor(). That function is never called.
Also, avoid doing actions in constructors, setting variables, that's OK, but actually sending mail on creating a new object is unexpected for most developers.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top