PHP - file_put_contents 在文件夹中保存文件

PHP - file_put_contents Save file in folder

尝试将电子邮件中的附件保存到我的服务器中,我目前使用的脚本运行良好,但是它将文件保存在我的 wp 根文件夹中。

foreach ($attachments as $key => $attachment) {
    $name = $attachment['name'];
    $contents = $attachment['attachment'];
    file_put_contents($name, $contents);
}

如何将文件保存到不同的文件夹中?

尝试使用此代码但无法正常工作。

foreach ($attachments as $key => $attachment) {
    $name = $attachment['name'];
    $contents = $attachment['attachment'];
    file_put_contents(get_stylesheet_directory_uri() . '/email_attachments/' . $name, $contents);
}

有什么想法吗?

您添加的路径正确,只是 get_stylesheet_directory_uri() 用于网络路径: https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri

尝试类似 get_home_path() 的方法: https://codex.wordpress.org/Function_Reference/get_home_path

干杯!

这里供以后参考如何找到路径:

foreach ($attachments as $key => $attachment) {
        $name = $attachment['name'];
        $contents = $attachment['attachment'];
        file_put_contents(STYLESHEETPATH . '/email_attachments/' . $name, $contents);
    }

You're adding the path correctly, it's just that get_stylesheet_directory_uri() is for the web path : https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri

Try something like get_home_path() : https://codex.wordpress.org/Function_Reference/get_home_path

这是不正确的。 您需要使用 get_stylesheet_directory() 函数而不是 get_stylesheet_directory_uri()。

echo file_put_contents(get_stylesheet_directory().'/file.txt','test');

应该打印 4