0

I want to get URL from HTML form action. How can I get this in PHP? The form tag like

<form method="post" action="my.aspx? id="aspnetForm" enctype="multipart/form-data">

</form>
Mahmood Rehman
  • 4,303
  • 7
  • 39
  • 76
  • possible duplicate of [Get a forms action/url with jquery](http://stackoverflow.com/questions/5620420/get-a-forms-action-url-with-jquery) – Kermit Jan 04 '13 at 16:40
  • 1
    PHP is a server-side language ... can you explain in more detail what it is you are trying to do ? – Manse Jan 04 '13 at 16:40
  • are you grabbing/scraping the the page, and trying to parse the html to get the action? – Doon Jan 04 '13 at 16:41
  • I want to read html page and try to get the url section from that. – Mahmood Rehman Jan 04 '13 at 16:41
  • Firstly, that code is invalid (although I'm assuming the `?` should be a `"`) And secondly: What are you talking about? When do you want the action URL (on/after page request)? How is the form given the URL? Read the question from our point of view and then try answering it. **It's hard work** – George Jan 04 '13 at 16:42
  • Ok let me more clear i want to read a page which contain form with action.Now i want to get only the url form action portion.I think this can be done using file_get_content like some function but not sure yet. – Mahmood Rehman Jan 04 '13 at 16:45
  • you can use DOM of php - just render it and take the attribute you want – sourcecode Jan 04 '13 at 16:46

3 Answers3

2

You can try to load the HTML with DOM and then extract the information using xpath:

// create a DOM document object and load your html
$doc = new DOMDocument();
$doc->loadHtml($yourHtml);

// create an Xpath selector for the document
$selector = new DOMXpath($doc);

// the following query will return all <form> elements
// you may refine it
$result = $selector->query('//form');

// get the first item (to keep the example simple)
$form = $result->item(0);

// get the value of the action attribute
$url = $form->getAttribute('action');
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

You can use regexp. But I think for you will simple make next steps:

  1. with stristr function detect begin of form tag - search string "<form"
  2. use stristr again for find begin of string "action="
  3. use substr for truncate first 7 chars to begin url string
  4. use strpos for detect first space after url string
  5. use substr for get string of url
  6. delete space and quotes from this string. Use for this str_replace or trim function

I think this will help you for study how you can parse any html tags and others things.

newman
  • 2,689
  • 15
  • 23
0

you can get like this..

      <?php
       $string = <<<XML
       <form method="post" action="my.aspx? id="aspnetForm" enctype="multipart/form-data"></form>
       XML;

      $xml = new SimpleXMLElement($string);

      $att = 'action';
      $attribute = $xml->form[0]->attributes()->$att; // answer
      ?>
sourcecode
  • 1,802
  • 2
  • 15
  • 17