How to get parts of an URL

Discussion in 'PHP' started by medialab, Aug 26, 2014.

  1. #1
    Hey Everyone,

    How can I use PHP to get parts out of an URL?

    Example: http://www.website.com/first-part/second-part/whatever/

    I want to extract the first-part and second-part in the url and echo them.

    I know there is something with dir_name but I can't figure it out for the life of me.

    Thanks!
     
    medialab, Aug 26, 2014 IP
  2. Jameyson MacDonald

    Jameyson MacDonald Well-Known Member

    Messages:
    452
    Likes Received:
    83
    Best Answers:
    3
    Trophy Points:
    115
    #2
    Whether or not you can do this will depend on accessibility. If access to the first-part is restricted, you won't be able to view or extract it. Many websites, for instance, have their images directory restricted so that while you may be able to view an image file in that directory, you can't view the complete contents of that directory.
     
    Jameyson MacDonald, Aug 26, 2014 IP
  3. medialab

    medialab Well-Known Member

    Messages:
    366
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    138
    Digital Goods:
    1
    #3
    Hey Jameyson,

    The folders don't really exist, they are created in .htaccess, I just need to get the text parts out, there is no accessibility issues.
     
    medialab, Aug 26, 2014 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    Disregard that last answer, it's completely off the mark.
    What you can do, if you always know which parts you want to extract, just check out this: http://php.net/manual/en/function.parse-url.php and do an explode() on the path item returned
     
    PoPSiCLe, Aug 26, 2014 IP
    malky66 likes this.
  5. medialab

    medialab Well-Known Member

    Messages:
    366
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    138
    Digital Goods:
    1
    #5
    Thanks PopSiCLe! For anyone else looking here is the code:

    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $path = parse_url($url, PHP_URL_PATH);
    $segments = explode('/', rtrim($path, '/'));
    PHP:
    Than you can just echo the outputs for as many as you have like so:

    <?php echo $segments[1]; ?>
    <?php echo $segments[2]; ?>
    ETC
    Code (markup):
     
    medialab, Aug 26, 2014 IP
  6. abhicyco

    abhicyco Active Member

    Messages:
    36
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #6
    I guess thats the best and easy solution anyone can go for..
     
    abhicyco, Aug 26, 2014 IP