goshaua
Новичок
Класс отправки почты (покритиковать)
Здравствуйте! Написал свой первый удачный (на мой взгляд) класс отправки почты с сайта. Хотелось бы "услышать" критуку опытных PHPстов. Буду благодарен всем за критику и рекомендации! Спассибо!
Файл FeedBack.php
Файл sendmail.class.php
Здравствуйте! Написал свой первый удачный (на мой взгляд) класс отправки почты с сайта. Хотелось бы "услышать" критуку опытных PHPстов. Буду благодарен всем за критику и рекомендации! Спассибо!
Файл FeedBack.php
PHP:
<body>
<?php
$timer = array_sum(explode(' ', microtime()));
$user_name = $_POST['name'];
$user_email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
include 'sendmail.class.php';
$Send_Mail = new sendMail('[email protected],[email protected]');
$Send_Mail->arrInfo = array('msg_sent' => 'Спасибо! Ваше сообщение отправлено.',
'msg_not_sent' => 'Ошибка отправки сообщения!',
'name_not_exist' => 'Введите имя.',
'email_not_exist' => 'Введите емейл адресс.',
'email_not_valid' => 'Не корректний емейл.',
'subject_not_exist' => 'Введите тему письма.',
'msg_not_exist' => 'Введите текс письма.');
if($Send_Mail->Send($user_name, $user_email, $subject, $message))
$style ='color: green; font-weight:bold';
else
$style ='color: red; font-weight:bold';
echo "<div style='$style'>".implode('<br />', $Send_Mail->getInfoMsgsArr()).'</div>';
?>
<form action="<?php echo basename(__FILE__) ?>" method="post" id="contactform">
<ol>
<li>
<label for="name">First Name <span class="red">*</span></label>
<input id="name" name="name" class="text" value="<?php echo $Send_Mail->userName ?>" />
</li>
<li>
<label for="email">Your email <span class="red">*</span></label>
<input id="email" name="email" class="text" value="<?php echo $Send_Mail->userMail ?>" />
</li>
<li>
<label for="subject">Subject</label>
<input id="subject" name="subject" class="text" value="<?php echo $Send_Mail->subject ?>" />
</li>
<li>
<label for="message">Message <span class="red">*</span></label>
<textarea id="message" name="message" rows="6" cols="50"><?php echo $Send_Mail->message ?></textarea>
</li>
<li>
<input type="submit" name="f_submit" class="f_button" value="Send message"/>
</li>
</ol>
</form>
<?php echo '<br />'.round(array_sum(explode(' ', microtime())) - $timer, 4); ?>
</body>
</html>
PHP:
<?
/** отправка емейла с сайта */
class sendMail {
private $countErr = 0;
private $msgsArr = array();
/** Текст отформатирован для отправки */
private $letter = '';
public $userName = '';
public $userMail = '';
public $subject = '';
public $message = '';
/** массив сообщений */
public $arrInfo = array('msg_sent' => 'Message sent!',
'msg_not_sent' => 'Message NOT sent!',
'name_not_exist' => 'Enter name!',
'email_not_exist' => 'Enter email!',
'email_not_valid' => 'Email not valid!',
'subject_not_exist' => 'Enter subject!',
'msg_not_exist' => 'Enter Message!');
public function __construct($sendTo) {
$this->addresses = explode(',', $sendTo);
if(count($this->addresses) > 0) {
foreach($this->addresses as $email) {
echo $email;
if($this->checkMail($email) != 0) throw new Exception('>>> Class -> '.__CLASS__.': Not the correct admin email address <<<');
}
}
}
/** проверка входных данных */
private function Validate() {
if(get_magic_quotes_gpc() == 1) {
$this->userName = stripslashes($this->userName);
$this->subject = stripslashes($this->subject);
$this->message = stripslashes($this->message);
}
$this->userName = trim($this->userName);
$this->subject = trim($this->subject);
$this->message = trim($this->message);
$this->userMail = trim($this->userMail);
if($this->userName == '') { $this->countErr++; $this->msgsArr[] = $this->arrInfo['name_not_exist']; }
switch($this->checkMail($this->userMail)){
case 1: $this->countErr++; $this->msgsArr[] = $this->arrInfo['email_not_exist']; break;
case 2: $this->countErr++; $this->msgsArr[] = $this->arrInfo['email_not_valid']; break;
}
if($this->subject == '') { $this->countErr++; $this->msgsArr[] = $this->arrInfo['subject_not_exist']; }
if($this->message == '') { $this->countErr++; $this->msgsArr[] = $this->arrInfo['msg_not_exist']; }
if($this->countErr == 0) return true; else return false;
}
/** заменяет укр буки и на анг + convert_cyr_string() */
private function Convert() {
$is = array('І', 'і');//Укр. букви
$wellbe = array('I', 'i');//Англ. букви
$this->subject = str_replace($is, $wellbe, $this->subject);
$this->letter = str_replace($is, $wellbe, $this->letter);
$this->subject = convert_cyr_string($this->subject,w,k);
$this->letter = convert_cyr_string($this->letter,w,k);
}
/** проверка емейла. Возвращает: 1 - нет емейла; 2 - емейл не коректный; 0 - при успехе */
private function checkMail($mail) {
// режем левые символы и крайние пробелы
$mail = trim(preg_replace("/[^\x20-\xFF]/","",@strval($mail)));
// если пусто - выход
if (strlen($mail) == 0) return 1;
if (!preg_match("/^[a-z0-9\_\-\.]{1,20}@(([a-z0-9-]+\.)+(com|net|org|mil|".
"edu|gov|arpa|info|biz|inc|name|[a-z]{2})|[0-9]{1,3}\.[0-9]{1,3}\.[0-".
"9]{1,3}\.[0-9]{1,3})$/is",$mail)) return 2;
return 0;
}
/** отправка почты; true - при успехе; если введены не корректные данные функция вернёт false, как и при ошибке отправки */
public function Send($userName, $userMail, $subject, $message) {
$this->userName = $userName;
$this->userMail = $userMail;
$this->subject = $subject;
$this->message = $message;
if($this->Validate()){
$line = '--------------------------------------------';
$this->letter = $this->userName." пише: \r\n $line \r\n ".$this->message." \r\n $line \r\n [url]http://[/url]".$_SERVER['HTTP_HOST'];
$this->Convert();
foreach($this->addresses as $to)
if(!mail($to, "$this->subject", "$this->letter", "From: $this->userMail \r \n".
"Reply-to: $this->userMail \r \n"."X-Mailer: /PHP".phpversion())) {
$this->msgsArr[] = $this->arrInfo['msg_not_sent']; return false;
}
$this->msgsArr[] = $this->arrInfo['msg_sent'];
$this->userName = '';
$this->userMail = '';
$this->subject = '';
$this->message = '';
return true;
}
return false;
}
public function getInfoMsgsArr(){
return $this->msgsArr;
}
}
?>
Все "легко встраивается"
- он воняет. Почти всем, чем можно.