expanding a quoted string within another string - php

I have two variables containing some html code, and another variable containing code for a html form. I am trying to expand a string within the second to pass it as a parameter to a function, however this causes some errors.
My make popup function is very simple:
function popup(htmlcode){
child1 = window.open ("about:blank");
child1.document.write(htmlcode);
child1.document.close();
}
The code that uses the above function
<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = "<form action=\"process.php\" method=\"post\" enctype=\"multipart/form-data \">
<label for=\"file\">Filename:</label>
<input type=\"file\" name=\"file\" id=\"file\"/>
<br />
<input type=\"submit\" name=\"submit\" value=\"Submit\" onclick=\"setTimeout(function() { sendInfo(\"".$blah."\", \"".$test."\"); } ),1250);\" />
</form>";
echo "<h1>hello</h1>
<div id='form'>
<a href='#' onclick=\"popup('" . htmlentities($formcode) . "'); return false;\">
click here</a>
</div>";
This produces decent enough html code, however firebug gives me an error that I have an unterminated string lateral. I cannot find where this is. I understand the way I have done this is not ideal, but I am learning and do not know a better way at present. I appreciate any input
edit: OK, so the problem was that I had unterminated string literals, which were \n characters. I made the string into one line and it called the function correctly.
Is it not possible to break one echo statement into multiple lines?
Now the problem is with the html generated in the popupwindow. Some of the code is actually printed to the screen, why is this?
<form action="process.php" method="post" enctype="multipart/form-data "><label for="file">Filename:</label><input name="file" id="file" type="file"> <br><input name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(" type="submit"><h1>Well</h1>", "<h2>Done</h2>"); },1250);" /></form>
See the image here:

A better way to do this is to open an HTML or PHP page that already has the form code in it, instead of opening about:blank and passing it dynamically.
There is no reason you should ever have to pass HTML into a Javascript function just so it can be directly written to document.

If you absolutely have to keep the popup function as is, I found a solution with help from this answer to "How do I escape a string inside javascript inside an onClick handler?".
<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = '<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br />
<input type="submit" name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(\\x27'.$blah.'\\x27, \\x27'.$test.'\\x27); }, 1250);" />
</form>';
echo "<h1>hello</h1>
<div id='form'>
<a href='#' onclick='popup(\"" . addslashes(str_replace("\n", ' ', $formcode)) . "\"); return false;'>
click here</a>
</div>";
?>
Before edit:
Maybe you can do it differently.
Javascript functions:
function popup(id, params){
var html = document.getElementById(id).innerHTML;
if (params != undefined) {
html = findAndReplaceStrings(html, params);
}
var child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
function findAndReplaceStrings(text, json) {
for (var x in json) {
text = text.replace(x, json[x]);
}
return text;
}
HTML hidden code:
<div style="display:none;" id="process">
<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br />
<input id="submit" type="submit" name="submit" value="Submit" onclick="setTimeout(function() { sendInfo('{param1}', '{param2}'); } ), 1250);" />
</form>
</div>
HTML link with json:
<a href="#" onclick="popup('process', {'{param1}':'<h1>Well</h1>', '{param2}':'<h2>Done</h2>'}); return false;">
click here</a>

You must escape the carriage returns (\n) by doing
$formcode = str_replace("\n", "\\n", $formcode);
You also have to escape the quotes
$formcode = str_replace("'", "\\'", $formcode);
You can combines those two lines into a single one:
$formcode = str_replace(array("\n", "'"), array("\\n", "\\'"), $formcode);

The submit button has an extra ) which closes the setTimeout function too early. The specific spot is inside:
} ),1250
you should also probably think about using single quotes inside the php string to make it all easier to read. And because you're using double quotes you don't have to break out of the string to insert the content of the variables $blah and $test.
something like this should work:
$formcode = "...
<input type='submit' name='submit' value='Submit'
onclick='setTimeout(function() { sendInfo(\"$blah\", \"$test\"); },1250);' />
...
";
EDIT:
looks like it's closing the onclick too early now. Matching these as the start and end quotes:
onclick=\"setTimeout(function() { sendInfo(\"
I changed the sendInfo line to the following, ran it and looks like it's working. The single quote is escaped here so it doesn't prematurely close the call to popup().
sendInfo(\'".$blah."\', \'".$test."\');

Related

Trimming whitespaces, tabs and newlines in php

When I sanitize the input fields or text area I face a problem. When someone gave spaces and submit the form, my script accepts the form. But I want not to accept fields until there is not written at least a single character. My code is as follows.
Html
<form action="" method="POST">
<textarea name='text'></textarea>
<input type='submit' name='submit'>
</form>
Php
if(isset($_POST['submit'])){
if(isset($_POST['text']) && !empty($_POST['text'])){
//do whatever but not accept white space
}
}
You can trim whatever you want, just by using
trim()
Which removes characters from both sides of a string.
Documentaion: http://php.net/manual/bg/function.trim.php
trim and preg_replace will do this easily
<?php
echo $text = " this is niklesh raut ";
echo "\n";
$text = preg_replace('/\s+/', ' ',$text);
echo trim($text);
?>
live demo : https://eval.in/818137
OUTPUT :
this is niklesh raut
this is niklesh raut
With new line and tab : https://eval.in/818138
You can either echo out your statement:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['text'])){
echo "Please enter a value.";
}
}
Or, add the required attribute to your input field.
<form action="" method="POST">
<textarea name='text' required></textarea>
<input type='submit' name='submit'>
</form>

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).

