PHP mail() works from command line but not apache

2019-01-12 04:48发布

I'm trying to figure out why the mail function in PHP fails when called via web browser (i.e. apache), but I can run the same script from the command line using

php -f mailtest.php

This is one of my client's Fedora servers, so I don't grok it completely, but I do have root access should I need to change anything.

from php.ini:

sendmail_path = /usr/sbin/sendmail -t -i

Not sure if this could matter, but /usr/sbin/sendmail is a symlink to /etc/alternatives/mta, which is a symlink back to /usr/sbin/sendmail.sendmail. FWIW the apache user does have permission to run sendmail (tested sendmail directly from the command line).

OS: Fedora Core 7 Linux (kernel 2.6.23.17)  
Apache: 2.2.8  
PHP: 5.2.6

Any help here will be greatly appreciated!

4条回答
三岁会撩人
2楼-- · 2019-01-12 05:01

This is my first answer here on StackOverflow! :o

So I had the same issue than you, matt! I use OpenSuse. I figured out that postfix check resulted with

postfix/postfix-script: warning: not owned by group maildrop: /usr/sbin/postqueue
postfix/postfix-script: warning: not owned by group maildrop: /usr/sbin/postdrop
postfix/postfix-script: warning: not set-gid or not owner+group+world executable: /usr/sbin/postqueue
postfix/postfix-script: warning: not set-gid or not owner+group+world executable: /usr/sbin/postdrop

so I ran the next commands:

# my postfix user is postfix and postfix group is maildrop
sudo chown 'postfix:maildrop' /usr/sbin/post{drop,queue}
sudo chmod g+s /usr/sbin/post{queue,drop}

and then, I tried to simple PHP script from my browser to test if everything works fine: (assuming you want to mail abc@gmail.com)

<?php
$ret = mail('abc@gmail.com', 'subject', 'message');
if ($ret === true)
  echo 'Success'.PHP_EOL;
else
  echo 'Error'.PHP_EOL;

and that's fine! I hope you will fix the issue with this method

查看更多
太酷不给撩
3楼-- · 2019-01-12 05:11

Is it a user permissions error? Your account and the one used to execute PHP scripts may have different privileges.

查看更多
聊天终结者
4楼-- · 2019-01-12 05:15

Anything in apache's error_log? Is PHP being run as an apache module or a CGI binary?

EDIT: Hmmm... nothing in the error log. What does the call to mail(...) return? Anything interesting in the mail log? This will vary depending on the MTA, often /var/log/maillog

EDIT 2: Is safe_mode turned on and are you using the mail() function's additional_parameters ?

查看更多
混吃等死
5楼-- · 2019-01-12 05:17

I found the problem. SELinux was preventing apache from being able to use sendmail. To diagnose, I used

$ sestatus -b | grep sendmail  
httpd_can_sendmail                   off

Then to actually fix the problem:

$ restorecon /usr/sbin/sendmail
$ setsebool -P httpd_can_sendmail 1

Read more about it here.

查看更多
登录 后发表回答