How to extract value from hidden field on form - php

I have form (on my own blog/cms install which i want to play with a bit) with hidden value which i want to extract. Problem is that there are 2 forms on that page, each with that hidden field with value. On each form field name is the same, only hidden value differs. Something like this:
<input type="hidden" id="_hiddenname" name="_hiddenname" value="valuehere"/>
Both look the same in html source. So, to help myself i opened php file with this page, edited it and added some random words before field that i need. So now one field (the one that i don't want) is like in above code but field i need is like this:
mywordshere <input type="hidden" id="_hiddenname" name="_hiddenname" value="valuehere"/>
How do i extract value from field i need (with mywordshere before its code) if i have my page's html source in php variable (grabbed with libcurl)?

An example using DOMDocument
<?php
$html = <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<body>
<input type="hidden" id="_hiddenname" name="_hiddenname" value="valuehere">
</body>
</html>
HTML;
$doc = new DOMDocument();
$doc->validateOnParse = true;
$doc->loadHTML( $html );
$node = $doc->getElementById( '_hiddenname' );
echo $node->getAttribute( 'value' );
?>
Note: your HTML string must have a DOCTYPE defined for this to work.

Assumably the two forms have different names, correct? So if you parse your scraped text with something DOM aware, you should be able to choose your input field by searching for it in its parent form.

The fact that you have two input fields named the same, and with the same id, is the real problem. The id attribute for HTML elements is supposed to be unique on a given page, and if it was, you could do this easily with a DOM parser. Example:
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$inputs = $dom->getElementsByTagName('input');
foreach ($inputs as $i)
{
if ($i->getAttribute('id') == 'targetId') {
//do some stuff
}
}
Since you can't take that approach, and you've marked your input with a string that you can identify, I would use a combination of string functions:
$str = 'mywordshere <input type="hidden" id="_hiddenname" name="_hiddenname" value="valuehere"/>';
$pos = strpos($str,'mywordshere');
if ($pos !== false) {
$valuePos = strpos($str,'value=',$pos);
if ($valuePos !== false) {
//get text starting from the 'value=' portion of the string
$str = substr($str,$valuePos);
$arr = explode('"',$str);
//value will be in $arr[1]
echo $arr[1];
}
}
I would strongly recommend you re-work your element IDs however, and use the DOM approach.

The value will be available in either $_GET["_hiddenname"] or $_POST["_hiddenname"], depending on which method you are using. Which one you get will depend on which form is doing the submitting.
If you have two fields which are named the same within the same form, you have a bigger problem.

Related

Searching my Array for values containing a specific character

I am developing a Website that is using HTML Valid Tags stored within an array for comparison against the users input into the system. I have currently developed the Array which contains all the of the HTML Tags that i require. I have also developed a function which validates the user input against data that is stored within the array.
If it is valid then it will tell the user it has been accepted and the valid tag will then be put in a different array which contains all of the tags that the user has inputted.
However i have tried to create the functionality that when the user inputs the tags within the system the array will be searched for any tags that contain a backslash / as this will identify all of the closing tags within the array.
So my question would be is how i would extract all records within my AllowedTags Array that contain a / Character and store those within a new array.
<html>
<head>
</head>
<body>
<form id="HTMLValidation" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<p> HTML Code: <input type="text" name="code">
<p><input type="submit" name="submit" value="Validate Your Code!"/></p>
</form>
<?php
//Depricated
//$TagArray = $UserInput.split("");
if(isset($_POST['code']))
{
$UserInput = htmlspecialchars($_POST['code']);
$InputtedTags = array();
//Array Containing all of the VALID HTML TAGS.
$AllowedTags = array("<html>","<head&gt","<body&gt","<div&gt","<p&gt","<b&gt","<base&gt","<link&gt","<meta&gt","<style&gt","<title&gt","<address&gt","<article&gt","<aside&gt","<footer&gt","<h1&gt","<h2&gt","<h3&gt","<h4&gt","<h5&gt","<h6&gt","<header&gt","<hgroup&gt","<nav&gt","<selection&gt","<dd&gt","<d1&gt","<dt&gt","<figcaption&gt","<figure&gt","<hr&gt","<li&gt","<main&gt","<ol&gt","<pre&gt","<ul&gt","<a&gt","<abbr&gt","<b&gt","<bdi&gt","<bdo&gt","<br&gt","<cite&gt","<code&gt","<data&gt","<dfn&gt","<em&gt","<i&gt","<kbd&gt","<mark&gt","<q&gt","<rp&gt","<rt&gt","<rtc&gt","<ruby&gt","<s&gt","<samp&gt","<small&gt","<span&gt","<strong&gt","<sub&gt","<sup&gt","<time&gt","<u&gt","<var&gt","<wbr&gt","<area&gt","<audio&gt","<img&gt","<map&gt","<track&gt","<video&gt","<embed&gt","<object&gt","<param&gt","<source&gt","<canvas&gt","<noscript&gt","<script&gt","<del&gt","<ins&gt","<caption&gt","<col&gt","<colgroup&gt","<table&gt","<tbody&gt","<td&gt","<tfoot&gt","<th&gt","<thead&gt","<tr&gt","<button&gt","<datalist&gt","<fieldset&gt","<form&gt","<input&gt","<label&gt","<legend&gt","<meter&gt","<optgroup&gt","<option&gt","<output&gt","<progress&gt","<select&gt","<textarea&gt","<details&gt","<dialog&gt","<menu&gt","<menuitem&gt","<summary&gt","<shadow&gt","<slot&gt","<template&gt","<acronym&gt","<applet&gt","<basefont&gt","<big&gt","<blink&gt","<center&gt","<command&gt","<content&gt","<dir&gt","<element&gt","<font&gt","<frame&gt","<frameset&gt","<isindex&gt","<keygen&gt","<listing&gt","<marquee&gt","<multicol&gt","<nextid&gt","<noembed&gt","<plaintext&gt","<shadow&gt","<spacer&gt","<strike&gt","<tt&gt","<xmp&gt","</html&gt","</head&gt","</body&gt","</div&gt","</p&gt","</b&gt","</base&gt","</link&gt","</meta&gt","</style&gt","</title&gt","</address&gt","</article&gt","</aside&gt","</footer&gt","</h1&gt","</h2&gt","</h3&gt","</h4&gt","</h5&gt","</h6&gt","</header&gt","</hgroup&gt","</nav&gt","</selection&gt","</dd&gt","</d1&gt","</dt&gt","</figcaption&gt","</figure&gt","</hr&gt","</li&gt","</main&gt","</ol&gt","</pre&gt","</ul&gt","</a&gt","</abbr&gt","</b&gt","</bdi&gt","</bdo&gt","</br&gt","</cite&gt","</code&gt","</data&gt","</dfn&gt","</em&gt","</i&gt","</kbd&gt","</mark&gt","</q&gt","</rp&gt","</rt&gt","</rtc&gt","</ruby&gt","</s&gt","</samp&gt","</small&gt","</span&gt","</strong&gt","</sub&gt","</sup&gt","</time&gt","</u&gt","</var&gt","</wbr&gt","</area&gt","</audio&gt","</img&gt","</map&gt","</track&gt","</video&gt","</embed&gt","</object&gt","</param&gt","</source&gt","</canvas&gt","</noscript&gt","</script&gt","</del&gt","</ins&gt","</caption&gt","</col&gt","</colgroup&gt","</table&gt","</tbody&gt","</td&gt","</tfoot&gt","</th&gt","</thead&gt","</tr&gt","</button&gt","</datalist&gt","</fieldset&gt","</form&gt","</input&gt","</label&gt","</legend&gt","</meter&gt","</optgroup&gt","</option&gt","</output&gt","</progress&gt","</select&gt","</textarea&gt","</details&gt","</dialog&gt","</menu&gt","</menuitem&gt","</summary&gt","</shadow&gt","</slot&gt","</template&gt","</acronym&gt","</applet&gt","</basefont&gt","</big&gt","</blink&gt","</center&gt","</command&gt","</content&gt","</dir&gt","</element&gt","</font&gt","</frame&gt","</frameset&gt","</isindex&gt","</keygen&gt","</listing&gt","</marquee&gt","</multicol&gt","</nextid&gt","</noembed&gt","</plaintext&gt","</shadow&gt","</spacer&gt","</strike&gt","</tt&gt","</xmp&gt");
//$Tags = implode(",",$AllowedTags);
//$OpenTags = implode(",",$AllowedTags);
//Search Allowed Tags Array For Values Containing a Backslash(/)
$CloseTags = implode(" ",$AllowedTags);
$needle = '/';
$ret = array_keys(array_filter($AllowedTags, function($var) use ($needle){
return strpos($var, $needle) !== false;}));
print_r($ret);
//Check What The User Has Inputted Into The System against the AllowedTags Array
//If it is true then display to the user the tag is valid
//Push The value that the user entered onto the InputtedTags Array
foreach($AllowedTags as $data)
{
if(strpos($UserInput,$data) !==false )
{
echo($UserInput. ": Valid Tags");
array_push($InputtedTags,$UserInput);
}
}
print_r($InputtedTags);
}
?>
</body>
</html>
"how i would extract all records within my AllowedTags Array that contain a / Character and store those within a new array"
$filtered_tags = array_filter($AllowedTags, function($val) {
return (bool)preg_match('/\//', $val);
});
print_r($filtered_tags);
If the user is providing the tags without angular brackets and only writing the tag name (say "head"), then maybe you can concatenate a backslash() in the beginning of the user input string while searching for the closing tag in the $AllowedTags.
I'm sorry if I misunderstood the question.

How to add static html markup to a CiviCRM form

I have CiviCRM 4.4.6 + Drupal 7 and i alter one of CiviCRM's forms.
Inside hook_civicrm_buildForm(), i try to:
form->addElement('html', 'statichtml', '<div>aa</div>');
$template =& CRM_Core_Smarty::singleton();
$bhfe = $template->get_template_vars('beginHookFormElements');
if (!$bhfe) {
$bhfe = array();
}
$bhfe[] = 'statichtml';
$form->assign('beginHookFormElements', $bhfe);
If i use it with 'text' element type, it works correctly. This way nothing is rendered, but an empty additional tr is added.
How to use this type of element correctly?
http://pear.php.net/manual/hu/package.html.html-quickform.intro-elements.php
Here is the explanation.
The element type should be static, not html and the above code starts to work.

How to get input field value from a form using preg_match()

I am not a expert in this field so please help me out and spare my ignorance if any.
I am trying to curl through a page and want to get value of the hidden <input> field. I am not familiar with regexp. my code is as below:
$page = curl_exec($ch);
}
curl_close($ch);
function parse_form_fields($page, $username, $password){
preg_match("/<input id=\"signuptoken\" type=\"hidden\" value=\"(.+?)\" name=\"signuptoken\"/", $page, $m);
$captchatoken = $m[1];
$parameters[] = "newaccounttoken=" . urlencode($captchatoken);
}
the form field is as below:
<input id="signuptoken" type="hidden" value="03AHJ_Vuv2ts6ev2LltAkZB91vjD6k-BsW3286bTC9QZYZLSHQUMNDQJFUaNmAQMAYb9FDhIkOFzAisafasfsTZuv_pl5KvkYNfsGUPcOAEX5YPlMaMOi7MZJq4ky0v_GyM60SmMgjPrtfZSJYE0hqw--GsfsafasmER0Sksr6OAvnLnBVAMsKcCi7uM" name="signuptoken">
I want to get the value out for this input field.
You're better off using DOMDocument. For example:
$html = '<input id="signuptoken" type="hidden" value="03AHJ_Vuv2ts6ev2LltAkZB91vjD6k-BsW3286bTC9QZYZLSHQUMNDQJFUaNmAQMAYb9FDhIkOFzAisafasfsTZuv_pl5KvkYNfsGUPcOAEX5YPlMaMOi7MZJq4ky0v_GyM60SmMgjPrtfZSJYE0hqw--GsfsafasmER0Sksr6OAvnLnBVAMsKcCi7uM" name="signuptoken">';
$dom = new DomDocument();
$dom->loadHTML($html);
$signuptoken = $dom->getElementById("signuptoken");
echo $signuptoken->getAttribute('value');
This should work for you to find the value:
<?php
$input = '<input id="signuptoken" type="hidden" value="03AHJ_Vuv2ts6ev2LltAkZB91vjD6k-BsW3286bTC9QZYZLSHQUMNDQJFUaNmAQMAYb9FDhIkOFzAisafasfsTZuv_pl5KvkYNfsGUPcOAEX5YPlMaMOi7MZJq4ky0v_GyM60SmMgjPrtfZSJYE0hqw--GsfsafasmER0Sksr6OAvnLnBVAMsKcCi7uM" name="signuptoken">';
$result = preg_match('/<input id="signuptoken" type="hidden" value="(.*?)"/', $input, $matches);
if(!$result){
// Could not find input
} else {
// Input value found
echo 'Value: '.$matches[1];
}
Parsing HTML with regex is not exactly resilient, however, as simply changing the order of the id and the type in the example input tag will break the scraper. If you're sure the HTML will never change, that shouldn't be an issue, but just be aware a DOM parser may be more useful in some cases.
Don't use things like value=\"(.+?)\", you may have a lot of troubles with them in some bad-formated HTML. Use something more limiting like value=\"([^\">]+?)\". The difference is that . matches a lot more entities, than [^">], which will always end on tag close or quote close.
The problem in your case might be the lack of multi-line match modifier s, try preg_match('/<input id="signuptoken" type="hidden" value="(.*?)"/s', $page, $m);.
Other than that, I'll second that, use DOM.
Also, save page HTML into file and test your RegEx on local file instead of calling the page every time.

