Mail()在函数内部不起作用

时间:2017-02-18 08:36:06

标签: php

以下功能未执行:

function sendCode(){
    $our_mail = 'username@gmail.com'
    $to = $email;
    $msg = "Hi $first_name, \n\nYour email has been used to sign up with us. To activate your account \nuse activation code:\n$unique_id\n\nThis message was sent to $email at your request."; 
    $subject = "$unique_id is your account activation code.";
    mail($to,$subject,$msg,'$from:'.$our_mail);
}

if($result){
    header('Location:activate.php'); //redirect
    sendCode();
}

虽然,这很好用:

if($result){
    header('Location:activate.php'); //redirect
    $our_mail = 'username@gmail.com'
    $to = $email;
    $msg = "Hi $first_name, \n\nYour email has been used to sign up with us. To activate your account \nuse activation code:\n$unique_id\n\nThis message was sent to $email at your request."; 
    $subject = "$unique_id is your account activation code.";
    mail($to,$subject,$msg,'$from:'.$our_mail); 
}

任何人都可以解释原因吗?

1 个答案:

答案 0 :(得分:1)

在函数变量中,scope将是local,因此您需要将变量声明为global或pass using参数。发送邮件后也要进行重定向

试试这个:

function sendCode($email){
 $our_mail='username@gmail.com'
 $to=$email;
 $msg= "Hi $first_name, \n\nYour email has been used to sign up with us. To activate your account \nuse activation code:\n$unique_id\n\nThis message was sent to $email at your request."; 
 $subject="$unique_id is your account activation code.";
 mail($to,$subject,$msg,'$from:'.$our_mail);
}

if($result){

 sendCode($email);
 header('Location:activate.php'); //redirect
}

OR

function sendCode(){
    global $email,$unique_id,$first_name; //<----- make variables global
     $our_mail='username@gmail.com'
     $to=$email;
     $msg= "Hi $first_name, \n\nYour email has been used to sign up with us. To activate your account \nuse activation code:\n$unique_id\n\nThis message was sent to $email at your request."; 
     $subject="$unique_id is your account activation code.";
     mail($to,$subject,$msg,'$from:'.$our_mail);
    }

    if($result){

     sendCode();
    header('Location:activate.php'); //redirect

    }