Rendering javascript code in php document

I'm a beginner to PHP and I have a quick question. Is it possible to have javscript code injected into a document through php?
For example, suppose I wanted to inject a button that called a function after a form is filled out:
<html>
<head>
<script type = text/javascript>
function func() {
...
}
</script>
</head>
<body>
<form action = 'welcome.php' method = 'post>
Name: <input type = 'text' name = 'fname' />
<input type = 'submit' value = 'submit' />
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type = button onclick = func />'
}
?>
</body>
</html>
Would this work? If not, why not?
Any help would be great
Will work fine - just remember to close your quoted strings :
<form action='welcome.php' method='post'> // add ' here
Name: <input type='text' name='fname' />
<input type='submit' value='submit' /> // removed a couple of spaces (not required)
</form>
<?php
if (isset($_POST['fname'])) {
echo '<input type="button" onclick="func" />'; // added some quotes and a semicolon
}
?>
I have removed the spaces between the attributes and the values in HTML from type = "something" to type="something" although I can't find the "official" specification on this. It seems that the spaces are perfectly valid ...I think its my personal preference to have no white space there .....
Try:
echo '<input type="button" onclick="' . $_POST['fname'] . '" />';
SAMPLE
If fname=doSomething then use:
echo '<input type="button" onclick="' . $_POST['fname'] . '()" />';
and your rendered HTML would be:
<input type="button" onclick="doSomething()" />
Then you'd just need your function somewhere:
<script>
function doSomething() { }
</script>
If your current page is welcome.php and you ran this code, you would press the Submit button and the page would reload and have your new button.
But the best way to see whether this works for you or not is to run it. Why don't you try that first?

Simple Php Echo

