Static Page A has a form with an action submitting to a Authorization page B which is a dynamic page. After authorization, B will redirect to a callback url C which is passed to B by A.
Besides redirecting to page C, B also post some parameters indicated the auth states. uin is a most important parameter that will be used in the content of page C namely the scripts. The scripts need uin to send Ajax request later. Question is how can I pass uin to the static page C?
A quick and dirty idea I got is to wrap the static page C with a PHP file, and output the data in a hidden div for example:
<?php
$html = file_get_contents("callback.html")
$div = "<div stype='display:none' uin={$_POST['uin']}></div>"
//add this div to $html and print it, need a little more work to figure out how to do this
?>
Is there a better way of doing this , because this is sort of 'idiot' I think...
Your code: (with stype typo fixed)
$div = "<div style=\"display:none\" uin={$_POST['uin']}></div>";
Looking at this code, the biggest problem I can see with it is that you're outputting a $_POST value without doing any escaping on it.
This a potential security threat; consider what would happen if someone provided a form that posted to your site, with the uin value set to a string of HTML code, starting with > to close the div. Their code would appear in your site, exactly as if you'd put it there. With a careful bit of styling, they could use this make your site look and behave however they want. Not great.
You can fix that by using wrapping the $_POST variable in html_entities() so it is properly escaped when it is output to the site.
Or, in this case, since it is (or appears to be) a numeric ID value, you could simply cast it as an int to ensure that it contains no unwanted data, no matter what the actual post data contains:
$uin = (int)$_POST['uin'];
...and then use $uin in the output rather than the raw post data.
The second point I'd make is one of validity. uin is not a valid HTML attribute. It may work, but it's not valid. The correct standards-compliant way to do custom attributes in HTML is to use a data attribute, like so:
$div = "<div style=\"display:none\" data-uin={$uin}></div>";
... ie the names of all custom attributes should start with data-
This is recommended because it allows you to have custom attributes with the same name as real attributes without risking any problems. eg you could have data-style, without colliding with the real style attribute.
It also means that the HTML spec can have new attributes added to it without risking clashes with other people's code. eg if a future version of HTML includes a uin attribute that future browsers use to do something clever with the element, it would cause problems with your code. Those problems would not happen if you use data-uin. (okay, so uin is an unlikely name for a new standard HTML attribute, but the point stands)
Perhaps you should store parameters from page B in user session. Than on page C you can use these parameters (after calling session_start() before anything is outputted to the browser). Also, if you are using javascript, consider placing uin in javascript variable instead of html div. Something like <script type="text/javascript">var uin = 123; </script>.
You have an syntax errors in your php code you need to mask the quotes around your inline style and you missed to add some colons:
<?php
$html = file_get_contents("callback.html");
$div = "<div style=\"display:none\" uin={$_POST['uin']}></div>";
//add this div to $html and print it, need a little more work to figure out how to do this
echo($html); // print variable $html
echo($div); // print variable $div
?>
Related
I've recently thrown together a basic PHP webpage that lists information pulled from an MySQL table and displays it in various sorts. I'm wanting to allow the user to add a new item to the table, edit an item in the list and delete an item in the list without refreshing the page (Ajax).
This currently goes;
To add/edit an article you click on a link which prompts the popover ajax form, and fills it's contents (if editing) by performing the function setEdit(comment) as below;
<a class="popup-button" title="<?php echo $row['comment']; ?>" onclick="setEdit('<?php if($row['comment']){ echo $row['comment']; } else { echo "Enter comment here..."; } ?>');"><?php echo $row['listitem']; ?></a>
The setEdit() comment is as follows;
function setEdit(editcomment)
{
if(editcomment){ document.getElementById('help-us-comment').value=editcomment; }
}
Which is then, after submitting the ajax form, handled by the following php code;
if(isset($_POST['comment_text']))
$comment=$_POST['comment_text'];
$sql = "INSERT INTO table SET
comment='$comment'";
Problem: I'm having constant issues trying to get the database contents through 1, 2, 3 without falling over at a new line, single or double quote. I've tried endless combinations of replacing tags, htmlspecialchars and nl2br with no half successes - where it's got to the point that it's so convoluted and encoded/decoded now that I'm assuming that there is a far simpler and obvious way that I'm missing.
The main problem happens when trying to load the data into the form, typically having either the form fall over and refuse to populate at all (typically by the a link becoming broken by the data extracted i.e. single quote or new line) or the form being populated with special characters instead of plain text to edit.
I've tried to go into as much detail as possible, but if any more is needed I'm happy to provide. Also apologies if this is an obvious fix/mistake, and I'm being an idiot.
You have two problems here: storing and displaying.
To display you should look in to htmlentities that makes it safe HTML (it does all the quotes replacing, html encoding, etc. for you) so that your string to be safe to be displayed as plain text, or as inputs' values.
To store the data, you should sanitize your queries. You could use mysqli and bind parameters, or use mysql_real_escape_string to escape your input manually.
Otherwise, say hi to Bobby Tables ;)
The following script has been created to test if the value of a db field has changed and if so then reload the page and if not, alert the user that the change has not happened.
The alert is just to see what is being returned by the .post function.
The auto_refresh works fine as i need it to check every 5 seconds, when the if() condition is set to '==' the page alert shows and if it is set to '!=' the page continually reloads.
jQuery.post is getting the db field data but it doesn't seem to be able to compare the 2 values correctly.
any help would be greatly appreciated, thanks
var auto_refresh = setInterval(function(){
$.post("/index.php/listen", function(data) {
if($('#slide').html() != data)
{
window.location.reload()
}
else
{
alert('its the same'+ data);
}
});
}, 5000);
EDITED
Rather than trying to parse raw data, why not pass HTML from the $.post() like:
<p>4</p>
Then the jQuery inserts the the replaces the p tag with the new version from the $.post()
because the html is passed on there is no white space and the comparison can be made correctly.
I don't think it is very safe to compare the new value with an html. Some browsers might add spaces or unwanted chars. I'd try to save the old value in an input of type hidden and use the .val() or, event better, in a variable. It depends of your scenario.
If $('#slide').html() == data
then that means that the conditional failed, it was not equal, so it showed the alert.
The problem is that the data variable might come back with a few extra white spaces. If I were you, I'd try to parse a small section of the data variable, and a small section of the html in slider and compare those values.
Like if slider has something within a p tag or an input value, compare it to the data to see if it has that same value returned in that p tag or input value, then replace all the whitespaces with an empty string just to be safe.
Btw, try not to use alerts since you can't really know for sure if there is an extra whitespace. Try to use something like "debugger" if using IE with visual studios, or console.log when using chrome or firefox.
You are comparing two html strings: one is serialized from the DOM, and another is from a server response.
There's no guarantee that the two strings will ever be the same! Think about it: the same rendered html can have many string differences. E.g. click and click are both the same HTML, but different strings.
You can take two different approaches here:
You can create some kind of canonicalization routine that guarantees that two html fragments you consider "the same" will have the same string form. Run both html fragments through this routine, then compare.
You can manage versions more explicitly.
Include some kind of version indicator:
You can use the ETAG header (which means you can take advantage of http caching mechanisms).
You can include some kind of version number in the html itself (maybe in a data-version attribute), and compare those.
You can keep the html string from your server separately and compare against that.
I have some multi line text saved in MySql database (VARCHAR 255). When i load it, and process it using standard php function "nl2br", it echoes fine (multi line). But, when i load multi line text from database, make it "nl2br" and then send it to javascript (so it gets displayed in textarea), it won't be displayed! What's wrong?
echo "<SCRIPT>FillElements('".$subject."','".$text."');</SCRIPT>";
P.S.
FillElements function:
function FillElements(Sub,Txt)
{
document.getElementById('txtSubject').value=Sub;
document.getElementById('txtMessage').value=Txt;
}
textareas don't actually store the contents in an attribute like value in the same manner as input elements. They actually store the contents in in between the <textarea> and </textarea> tags. Meaning that the contents is actually treated as CDATA in the document.
<textarea>
This is my Content
</textarea>
Produces a text area with "This is my Content" as the contents.
The implication of this is that you cannot use the code you have to alter the contents of a textarea. You have to alter the innerHTML property of the textarea. I have set up a simple example here:
http://jsfiddle.net/wFZWQ/
As an aside, since you are populating the fields using PHP on the creation of the page, why not merely fill the data in the HTML markup, this seems like a long way round to do it.
Also, since you don't appear to be using it, have you seen [jQuery][1] it abstracts alot of things out, so instead of typing document.getElementById("the_id") to get an element you can use CSS selectors and merely write $("#the_id") to get the same element. You also get a load of useful functions that make writing javascript mucxh easier.
[1]: http://jquery.com jQuery
Newline tags (<br />) don't cause actual new lines in <textarea>.
You can pass the "real" newlines (\n) to your <textarea>, though.
I created a fiddle for that.
EDIT: For the updated FillElements code:
$subject = "String\nWith\nMultiple\nLines";
printf('<script type="text/javascript">FillElements(%s)</script>',
json_encode($subject)
);
My guess is that your HTML source code looks like this:
<script>FillElements("foo","foo
bar
baz");<script>
Correct?
In JavaScript, strings cannot span multiple lines...
I have a form where a user types paragraphs into a text area and then it takes them to another page after they submit. How can I pass whatever they typed to the page after they submit? The text area might have linebreaks and if I use a query string to pass the data, it gives me an error. This is my current code to pass the field:
<?php
if(isset($_POST['form']))
{
$title = $_POST['title'];
$body = $_POST['body'];
header("SubmitForm.php?title=$title&body=$body");
?>
<html>
...html form...
It doesn't work when the text area has line breaks in it.
I would suggest installing a wysiwyg editor to make this easier for you, but i assume that would add some time for the learning curve.
The simplest tips I can give you is to set a CSS attribute for your textarea: white-space:pre so that when it gets submitted, all line breaks get sent as well.
On your server side, you would need to use the nl2br() function, so that when it gets saved on your DB or wherever you store them, all line breaks are converted to HTML breaks.
For your additional reference, I had a similar question like this last year.
You really shouldn't be putting anything that long in a query string in the first place. Look into using sessions to store data across pages instead.
(This is assuming I understood the question right)
urlencode the data in order to pass it via query string.
I'm playing around with Symfony and have encountered a road block.
I created a model "CmsPage" which has a field called "content" which is stored as a clob (this is specific to doctrine I believe). When I created the app I set "--escaping-strategy=on" so if I enter any html when editing a CmsPage that gets encoded with html entities or something along those lines. I would like to allow html in this field and a quick googling hasn't helped much. Maybe I'm searching for the wrong terms.
Anywho I would like to disable character escaping for this field and possibly only allow a small selection of html tags. What is the correct way to do this in Symfony?
You can use http://htmlpurifier.org/ It is great tool for your needs.
Here is small configuration for htmlpurifier. These rules perfect match with TinyMce editor.
$purifier = new HTMLPurifier();
$purfier_config = HTMLPurifier_Config::createDefault();
$purfier_config->set('HTML.DefinitionID', 'User Content Filter');
$purfier_config->set('HTML.DefinitionRev', 1);
// these are allowed html tags, means white list
$purfier_config->set('HTML.Allowed', 'a,strong,em,p,span,img,li,ul,ol,sup,sub,small,big,code,blockquote,h1,h2,h3,h4,h5');
// these are allowed html attributes, coool!
$purfier_config->set('HTML.AllowedAttributes', 'a.href,a.title,span.style,span.class,span.id,p.style,img.src,img.style,img.alt,img.title,img.width,img.height');
// auto link given url string
$purfier_config->set('AutoFormat.Linkify', true);
// auto format \r\n lines
$purfier_config->set('AutoFormat.AutoParagraph', true);
// clean empty tags
$purfier_config->set('AutoFormat.RemoveEmpty', true);
// cache dir, just for symfony of course, you can change to another path
$purfier_config->set('Cache.SerializerPath', sfConfig::get('sf_cache_dir'));
// translation type,
$purfier_config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
// allow youtube videos
$purfier_config->set('Filter.YouTube', true);
$purfier_config->set('HTML.TidyLevel', 'heavy');
// now clean your data
$clean_nice_html_data = $purifier->purify($user_input_data, $purfier_config);
Now you can insert data to databse with html tags, and you don't need to escape your data, because, htmlpurifier clean nasty, dangerous data for you, and only accept your allowed tags and attributes.
I hope it helps.
From http://www.librosweb.es/symfony_1_1_en/capitulo7/output_escaping.html
Every template has access to an $sf_data variable, which is a container object referencing all the escaped variables.
[skipped]
$sf_data also gives you access to the unescaped, or raw, data. This is useful when a variable stores HTML code meant to be interpreted by the browser, provided that you trust this variable. Call the getRaw() method when you need to output the raw data.
echo $sf_data->getRaw('test');
=> alert(document.cookie)You will have to access raw data each time you need variables containing HTML to be really interpreted as HTML. You can now understand why the default layout uses $sf_data->getRaw('sf_content') to include the template, rather than a simpler $sf_content, which breaks when output escaping is activated.