5

I have a simple script like this

$data = "http://example.com/index.php?data=data&value=value";

How to get base url from $data? The output will be like this

http://example.com

The output without this text " /index.php?data=data&value=value

G.I Joe
  • 53
  • 1
  • 4

4 Answers4

15

Use parse_url()

$url = "http://example.com/index.php?data=data&value=value";
$url_info = parse_url($url);
echo $url_info['host'];//hostname

Additionally $user_info contain below

[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor

SO you can get http by scheme

you can do something like :

echo $url_info['scheme'] . '://' . $url_info['host'];//http://example.com

Devsi Odedra
  • 5,071
  • 1
  • 21
  • 33
0

Check Parsing Domain From URL In PHP

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'
0

You can use pathinfo included scheme and hostname.

$url = "http://example.com/index.php?data=data&value=value";
$base_url = pathinfo($url, PATHINFO_DIRNAME);
echo $base_url;

Output:

http://example.com
Nabi K.A.Z.
  • 8,401
  • 6
  • 51
  • 69
0
$url= parse_url($url, PHP_URL_HOST);

Why can't we just use this. Worked for me.

Yasir Ijaz
  • 514
  • 8
  • 18