problems displaying html characters - php

I'm building a sign-in/up form and I have problems displaying HTML characters. When a user signs up, I use this function for the sign-up data and then insert it into the database.
function clearInput( $string) {
$string = stripslashes($string);
return htmlentities($string);
}
When a user signs-up with the name <p>hello</p> it will look like this in the db: "&lt;p&gt;hello&lt;/p&gt"<br>.
If the user signs-in and I var_dump the name that is saved in the session it looks like this <br>'<p>hello</p>' in the browser.
If I echo this <p>hello</p> manually in the document, it displays this <p>hello\</p> as it should normally.
Does someone know how it shows <p>hello</p> when I var_dump the session name?

I don't get your question but it will help you.
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars_decode($str);
This is some <b>bold</b> text.
$str = '<a href="https://www.test.com">test.com</a>';
echo html_entity_decode($str);
test.com

Related

Style text with HTML tags

I have a string saved in a database as <b>hello</b>
When I get the string from the database using a query, the text isn't bold (which should be caused by the <b> tags). Instead, it simply displays as 'hello'.
How can I apply the html tags to the text ?
<?php
$stmt = $con->prepare("SELECT * FROM posts");
$stmt->execute();
$text = $row['text'];
echo $text;
?>
I have tried using htmlentities as well as html_entity_decode, but the result is the same.
I'm unable to use html tags in the output ($text = "<b>" . $row['text'] . "</b>";) as I'm getting multiple strings from the database, each with different html tags.
#Fred-ii- Hi Fred, just to let you know that I tried htmlspecialchars_decode(stripslashes($row['text'])) again and out of the blue, it strangely worked. – The Codese
As stated in comments:
htmlspecialchars_decode(stripslashes($row['text']))
is what should have been used.

How to get a url from a database

So I have three pages one that is the index page. One that writes the data from a form inside the index page to the database. And one that gets data from the database and echos out a html table with the data inside.
Currently if you write a link in the form. It will just come out as text. I would like the whole link to be like [link].
so say if I wrote this onto the form:
Look at this: www.google.com or Look at this: https://www.google.com
it would come out like this in html
Look at this: www.google.com
How could I go about doing this?
Okay so the html is:
<form class="wide" action="Write-to.php" method="post">
<input class="wide" autocomplete="off" name="txt" type="text" id="usermsg" style="font-size:2.4vw;" value="" />
</form>
in which the user would write:
"Look at this: www.google.com or Look at this: https://www.google.com"
This would then get sent to the database through Write-to.php.
$sql="INSERT INTO social (comunicate)
VALUES
('$_POST[txt]')";
}
this then gets written back into the database:
$result = mysqli_query($con,"(select * from social order by id desc limit {$limit_amt}) order by id asc");
while($row = mysqli_fetch_array($result))
{
echo "<tr div id='".$i."' class='border_bottom'>";
echo "<th scope='col'>";
echo "<span class='text'>".htmlspecialchars($row['comunicate'])."</span><br />";
echo "</th>";
echo "</tr>";
}
Just try:
echo(''.$your_url_variable.'');
Update:
The OP really wanted to detect url's in a string. One possible solution could be filter it using a regular expression. This code could help:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "{$url[0]} ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
Source: http://css-tricks.com/snippets/php/find-urls-in-text-make-links/
There are quite a few things you need to worry about when displaying user supplied (tainted) data.
You must ensure that all the data is sanitised -- never ever just echo the content, look into htmspecialchars and FILTER_VALIDATE_URL for example:
function validateUrl($url) {
return filter_var($url, FILTER_VALIDATE_URL);
}
What you are attempting to do is convert a string into a link, for example you can write a function like this:
function makeClickable($link) {
$link = htmlspecialchars($link);
return sprintf('%s', $link, $link);
}
You can use string concatenation as well, but I wouldn't do that in my view code. Just personal preference.
Take a look at the urlencode function, it will certainly come in handy.
I would also recommend you read about cross site scripting
Please note that I am not making any implementation recommendations, my aim is just to show you some contrived code samples that demonstrate making a string "clickable".
Update:
If you would like to make links clickable within text, refer to the following questions:
Best way to make links clickable in block of text
Replace URLs in text with HTML links
save the hyperlink in db and retrieve as a string by sql query
like:
select link from table_name where index = i
and save link as: whaatever here
and print it
Use this
echo '' . $res['url'] . '';

Get content in faster way from url using php

