Syed Saqib Nadvi
Syed Saqib Nadvi

Reputation: 29

Detect Dir after / in a URL

I want to write a PHP script which will first detect URL's and see if they have sub dir or not, if they are simple URL like site.com then it would write 1 in one of the DB's table but if the URL is something like this site.com/images or site.com/images/files then it should'nt do the query..

EDIT: Answer by Mob it works but doesnt work if there are more than one url

 $url = "http://lol.com";
 $v = parse_url($url);

 if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
 echo "yeah";
 } else { 
 echo "nah";
 }

Upvotes: 1

Views: 89

Answers (3)

Mob
Mob

Reputation: 11106

Use parse_url

$url = "http://lol.com";
$v = parse_url($url);

if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
       echo "yeah";
   } else { 
       echo "nah";
   }

EDIT:

To parse multiple urls;

  • Store the urls in an array.
  • Use a loop to iterate over the array while passing the values to a function that performs the check

Here:

<?php


$arr = array("http://google.com",
             "http://google.com/image/",
             "http://flickr.com",
             "http://flickr.com/image" );

foreach ($arr as $val){
    echo $val."       ". check($val)."\n";
}

function check ($url){
$v = parse_url($url);

if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
           return "true";
       } else { 
           return "false";
       }
}
    ?>

The output is :

http://google.com              false
http://google.com/image/       true
http://flickr.com              false
http://flickr.com/image        true

Upvotes: 2

Pete
Pete

Reputation: 1309

$_SERVER is what you need. I'll let you google it.

Upvotes: 0

SenorAmor
SenorAmor

Reputation: 3345

Try strpos()

Syntax: strpos($haystack, $needle)

You could use something like:

if (!strpos($url, '/'))
{
    do_query();
}

edit Remember to strip the slashes in http://, of course.

Upvotes: 0

Related Questions