How do I read values (PHP defined constants) from wp-config.php?

后端 未结 7 1046
悲哀的现实
悲哀的现实 2021-02-07 03:40

I need to get username, password etc from the wp-config file to connect to a custom PDO database.

Currently I have another file where I have this info, but

7条回答
  •  深忆病人
    2021-02-07 04:15

    Here is a function to read all WP DB defines:

    function get_wordpress_data() {
        $content = @file_get_contents( '../wp-config.php' );
    
        if( ! $content ) {
            return false;
        }
    
        $params = [
            'db_name' => "/define.+?'DB_NAME'.+?'(.*?)'.+/",
            'db_user' => "/define.+?'DB_USER'.+?'(.*?)'.+/",
            'db_password' => "/define.+?'DB_PASSWORD'.+?'(.*?)'.+/",
            'db_host' => "/define.+?'DB_HOST'.+?'(.*?)'.+/",
            'table_prefix' => "/\\\$table_prefix.+?'(.+?)'.+/",
        ];
    
        $return = [];
    
        foreach( $params as $key => $value ) {
    
            $found = preg_match_all( $value, $content, $result );
    
            if( $found ) {
                $return[ $key ] = $result[ 1 ][ 0 ];
            } else {
                $return[ $key ] = false;
            }
    
        }
    
        return $return;
    }
    

    this returns an array like this:

    array (size=5)
      'db_name' => string '.........'
      'db_user' => string '.........'
      'db_password' => string '.........'
      'db_host' => string 'localhost'
      'table_prefix' => string 'wp_'
    

提交回复
热议问题