get_file_data

Retrieve metadata from a file.

Description

(array) get_file_data( (string) $file, (array) $default_headers, (string) $context = '' ); 

Searches for metadata in the first 8kiB of a file, such as a plugin or theme. Each piece of metadata must be on its own line. Fields can not span multiple lines, the value will get cut at the end of the first line.

If the file data is not within that first 8kiB, then the author should correct their plugin file and move the data headers to the top.

Returns (array)

Array of file headers in `HeaderKey => Header Value` format.

Parameters (3)

0. $file (string)
Path to the file.
1. $default_headers (array)
List of headers, in the format array('HeaderKey' => Header Name).
2. $context — Optional. (string) => ''
The context.

Usage

  1. if ( !function_exists( 'get_file_data' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Path to the file. 
  5. $file = ''; 
  6.  
  7. // List of headers, in the format array('HeaderKey' => 'Header Name'). 
  8. $default_headers = array(); 
  9.  
  10. // The context. 
  11. $context = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = get_file_data($file, $default_headers, $context); 
  15.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function get_file_data( $file, $default_headers, $context = '' ) { 
  2. // We don't need to write to the file, so just open for reading. 
  3. $fp = fopen( $file, 'r' ); 
  4.  
  5. // Pull only the first 8kiB of the file in. 
  6. $file_data = fread( $fp, 8192 ); 
  7.  
  8. // PHP will close file handle, but we are good citizens. 
  9. fclose( $fp ); 
  10.  
  11. // Make sure we catch CR-only line endings. 
  12. $file_data = str_replace( "\r", "\n", $file_data ); 
  13.  
  14. /** 
  15. * Filters extra file headers by context. 
  16. * The dynamic portion of the hook name, `$context`, refers to 
  17. * the context where extra headers might be loaded. 
  18. * @since 2.9.0 
  19. * @param array $extra_context_headers Empty array by default. 
  20. */ 
  21. if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) { 
  22. $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values 
  23. $all_headers = array_merge( $extra_headers, (array) $default_headers ); 
  24. } else { 
  25. $all_headers = $default_headers; 
  26.  
  27. foreach ( $all_headers as $field => $regex ) { 
  28. if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] ) 
  29. $all_headers[ $field ] = _cleanup_header_comment( $match[1] ); 
  30. else 
  31. $all_headers[ $field ] = ''; 
  32.  
  33. return $all_headers;