I am just starting to learn php, how would I initiate a echo statement after a submit button is pushed, or even a anchor tag.
Here is my code so far
form name="myform" method="get" actions="madlib01.php"
Name: <input type="text" name="name" /> <br />
<input type="submit" name="submit" />
form
<?php
$Name = $_GET['name'];
$hello .= "Hello $Name";
echo $hello //I would prefer the echo to happen after the submit button is hit
?>
the correct attribute for your form tag is "action", not "actions"
When the form is submitted, a new request is sent to the server (in your case, using GET).
So to do it all in one page:
form.php:
<form action="form.php" method="GET">
<input type="text" name="name"/>
<input type="submit">
</form>
<?PHP
if (! empty($_GET['name'])){
echo 'Hello, ' . $_GET['name'];
}
?>
You will first need to check if PHP has received your GET parameter using isset or array_key_exists:
if(isset($_GET['name']) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
}
or:
if(array_key_exists('name', $_GET) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
} else {
//example: default to something if nothing has been passed
echo "Hello Guest";
}
Also note, if you're submitting to the same page, you can omit the action attribute from your form tag altogether:
<form method="GET">
echo $hello
You've just gained an HTML-injection vulnerability. If someone sends your user to:
http://www.example.com/madlib01.php?name=<script>stealYourCookies()</script>
you've got problems.
Yes, this is a My First PHP Script. That doesn't make security optional. This is a mistake every tutorial makes: teaching bad practice from the start, treating correctness (and security, which is a subset of correctness) as an optional extra.
The result is that most PHP code out there is full of holes. But there's no need for yours to be! Every time you place a pure-text string into a surrounding HTML context, escape it properly:
echo htmlspecialchars($hello);
I tend to define a function with a shorter name than ‘htmlspecialchars’ to do that for me, as I'm lazy.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
$name= '';
if (isset($_REQUEST['name']))
$name= trim($_REQUEST['name']);
?>
...
<?php if ($name!=='') { ?>
<p> Hello, <?php h($name); ?>! </p>
<?php } ?>
<form method="get" action="madlib01.php">
<p>
<label for="namefield">Name:</label>
<input id="namefield" type="text" name="name" />
</p>
<p>
<input type="submit" />
</p>
</form>
Now if you say your name is Mister <script>, the page will greet you exactly as such, angle brackets and all, instead of trying to run JavaScript. This is the correct output and thus also secure.

Click on link, add text to textarea?

Let's say I have this javascript:
<script language="javascript" type="text/javascript">
function addtext() {
var newtext = document.myform.inputtext.value;
document.myform.description.value += newtext;
}
</script>
and I want to enable it so I can click on some html link that says "add text" and I want the text to be # . $username . (using PHP to insert the username). So when you click the "add text" link it'll put into the textarea #username. It is hard to visualize and I'm not sure where to put the text and PHP exactly. Thanks!
Textarea:
<form Name ="myform" action="<?$posted = $_POST['description'];
$object->post_tweet($posted); ?>" method="post">
<table align="left" border="0" cellspacing="1" cellpadding="5">
<tr>
<td class="2">
<textarea name='description' class="color" COLS=84 ROWS=2 type="text" id="eBann" name="bannerURL" maxlength="100" size="60" onKeyUp="toCount('eBann','sBann','{CHAR} characters left',140);"></textarea>
<br>
<span id="sBann" class="minitext">140 characters left.</span>
</td>
</tr>
</table><BR><BR><BR>
<p><input type='submit' value='Tweet!' /><input type='hidden' value='1' name='submitted' /> </p>
</form>
This is what I want to do with the link:
<a href="#" onclick="addtext("#'. $twit->user->screen_name .'"); return false>reply</a>'
This gives me an error though (I added the addtext function too).
EDIT: Got it! I had mistakes with ' and " haha wow, stupid mistake. Thanks everybody!
Ooh, tough one. This is a fantastic mish-mash of HTML, JavaScript, and PHP, isn't it?
<script language="javascript" type="text/javascript">
function addtext(text) {
document.myform.description.value += text;
}
</script>
...
<a href="#" onclick="addtext('#<?php echo htmlspecialchars(addslashes($userName)) ?>'); return false"
>reply</a>
Let's break that down: pretend $userName is "TeaCast". Then the HTML that will get sent to the browser after the <?php ?> part has executed would look like:
<a href="#" onclick="addtext('#TeaCast'); return false"
>reply</a>
Ah!
Additional notes:
The href="#" sets up a fake link that gives you the hand cursor but doesn't do anything.
The addslashes() in the PHP code puts a backslash before any quotes.
The htmlspecialchars() call ensures that a user name that contains weird characters like '<' or '&' won't mess up your page. Say some evil user who named themselves "<script>alert('haha')</script>" (yes, their user name is a snippet of HTML).
John's answer works fine, but another alternative you can do is store the username in the javascript, such as:
<script language="javascript" type="text/javascript">
var username = '<?php echo htmlspecialchars(addslashes($userName)) ?>';
function addtusername() {
document.myform.description.value += "#" + username;
}
</script>
...
reply
This way, you can use the variable username in the Javascript for other functions later, instead of using a bunch of php.

Categories