Vinayak
Vinayak

Reputation: 776

Prepend bytes to file before download

Is it possible to prepend some bytes to a file when it is requested for download WITHOUT writing the file on the server in a temporary location using PHP.

For example, consider a file somefile.txt which has the contents "originaltext". If the file is requested for download, then the file that gets downloaded has the contents "prependedtext_originaltext"

I wish to achieve this without creating a temp copy of the file on the server because this file is likely to be very large and server space would fill up rapidly if a large number of users requested the file.

Thanks

Upvotes: 1

Views: 126

Answers (1)

Jan Hančič
Jan Hančič

Reputation: 53931

It's possible, of course.

Now this depends on how you are serving the files. If you link directly to the files you will have to create a rewrite rule in your web server, that will pass the requested file to your PHP script[1]. The script will then output your "prependtext" along with the contents of the file. Don't forget to add appropriate HTTP headers[2]!

If you are already serving the files trough a PHP script then you jut need to output your "prependtext" before you output the contents of the file.

Remarks:

[1] To do so memory efficient with large files, use readfile()

[2] For text files the most important header is Content-type: text/plain (also see documentation for header() and readfile())

Upvotes: 3

Related Questions