Get variable from URL (posted in a form)

Discussion in 'PHP' started by MrLeN, Jan 17, 2013.

  1. #1
    I know how to get a variable from a URL if it is the current URL. That's easy. Just use $_GET['value']..

    ..but what if the value is posted in a URL in a form. How can I get it then?

    ie:

    I have a form, and someone enters a YouTube URL:

    https://www.youtube.com/watch?v=dMH0bHeiRNg

    The method is POST!

    Ok, so how can I get the value of "v"?

    ie: I want something like:

    $video_id = "???How do I get v???";

    Then I can use $video_id for my purposes.
     
    Solved! View solution.
    Last edited: Jan 17, 2013
    MrLeN, Jan 17, 2013 IP
  2. MrLeN

    MrLeN Well-Known Member

    Messages:
    406
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    120
    #2
    I suspect that my explanation above will confuse people (after reading it, lol).

    So, I will explain another way:

    if $_POST['video_url'] = https://www.youtube.com/watch?v=dMH0bHeiRNg

    ..then, how can I get the value of "v" out of it and turn it into $video_id?

    So I have:

    $video_id = "dMH0bHeiRNg";

    ???
     
    MrLeN, Jan 17, 2013 IP
  3. MrLeN

    MrLeN Well-Known Member

    Messages:
    406
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    120
    #3
    A friend helped me in skype.

    This is the answer:

    
    preg_match('|v=([a-zA-Z0-9]{11})|', $_POST['video_url'], $matches);
    $video_id =  $matches[1];
    
    Code (markup):
     
    MrLeN, Jan 17, 2013 IP
  4. danmaster

    danmaster Greenhorn

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #4
    MrLeN look function parse_url
     
    danmaster, Jan 17, 2013 IP
  5. #5
    I would use built in methods instead, this way no matter what Google decides the v variable becomes or changes, it will always work:

    
    <?php
    $url = 'https://www.youtube.com/watch?v=dMH0bHeiRNg';
    $parts = parse_url($url);
    if (!empty($parts['query'])) {
        // baz
        parse_str($parts['query'], $variables);
        echo $variables['v'];
    }
    
    PHP:
     
    ThePHPMaster, Jan 18, 2013 IP
  6. MrLeN

    MrLeN Well-Known Member

    Messages:
    406
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    120
    #6
    That is actually very helpful, and better than what I had already used. I appreciate your help mate.
     
    MrLeN, Jan 18, 2013 IP
  7. dixcoder

    dixcoder Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    26
    #7
    thanks mate for sharing didn't know there was parse_url function too i also used to do same via preg match which wasn't accurate all the time :)
     
    dixcoder, Jan 20, 2013 IP