user2937998
user2937998

Reputation: 367

PHP's file_get_contents: dealing with relative paths inside the result

I'm trying to solve a cross-domain issue, so I'm implementing a script that will get a URL from a GET parameter and open with file_get_contents. It works fine until the page try to get relative paths like (the following line is inside index.html):

<script src="js/custom_script.js" />

If I create a regex with preg_replace that replace all the HTML data switching js/custom.js to http://content.domain/js/custom_script.js it also works, but the problem is that I don't always know how many levels are inside the page I'm trying to open, like: index.html could have a button to another page with another relative paths.

Is there an elegant solution to this problem?

Upvotes: 1

Views: 261

Answers (1)

Jacob
Jacob

Reputation: 2767

I would use the base HTML tag, and instead of scraping through the whole source, just insert it right before the </head> tag.

Could be really simple with just a line of code: echo str_replace("</head>", "<base href=\"http://content.domain/\" target=\"_blank\"></head>", $source)

Using the base tag makes the browser handle all the nested links for you:

Specify a default URL and a default target for all links on a page:

Upvotes: 2

Related Questions