Grabbing hidden inputs as a string (Using PHP Simple HTML DOM Parser)

So I have a form that has 4 inputs, 2 text, 2 hidden. I've grabbed the two text input values from the name, which are (get_me_two, get_me_three) and I've also grabbed the form action which is (get_me.php). What I'm looking to do now is grab the 2 hidden inputs, but not the values. I want to grab the inputs themselves.
E.G: Here's my form:
<form action="get_me.php" method="post">
<input type="text" name="get_me_two">
<input type="text" name="get_me_three">
<input type="hidden" name="meta_required" value="from">
<input type="hidden" name="meta_forward_vars" value="0">
</form>
And what I want to grab from here is the two hidden inputs, Not the values, the complete string.
I'm not sure how to grab these using: PHP Simple HTML DOM Parser, if anybody knows a way that would be great, if not, if there's an alternative that also would be great. Once I've grabbed these I plan on passing the 2 input values to another page with the hidden strings, and of course the form action.
Also, if anybody is interested here's my full code, which includes the simple html dom functionality.
<?php
include("simple_html_dom.php");
// Create DOM from URL or file
$html = file_get_html('form_show.php');
$html->load('
<form action="get_me.php" method="post">
<input type="text" name="get_me_two">
<input type="text" name="get_me_three">
<input type="hidden" name="meta_required" value="from">
<input type="hidden" name="meta_forward_vars" value="0">
</form>');
// Get the form action
foreach($html->find('form') as $element)
echo $element->action . '<br>';
// Get the input name
foreach($html->find('input') as $element)
echo $element->name . '<br>';
?>
So, the end result would grab the 3 values, and then the 2 hidden inputs (full strings). Help would be much appreciated as It's driving me a little mad trying to get this done.
I don't use the SimpleDom (I always go whole-hog and use DOMDocument), but couldn't you do something like ->find('input[#type=hidden]')?
If the SimpleDOM doesn't allow that sort of selector, you could simply loop over the ->find('input') results and pick out the hidden ones by comparing the attributes yourself.
If you use DomDocument, you could do the following:
<?php
$hidden_inputs = array();
$dom = new DOMDocument('1.0');
#$dom->loadHTMLFile('form_show.php');
// 1. get all inputs
$nodes = $dom->getElementsByTagName('input');
// 2. loop through elements
foreach($nodes as $node) {
if($node->hasAttributes()) {
foreach($node->attributes as $attribute) {
if($attribute->nodeName == 'type' && $attribute->nodeValue == 'hidden') {
$hidden_inputs[] = $node;
}
}
}
} unset($node);
// 3. loop through hidden inputs and print HTML
foreach($hidden_inputs as $node) {
echo "<pre>" . htmlspecialchars($dom->saveHTML($node)) . "</pre>";
} unset($node);
?>

Finding name attributes inside a tag using php

i want to find the name attribute with in a tag in a form using php4 . Does any one help me how it find..
eg
<input type="text" name="txt_name" value="" >
I want to know name of all the fields
You need a library/code which implements an HTML DOM, look at these SO questions for more information.
When you submit a form, a url is send to the server in the form "name=value&name1=value1" etc. Here the "name" stands for the attribute "name" of an html element. So If you are using the $_GET or a $_POST then you can get the form item names in an array as follows
$names=array();
foreach($_GET as $key => $value)
{
$names[] = $key;
}
print_r($names);
You can use simple html dom as mentioned by Ignacio Vazquez-Abrams
Add it in your code like this
require_once('Simple_html_dom.php');
To use it I initialized it using this line
$html = new Simple_html_dom();
Load a page or link using the line
$html->load_file('http://www.yourste.com/yourpage.php');
to parse and find this element
$e = $html->find("input", 0);
the echo the value of attribute name
echo $value = $e->name

Categories