User adds a URL
(Like URLs
below). I want to return all links on the page that appears in href
attribute. I can get all links using DOMDocument class. But some links are relative. I want to convert them to absolute links.
Suppose I have these strings (URLs
) (User may sends any link. like one of these):
http://example.com/test/index.html
http://example.com/test/test.php
http://example.com/test/
http://example.com/test
Now I get all contents of the href
of user's input URL
. Some of these URLs are relative so I have to merge those relative links to the base URL
. My problem is that I cannot get the base URL. In this example my base URL
would be http://example.com/test
. So if user enters any of those URLs
above I have to get the same base URL
.
How can I extract the URL base correctly?
You can use parse_url method like this code:
<?php
$url = 'http://example.com/test';
//get base url from link
$base_url=parse_url($url, PHP_URL_HOST);
//get path from link
$path=parse_url($url, PHP_URL_PATH);
//print base_url
echo 'Base URL = '.$base_url;
//print path
echo ' PATH = '.$path;
?>