I am using php, I want to get the content from url in faster way.
Here is a code which I use.
Code:(1)
<?php
$content = file_get_contents('http://www.filehippo.com');
echo $content;
?>
Here is many other method to read files like fopen(), readfile() etc. But I think file_get_contents() is faster than these method.
In my above code when you execute it you see that it give every thing from this website even images and ads. I want to get only plan html text no css-style, images and ads. How can I get this.
See this to understand.
CODE:(2)
<?php
$content = file_get_contents('http://www.filehippo.com');
// do something to remove css-style, images and ads.
// return the plain html text in $mod_content.
echo $mod_content;
?>
If I do that like above then I am going in wrong way, because I already get the full content in variable $content and then modify it.
Can here is any function method or anything else which get the directly plain html text from url.
Below code is written only to understanding, this is not the original php code.
IDEAL CODE:(3);
<?php
$plain_content = get_plain_html('http://www.filehippo.com');
echo $plain_content; // no css-style, images and ads.
?>
If I can get this function it will be much faster than others. Can it is possible.
Thanks.
Try this.
$content = file_get_contents('http://www.filehippo.com');
$this->html = $content;
$this->process();
function process(){
// header
$this->_replace('/.*<head>/ism', "<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE html PUBLIC '-//WAPFORUM//DTD XHTML Mobile 1.0//EN' 'http://www.wapforum.org/DTD/xhtml-mobile10.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head>");
// title
$this->_replace('/<head>.*?(<title>.*<\/title>).*?<\/head>/ism', '<head>$1</head>');
// strip out divs with little content
$this->_stripContentlessDivs();
// divs/p
$this->_replace('/<div[^>]*>/ism', '') ;
$this->_replace('/<\/div>/ism','<br/><br/>');
$this->_replace('/<p[^>]*>/ism','');
$this->_replace('/<\/p>/ism', '<br/>') ;
// h tags
$this->_replace('/<h[1-5][^>]*>(.*?)<\/h[1-5]>/ism', '<br/><b>$1</b><br/><br/>') ;
// remove align/height/width/style/rel/id/class tags
$this->_replace('/\salign=(\'?\"?).*?\\1/ism','');
$this->_replace('/\sheight=(\'?\"?).*?\\1/ism','');
$this->_replace('/\swidth=(\'?\"?).*?\\1/ism','');
$this->_replace('/\sstyle=(\'?\"?).*?\\1/ism','');
$this->_replace('/\srel=(\'?\"?).*?\\1/ism','');
$this->_replace('/\sid=(\'?\"?).*?\\1/ism','');
$this->_replace('/\sclass=(\'?\"?).*?\\1/ism','');
// remove coments
$this->_replace('/<\!--.*?-->/ism','');
// remove script/style
$this->_replace('/<script[^>]*>.*?\/script>/ism','');
$this->_replace('/<style[^>]*>.*?\/style>/ism','');
// multiple \n
$this->_replace('/\n{2,}/ism','');
// remove multiple <br/>
$this->_replace('/(<br\s?\/?>){2}/ism','<br/>');
$this->_replace('/(<br\s?\/?>\s*){3,}/ism','<br/><br/>');
//tables
$this->_replace('/<table[^>]*>/ism', '');
$this->_replace('/<\/table>/ism', '<br/>');
$this->_replace('/<(tr|td|th)[^>]*>/ism', '');
$this->_replace('/<\/(tr|td|th)[^>]*>/ism', '<br/>');
// wrap and close
}
private function _replace($pattern, $replacement, $limit=-1){
$this->html = preg_replace($pattern, $replacement, $this->html, $limit);
}
for more - https://code.google.com/p/phpmobilizer/
you can use regular expression to delete css-script's tags and image's tags, just replace those codes with blank space
preg_replace($pattern, $replacement, $string);
for more detail of function go here: http://php.net/manual/en/function.preg-replace.php

Having trouble passing text from MySQL to a Javascript function using PHP

So here's the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.
At some point I want to pass this data into a javascript function called foo.
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{$someText}')\">";
If the data in $someText has line breaks in it like:
Line 1
Line 2
Line 3
The javascript breaks because the html output is
<img src=someimage.gif onclick="foo('line1
line2
line3')">
So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?
===========================================================================================
After using json like this:
echo "<img src=someimage.gif onclick=\"foo($newData)\">";
It is outputting HTML like this:
onclick="foo("line 1<br \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">
json_encode() is the way to go:
$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick=\"foo($safe)\">";
You can see a demo here: http://codepad.org/TK45YErZ
If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";
You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...
Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";

Preserve Line Breaks From TextArea

I'm using a textarea to enable users to input comments. However, if the users enters new lines, the new lines don't appear when they are outputted. Is there any way to make the line breaks stay.
Any idea how do preserve the line breaks?
Two solutions for this:
PHP function nl2br():
e.g.,
echo nl2br("This\r\nis\n\ra\nstring\r");
// will output
This<br />
is<br />
a<br />
string<br />
Wrap the input in <pre></pre> tags.
See: W3C Wiki - HTML/Elements/pre
Here is what I use
$textToOutput = nl2br(htmlentities($text, ENT_QUOTES, 'UTF-8'));
$text is the text that needs to be displayed
$textToOutput is the returned text from nl2br and htmlentities so it can be safety displayed in the html context.
ENT_QUOTES will convert both double and single quotes, so you'll have no trouble with those.
Got my own answer: Using this function from the data from the textarea solves the problem:
function mynl2br($text) {
return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />'));
}
More here: http://php.net/nl2br
i am using this two method steps for preserve same text which is in textarea to store in mysql
and at a getting time i can also simply displaying plain text.....
step 1:
$status=$_POST['status'];<br/>
$textToStore = nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8'));
In query enter $textToStore....
step 2:
write code for select query...and direct echo values....
It works
This works:
function getBreakText($t) {
return strtr($t, array('\\r\\n' => '<br>', '\\r' => '<br>', '\\n' => '<br>'));
}
function breakit($t) {
return nl2br(htmlentities($t, ENT_QUOTES, 'UTF-8'));
}
this may help you
pass the textarea wal
why make is sooooo hard people when it can be soooo easy :)
//here is the pull from the form
$your_form_text = $_POST['your_form_text'];
//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);
//email away
$message = "Comments: $your_form_text";
mail("destination_email#whatever.com", "Website Form Submission", $message, $headers);
you will obviously need headers and likely have more fields, but this is your textarea take care of

Categories