views:

230

answers:

2

I grabbed this bit of code from the PHP.net readfile page:

<?php

// Action controller
public function someAction() {

    $response = $this->_response;

    // Disable view and layout rendering
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout()->disableLayout();

    // Process the file
    $file = 'whatever.zip';
    $bits = @file_get_contents($file);
    if(strlen($bits) == 0) {
        $response->setBody('Sorry, we could not find requested download file.');
    }
    else {
        $response->setHeader('Content-type', 'application/octet-stream', true);
        $response->setBody($bits);
    }
}

?>

It works great with most files but when I test it on a file with spaces in the filename, it says it can't find the requested file. Any suggestions, or is there a better way to do a readfile in Zend Framework where the filename can have spaces in it?

+1  A: 

From the file_get_contents() manual page:

Note: If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

(Edit: Use rawurlencode() to convert spaces to %20 instead of +)

So, you need to rawurlencode() the filename before using it:

$file = rawurlencode('whatever.zip');
Richard Nguyen
No dice there. It puts +'s in the name and I get the message saying "Sorry, we could not find requested download file."
Stepppo
You're right. Use `rawurlencode()` instead. This translates spaces to `%20` instead of `+`. Don't use `str_replace()` :)
Richard Nguyen
I couldn't get rawurlencode() to work either. Just curious, why don't use str_replace()?
Stepppo
Using `str_replace()` makes for fragile and unmaintainable code - you're essentially writing a hack to manually encode the space character. `rawurlencode()` will encode *all* non-alnum characters so your code doesn't break when you suddenly get a filename with a `@` or `^` character.
Richard Nguyen
`rawurlencode()` may not be working if you run it on a directory path, since it will also encode slashes. It is designed to run on only the filename part of a URI. If you're downloading a file from a directory, just append the encoded filename to the directory path. See the PHP Manual for usage examples: http://www.php.net/manual/en/function.rawurlencode.php
Richard Nguyen
A: 

I got rid of the space in the filename with a string replace and now it works:

$file = str_replace(" ","%20",$file);
Stepppo