Skip to content

Instantly share code, notes, and snippets.

@kagg-design
Created February 23, 2023 16:06
Show Gist options
  • Select an option

  • Save kagg-design/b01de25eae04774bc24b6d2a6984c0cd to your computer and use it in GitHub Desktop.

Select an option

Save kagg-design/b01de25eae04774bc24b6d2a6984c0cd to your computer and use it in GitHub Desktop.

Revisions

  1. kagg-design created this gist Feb 23, 2023.
    86 changes: 86 additions & 0 deletions rest-download-xls.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,86 @@
    <?php

    add_action(
    'rest_api_init',
    static function () {
    $namespace = 'myplugin/v1';
    $route = '/file';
    $params = [
    [
    'methods' => 'GET',
    'callback' => 'my_callback',
    ],
    ];

    register_rest_route( $namespace, $route, $params );
    }
    );

    function my_callback( WP_REST_Request $request ) {

    my_download_file( site_url( 'test.xlsx' ) );
    }

    /**
    * Download file.
    *
    * @param string $url file url.
    */
    function my_download_file( string $url ): void {
    if ( ! $url ) {
    return;
    }

    $file_path = realpath( untrailingslashit( ABSPATH ) . wp_make_link_relative( $url ) );

    if ( ! $file_path ) {
    return;
    }

    $file_name = rawurlencode( pathinfo( $file_path, PATHINFO_FILENAME ) );

    $file_extension = rawurlencode( pathinfo( $file_path, PATHINFO_EXTENSION ) );

    $file_size = filesize( $file_path );

    $known_content_types = [
    'html' => 'text/html',
    'htm' => 'text/html',
    'txt' => 'text/plain',
    'jpg' => 'image/jpg',
    'jpeg' => 'image/jpg',
    'png' => 'image/png',
    'gif' => 'image/gif',
    'tiff' => 'image/tiff',
    'pdf' => 'application/pdf',
    'doc' => 'application/msword',
    'docx' => 'application/msword',
    'xls' => 'application/vnd.ms-excel',
    'xlsx' => 'application/vnd.ms-excel',
    'ppt' => 'application/vnd.ms-powerpoint',
    'pptx' => 'application/vnd.ms-powerpoint',
    'php' => 'text/plain',
    'exe' => 'application/octet-stream',
    'zip' => 'application/zip',
    ];

    $content_type = 'application/force-download';

    if ( array_key_exists( $file_extension, $known_content_types ) ) {
    $content_type = $known_content_types[ $file_extension ];
    }

    header( 'Expires: 0' );
    header( 'Cache-Control: no-cache, no-store, must-revalidate' );
    header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false );
    header( 'Pragma: no-cache' );
    header( "Content-type: {$content_type}" );
    header( "Content-Disposition:attachment; filename={$file_name}.{$file_extension}" );
    header( 'Content-Transfer-Encoding: binary' );
    header( "Content-Length: {$file_size}" );

    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_readfile
    readfile( $file_path );
    exit();
    }