1

我有一个带有 WAMP、Wordpress 和 PHPEdit IDE 的开发人员环境设置。我在侧边栏中使用 Facebook、Twitter 和 YouTube API。我正在使用 Facebook 的 PHP SDK 来显示信息(没有登录或管理功能)。由于 FB SDK 和 WP 使用 session_start() 我收到以下警告:

警告:session_start() [function.session-start]:无法发送会话缓存限制器 - 标头已发送(输出开始于 C:\wamp\www\dfi\wp-content\themes\DFI\header.php:12) C:\wamp\www\dfi\wp-content\themes\DFI\api\facebook.php 在第 36 行

我试图通过使用警告输出来解决这个问题,但它无助于考虑以下内容。<?php ?>我知道在任何 http 输出之前和之后清除空格和字符并将 session_start() 放置在之前。我使用没有 BOM 的 unix line enders 和 UTF8 编码。我的主机服务器没有为 output_buffering 设置。

header.php 第 11 到 13 行

11 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
12 <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes();?>>
13 <head>

看起来警告来自内联 php 代码。我不知道我能做些什么来修复这条线。

facebook.php 第 34 至 37 行

34    public function __construct($config) {
35    if (!session_id()) {
36      session_start();
37    }

我认为我不能阻止 FB 或 WP 调用 session_start() 而不会破坏一切。如何让 Wordpress 和 Facebook 完美配合而不会出现此错误?

编辑:为了停止显示警告,我将@放在 session_start() 前面。

public function __construct($config) {
    if (!session_id()) {
      @session_start();
    }

它只是一种解决方法,我仍然想找到问题的根源。

4

2 回答 2

1

正如您在评论中发现的那样,问题不在于包含 PHP 文件,而在于您定义类的位置。wp在钩子中可以安全地创建 Facebook 类的实例(据我所知,它对我有用) 。这将允许您在任何 HTML 输出之前定义类的实例,然后您可以在类中的任何位置使用该变量。

但是,您确实希望确保只包含一次该类,但您可以根据需要多次实例化该类。

这是一个让您入门的基本示例:

if( !class_exists( 'Facebook' ) ) {
    require_once 'facebook.php';
}

if( !class_exists( 'YourClass' ) ) {

    class YourClass {

        public $facebook = null;

        public function __construct() {

            add_action( 'wp', array( $this, 'define_facebook' ) );
            add_action( 'any_hook_after_wp', array( $this, 'example_usage' ) );

        }

        public function define_facebook() {
            global $post;

            // Assuming you are using post meta for the app ID and secret, you can use other methods though
            $app_id = get_post_meta( $post->ID, 'appId', true );
            $app_secret = get_post_meta( $post->ID, 'appSecret', true );

            $this->facebook = new Facebook( array( 'appId' => $app_id, 'secret' => $app_secret ) );

        }

        public function example_usage() {

            if( !is_null( $this->facebook ) ) {

                // Lets see what we have here..
                echo "<pre>";
                print_r( $this->facebook );
                echo "</pre>";
                exit;

            }

        }

    }

}
于 2012-06-02T01:25:05.603 回答
0

您可以使用 Hook Action init 来检查 session_id 是否存在。


// add it into functions.php in theme folder
add_action('init', 'themename_wp_session_start');
function themename_wp_session_start(){
    if( !session_id() ){
        session_start();
    }
}

于 2015-04-16T06:31:49.513 回答