title: PHP: How to get base URL from HTML page
body: <p>I'm struggling with figuring out how to do this. I have an absolute URL to an HTML page, and I need to get the base URL for this. So the URLs could be for example:</p>
  
  <ul>
  <li><a href="http://www.example.com/" rel="nofollow">http://www.example.com/</a></li>
  <li><a href="https://www.example.com/foo/" rel="nofollow">https://www.example.com/foo/</a></li>
  <li><a href="http://www.example.com/foo/bar.html" rel="nofollow">http://www.example.com/foo/bar.html</a></li>
  <li><a href="https://alice@www.example.com/foo" rel="nofollow">https://alice@www.example.com/foo</a></li>
  </ul>
  
  <p>And so on. So, first problem is to find the base URL from those and other URLs. The second problem is that some HTML pages contain a base tag, which could be for example <code>http://example.com/</code> or simply <code>/</code> (although I think some browser only support the one starting with <code>protocol://</code>?).</p>
  
  <p>Either way, how can I do this in PHP corrrectly? I have the URL and I have the HTML loaded up in a DOMDocument so should be able to grab the base tag fairly easily if it exists. How do browsers solve this for example? </p>
  
  <hr>
  
  <p><strong>Clarification on why I need this</strong></p>
  
  <p>I'm trying to create something which takes a URL to a web page and returns the absolute URL to all the images this web page links to. Since some/many/all of these images might have relative URLs, I need to find the base URL to use when I make them absolute. This might be the base URL of the web page, or it might be a base URL specified in the HTML itself.</p>
  
  <p>I have managed to fetch the HTML and find the URLs. I think I've also found a working method of making the URLs absolute when I have the base URL to use. But finding the base URL is what I'm missing, and what I'm asking about here.</p>