在插件目录中使用PHP创建一个CSV

时间:2016-12-12 作者:Jordan

我正在尝试在我的管理面板中开发一种方法,允许在插件目录中创建CSV文件。下面是我的代码:其中$amount是预先计算的文件名的下一个增量(如果存在1.CSV和2.CSV,则创建3.CSV)。由于我尝试回显文件路径,此计算工作正常

    function createNewGallery($amount)
{
    $files = $amount;
    echo "CREATE NEW GALLERY";
    $databaseURL = plugins_url( \'/\', __FILE__ );
    $databaseURL .= $files + 1 . \'.csv\';
    echo $databaseURL;
    $headers = array(\'imageid\', \'imgurl\', \'IMGTEXT\');
    echo " $headers ";

    $fp = fopen($databaseURL, \'w\');
    fwrite($fp, $headers);
    fclose($fp);

}
上面的代码似乎可以执行,但实际上没有做任何事情。我希望它在指定的目录中创建CSV的下一次迭代,然后将标题推送到它,但查看实时FTP时什么都没有发生

2 个回复
最合适的回答,由SO网友:prosti 整理而成

如果您计划写入pugin文件夹fopen, fwite, flose 您使用了错误的功能:

File: wp-includes/link-template.php
3189: /**
3190:  * Retrieves a URL within the plugins or mu-plugins directory.
3191:  *
3192:  * Defaults to the plugins directory URL if no arguments are supplied.
3193:  *
3194:  * @since 2.6.0
3195:  *
3196:  * @param  string $path   Optional. Extra path appended to the end of the URL, including
3197:  *                        the relative directory if $plugin is supplied. Default empty.
3198:  * @param  string $plugin Optional. A full path to a file inside a plugin or mu-plugin.
3199:  *                        The URL will be relative to its directory. Default empty.
3200:  *                        Typically this is done by passing `__FILE__` as the argument.
3201:  * @return string Plugins URL link with optional paths appended.
3202:  */
3203: function plugins_url( $path = \'\', $plugin = \'\' ) {
3204: 
您可能应该使用此功能:

File: wp-includes/plugin.php
703: /**
704:  * Get the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in.
705:  *
706:  * @since 2.8.0
707:  *
708:  * @param string $file The filename of the plugin (__FILE__).
709:  * @return string the filesystem path of the directory that contains the plugin.
710:  */
711: function plugin_dir_path( $file ) {
712:    return trailingslashit( dirname( $file ) );
713: }
那你就靠自己了:

$plugin_dir = plugin_dir_path( __FILE__ );
$logfile = $plugin_dir . \'log.csv\';

$fp = fopen($logfile, \'w\');
fwrite($fp, $data);
fclose($fp);
目前,WordPress中的插件拥有WordPress写入文件系统时的所有权限,这些权限是web服务器进程赋予的。

您的命名约定不完美:$databaseURL 可能是选错了。这不是URL。

SO网友:Rarst

写入插件目录被认为是不正确的做法:

插件更新时会覆盖插件目录在WP结构中,写操作最容易的位置(尽可能允许)是uploads文件夹(wp-content/uploads 默认情况下,但实际上应该针对当前配置进行检测)。

此外,如果数据是最不敏感的,您应该考虑永远不要将其留在web可访问的文件夹中(这是所有WP结构的设计)。您可以在服务器上的不同位置生成并从中提供服务,也可以动态创建并发送到浏览器,而无需创建中间文件。