Skip to content
Advertisement

How to use FPDI SetSourceFile with a URL that redirects?

I’ve got a PDF file on my server, and I want to use it as parameter for this function:

$fpdi->setSourceFile()

The problem is that the link used as a source redirects to another URL and I don’t know the final URL. It seems that setSourceFile needs the real PDF filename. Is there a way to get the final URL, and then pass it as parameter?

Advertisement

Answer

I edited your question according to the explanation you gave in the comments. This is not related to a rewrite, it’s related to URL redirection.

Solution 1: open a stream manually

I looked at the source code for this specific function and it expects to receive either a filename or a Stream. You could fetch the PDF link manually, process the redirects and pass the final Stream to this function:

$stream = fopen('https://example.com/12/PDF', 'rb', false, stream_context_create());

$fpdi->setSourceFile($stream);

You can tweak the headers and other parameters such as cookies in the stream_context_create function if needed. It’s likely that the remote server requires a cookie or something before redirect to the final URL.

Solution 2: download the file

If you pass a link to this function it will recognize it as a String and try to open it as a file. Since you stated that passing a link that doesn’t redirect works, your server is allowing the function fopen() to open external links. If that’s the case, you could simply use ordinary file functions to download the PDF to a local folder temporarily:

// saves the file locally
file_put_contents('localFile.pdf', file_get_contents('https://example.com/12/PDF'));

// do what you need to do with it
$fpdi->setSourceFile('localFile.pdf');

// deletes the file after using it
unlink('localFile.pdf');
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement