problems with htmlspecialchars - php

I am generating links from the following php code. The links appear in the browser, and the generated html code seems fine, however the links are not click-able. I have tested this in IE and FF, and tried to see with FireBug to no avail.
The code to generate my form
$uploadhtml = htmlspecialchars(json_encode("<form action='up.php' method='post'
enctype='multipart/form-data'>
<label for='file'>Filename:</label>
<input type='file' name='file' id='file'/>
<br />
<input type='hidden' name='pk' value='".$pk."'>
<input type='hidden' name='username' value='".$USERNAME."'>
<input type='submit' name='submit' value='Submit' onclick=\"setTimeout(function() {
updateByPk('Layer2', '".$pk."', '".$brand."', '".$pg."'); } ),1250);\" />
</form>"), ENT_QUOTES);
The resultant html code:
<a onclick="makewindows('"<form action='up.php' method='
post'\r\nenctype='multipart\/form-data'>\r\n<label for='
`file'>Filename:<\/label>\r\n<input type='file' name='file' id='`file'\/> \r\n<br \/>\r\n<input type='hidden' name='pk' value='
380118179930'>\r\n<input type='hidden' name='username' value='
janmaybach'>\r\n<input type='submit' name='submit' value='
Submit' onclick=\"setTimeout(function() { updateByPk('Layer2',
'380118179930', 'Ed Hardy', '1'); } ),1250);\"
\/>\r\n<\/form>"'); return false;" href="#">Upload files</a>
I guess it's a JavaScript error, but I don't know how to pinpoint it?
edit: The html code without ENT_QUOTES:
<a href="#" onclick="makewindows('"<form action='up.php' method='post'\r
\nenctype='multipart\/form-data'>\r\n<label for='file'>Filename:<\/label>\r\n<input
type='file' name='file' id='file'\/> \r\n<br \/>\r\n<input type='hidden' name='pk'
value='380118185183'>\r\n<input type='hidden' name='username' value='janmaybach'>\r
\n<input type='submit' name='submit' value='Submit' onclick=\"setTimeout(function()
{ updateByPk('Layer2', '380118185183', 'Ed Hardy', '1'); } ),1250);\"
\/>\r\n<\/form>"'); return false;">Upload files</a>
It still is not clickable..., everything seems to be quoted correctly?
When I try without htmlspecial chars, the following html output is produced:
<input type='submit' name='submit' value='Submit' onclick=" settimeout(function()="" {="" updatebypk(="" layer2="" 380118179930="" ed="" hardy="" ,="" 1="" );="" }="" ),1250);="">
'); return false;">Upload files</a>

As said in the comment to the question, this is absolutely horrendous code, and you're suffering the consequences. The main problem is the number of code levels: server code that renders Javascript, that renders HTML - and difference escapes at every level and interfere with each other.
To improve the situation, have a separate PHP page with the form and have your popup link open that page - no Javascript required. If you really want to avoid having that separate page at all costs, at least have the Javascript function that generates the form in the header of the page (non-dynamic) and have the link contain only a call to that function with your variables as parameters.

The parameter in your makewindows function ist not quoted. Your quotes are escaped (%#39). Replace it with ' and you're done.

Your ENT_QUOTES flag is screwing up the output. If you look closely you'll see that there are no actual quotes in the HTML output - just escaped entities. Make a test that doesn't use htmlspecialchars(). You should escape the quotes with a backslash OR better still add the javascript functionality unobtrusively. jQuery might help you to achieve that http://jquery.com

Related

Passing php variable as hidden input where html is contained in one echo

<?php
if(isset($_POST['btnLogin'])){
$myVariable = $_POST['fieldParameter'];
if(condition){
//do something
}else{
echo "
<form method='POST' action='submit.php'><br/>
<input type='hidden' name='myVariable' value='<?php echo $myVariable; ?>'/>
<br/>
<input type='submit' name='btnSubmit' id='submit' value='Submit'>
</form>
";
}
}
?>
Notice that the variable $myVariable is contained in the main IF block. I'm trying to send the value of $myVariable to submit.php as hidden field.
Also, i enclosed all the html tags using one echo statement with double quotes.
I found related questions here in SO but can't find similar to embedding php within a long echo of html tags
I tried to put value='<?php echo $studentNo; ?>' with no success.
I want to access it in a submit.php file like this,
submit.php
<?php
$aVariable = $_POST['myVariable'];
echo $aVariable;
?>
How can I pass the value contained in $myVariable as hidden field? Is there something wrong with the way I use double and single quotes?
If you are already echoing a string you shouldn't put <?php echo "" ?> inside it again. You should concatenate your string instead. But in your case you don't even need to do that, because you're using double quotes for echoing which means you can simply just write your variable in it.
echo "<form method='POST' action='submit.php'><br/>
<input type='hidden' name='myVariable' value='$myVariable;'/>
<br/>
<input type='submit' name='btnSubmit' id='submit' value='Submit'>
</form>";
If you were using single quotes for your echo, it would look like this:
echo '<form method="POST" action="submit.php"><br/>
<input type="hidden" name="myVariable" value="' . $myVariable . '"/><br/>
<input type="submit" name="btnSubmit" id="submit" value="Submit">
</form>';
You just need to type $myVariable instead of in your string. Double quotes "" only creates a string literal. It doesn't directly output data like inline HTML. As you can see from the syntax coloring in StackOverflow, the
You can try these variants (simplified):
// code before
echo "<input type='hidden' name='myVariable' value='$myVariable'/>";
// code after
// OR //
// code before
?>
<input type='hidden' name='myVariable' value='<?= $myVariable ?>'/>
<?php
// code after
Note that the quotes you use in HTML don't affect PHP, as long as you escape them properly (use \" and \' where appropriate).

how to properly handle php undefined index

I have a script where a user can input some text, view it, and change it. It looks like that:
if(isset($_POST['change']))
{
$text = $_POST['text'];
echo"
<form method='post' action='datei.php'>
<p>You wrote: $text</p>
<input name='text' type='hidden' size='21' value='$text'>
<input name='submit' type='submit' value='Change'>
</form>";
}else
{
$text = $_POST['text'];
echo"
<form method='post' action='datei.php'>
<p>Write some additional Information</p>
<input name='text' type='text' size='21' value='$text'>
<input name='change' type='submit' value='View'>
</form>";
}
When I load the page the first time, I get the following notification
Notice: Undefined index: text in ...
I found two solutions how to fix the problem:
Ignore Notifications
Use isset()
If I would use isset I would have to change two lines from above to:
if(isset($_POST['text']))$text = $_POST['text'];
and
<input name='text' type='text' size='21' value='"; if(isset($_POST['text'])) echo $text; echo"'>
Since my original form has more then 20 input fields, this would make the code less readable and more likly for erros when editing the code. Is there any better way to get around the notification that I currently miss?
First be sure that you define all the variables before using them, like
$text = false;
Plus, checking that a variable is set is always a good practice. Not to mention that you shouldn't be using $_POST directly.

Resource interpreted as Image but transferred with MIME type text/html, curl, php

I'm getting this error which i haven't seen before. I'm using cURL to try and get a captcha image from my site, but im getting this error instead of the image i want.
if(isset($_GET['captcha'])) {
$curl->open("GET","https://mydomain.com");
$curl->exec();
preg_match('/_mobile_sess=[^;]+/', $curl->getHeaders(), $sess);
$_SESSION['cookie'] = $sess[0];
preg_match('/ame="authenticity_token" type=\"hidden\" value=\"(.+?)\"/i',$curl->responseText, $tkn);
$_SESSION['token'] = $tkn[1];
preg_match('/\/signup\/captcha\/([0-9-a-z]+)\.gif/i', $curl->responseText, $cs);
$_SESSION['captchaUrl'] = $cs[1];
$curl->open("GET", "http://mydomain.com" . $cs[0]);
$curl->cookie = $_SESSION['cookie'];
$curl->exec();
echo $curl->responseText;
die;
}
I've set the MIME type as <meta http-equiv="Content-Type" content="image/gif"> in my head of my HTML doc but still get the same issue.
This is the form where i'm trying to output the image.
if(empty($_SERVER['QUERY_STRING'])){
echo "<center><form method='POST' action='?go'>
<input type='hidden' name='nameC' value='- SAFAL -' ><br/>
<b>User Name</b><br><input name='login' size='30' id='login' value='safal".rand(111111,9999999)."'><br/>
<b>Password</b><br><input name='senha' id='senha' size='30' value='".rand()."'><br/> <br>
<img src='?captcha'><br/>
<input name='cs' id='cs' placeholder='Put The Capcha' size='20' onclick='if(this.value==\"Digite aqui\") this.value=\"\"'><br><br><br>
<input type='submit' value='Click Here' id='btn'>
</form>";
}
Stumbled upon this question via Google Search. Adding my case for reference:
If you set a background-image: url('../img/sample.png'); like this with single quotation marks, the Chrome/ Opera console will also show this warning.
Eliminating the quotation marks does the trick.
Put header('Content-Type: image/gif'); in your php block code before you are printing a stream to output.

PHP $_POST Alert

I have this form which allows the input of any product quantity from 1-10:
<form method='post' action='cart.php'>
<input type='number' name='quantitychange' size='2' min='1' max='10' value=".$_SESSION["itemsSelected"][$i][1].">
<input type='hidden' name='ProductID' value=".$_SESSION["itemsSelected"][$i][0].">
<input type='submit' value='Update'>
</form>
And another form (button) to display a selection of payment modes:
<form action='cart.php' method='post'>
<input type='hidden' name='next'>
<input type='submit' value='Select Payment Mode'>
</form>
What I want to happen is that when a user did not input anything (1st form), ex. null or 0, I want to display an alert box that says 'Product quantity can't be null or 0'.
Here's my code for that:
if (isset($_POST['next'])) {
if ($_POST['quantitychange']==null || $_POST['quantitychange']==0) {
?>
<script type='text/javascript'>
alert('Product quantity can't be null or 0.');
</script>
<?php
}
else {
echo "
//Payment modes here
";
}
}
The error is that even when a user inputs a quantity bet. 1 to 10, it still displays the alert message. Any help? Thank you.
By the way, the input type "number" only works in Google Chrome browser.
Use a small javascript (or jQuery) function to validate the form before posting it. Have this function throw up the alert if your condition isn't met and then return false. If the condition is met, return true, and it gets submitted.
Edited to add since this might get googled, I'll help a bit with code snippet I have used. The below example is jQuery and was used in production for a web application I made for my employees. document.form.doit.submit(); should be the pure javascript way of submitting the form.
<script type="text/javascript">
function subForm() {
// document.form.doit.submit();
if( test condition passes ) {
$('#save_order').submit();
}
}
</script>
<form id="save_order" action="oms_db.php" method="POST">
<input id="doit" type="button"
value="i am a button" onClick="subForm();">
</form>
I think you have some error in your forms. Instead of the below:
<input type='number' name='quantitychange' size='2' min='1' max='10' value=".$_SESSION["itemsSelected"][$i][1].">
<input type='hidden' name='ProductID' value=".$_SESSION["itemsSelected"][$i][0].">
you should be using something like this:
<input type='number' name='quantitychange' size='2' min='1' max='10' value="<?php echo $_SESSION["itemsSelected"][$i][1]; ?>">
<input type='hidden' name='ProductID' value="<?php echo $_SESSION["itemsSelected"][$i][0]; ?>">
The value parameters in the hidden input fields needs to be echoed from PHP. What you have now is like the value is simple strings ".$_SESSION["itemsSelected"][$i][0].".
I suggest you use
if(empty($_POST['quantitychange'])) { echo 'yourerror'; }
As it is far cleaner then your script. (http://php.net/manual/en/function.empty.php)
Update:
Also, you can't use two seperate forms like you do, your browser only posts whats between
<form>
</form>
Using only one will fix your problem.

PHP - Input hidden fields with variables that contain quotes

I try to make a editor for a job offer. It must have a preview function. There are 2 form. First form submits the preview, the second one appears when the preview is there and sends the variables to save them in the database. The problem is, that when the second form get submitted, all quotes disappear. I tryed mysql_real_escape_string, htmlspecialchars, htmlentitles, but nothing works. Do you got an idea where the problem is?
Could it be that there's a problem, because I use the variable '$content' to store the site's content, instead to make a direct output with 'echo'?
Thanks!
<td><input style='float:left;' type='submit' name='jobpreview' value='preview' />
</form>";
if(isset($_GET['preview']))
{
$_POST['titel'] = htmlentities($_POST['titel']);
$_POST['elm1'] = htmlentities($_POST['elm1']);
$content .= " <td><form action='?s=intern&sub=neuerjob&preview' method='POST'>
<input type='hidden' name='titel' value='".$_POST['titel']."' />
<input type='hidden' name='elm1' value='".$_POST['elm1']."' />
<input style='float:left;' type='submit' name='jobsave' value='save' />
</form></td></tr></table>";
}
You need to use the second parameter to htmlentities() to encode the quotes.
$titel = htmlentities($_POST['titel'], ENT_QUOTES);
$elm1 = htmlentities($_POST['elm1'], ENT_QUOTES);
<input type='hidden' name='titel' value='".$titel."' />
<input type='hidden' name='elm1' value='".$elm1."' />
For this purpose, htmlentities() is overkill though, and you can use htmlspecialchars()
also with the ENT_QUOTES param.
$titel = htmlspecialchars($_POST['titel'], ENT_QUOTES);
$elm1 = htmlspecialchars($_POST['elm1'], ENT_QUOTES);

Categories