Way to create an HTTP proxy to convert relative paths to absolute paths

237 Views Asked by At

So, let's say that I am trying to proxy somesite.com, and I want to change this:

<!doctype html>
<html>
 <body>
  <img src="computerIcon.png">
 </body>
</html>

to:

<!doctype html>
<html>
 <body>
  <img src="http://someproxy.net/?url=http://somesite.com/computerIcon.png">
 </body>
</html>

And by the way, I prefer PHP.

1

There are 1 best solutions below

0
Syscall On

You can use an XMLparser to update URLs of a document :

// Initial string
$html = '<!doctype html>
<html>
 <body>
  <img src="computerIcon.png">
 </body>
</html>
';

$proxy = 'https://proxy.example.com/?url=https://domain.example.com/';

// Load HTML
$xml = new DOMDocument("1.0", "utf-8");
$xml->loadHTML($html);

// for each <img> tag,
foreach($xml->getElementsByTagName('img') as $item) {
    // update attribute 'src'
    $item->setAttribute('src', $proxy . $item->getAttribute('src'));
}

$xml->formatOutput = true;
echo $xml->saveHTML();

Output:

<!DOCTYPE html>
<html><body>
  <img src="https://proxy.example.com/?url=https://domain.example.com/computerIcon.png">
</body></html>

Demo: https://3v4l.org/bW68Z