PHP - Htmlspecialchars Vs. Htmlentities
What do most people prefer to use? htmlspecialchars or htmlentities
Similar TutorialsHello Guys ... i am new here and i am also new in php i selfstudy html css and js and bootstrap for front-end and for back-back php & mysql & PDO & OOP and i will soon start mvc then laravel and i am trying to secure my input field and i do not want any attacks or sql injects and i see people user filter_var and htmlentities and htmlspecialchars and each one has diffrent opinion can some one help me and tell me what is the best for securing input which all values will store in database thanks <3
Does anyone have an example of when htmlentities() would be used over htmlspecialchars()? I'm getting this error and not sure my fix. <b>Warning</b>: htmlspecialchars() expects parameter 1 to be string, array given in <b>/home/xtremer/public_html/efedmanager/processes/polls.php</b> on line <b>13</b><br /> $answer = explode(',', $_POST['answersList']); $answer = htmlspecialchars($answer); Hi, should i use htmlspecialchars() when i write in mysql or when i read from mysql, and should i use another function for safety ? I need to put this inside of a p tag so I can change some properties but everything I've tried doesn't work and just shows nothing.
I've tried this:
printf('<p style="text-align: left; width: 500px;">', htmlspecialchars($fetch['shout'], ENT_QUOTES, 'UTF-8'), '</p>');This is what I need to be wrapped in p tags: htmlspecialchars($fetch['shout'], ENT_QUOTES, 'UTF-8');EDIT: I've noticed the code below works but when I style it inside of the tag the text won't show, should I include a CSS file on the PHP file? echo "<p>".htmlspecialchars($fetch['shout'])."</p>\n";EDIT: I just needed to create the CSS for the p tags in the index and it worked perfectly fine. Sorry for the pointless thread. Edited by Alanay, 18 December 2014 - 09:14 AM. Hello and thanks in advance for any help. Overview: Im tyring to pull data from a XML api using simpleXML. I have ran into a problem with special characters and entities that simpleXML does not accept. IE " " Ive tried all the solutions i could find to no avail. SimpleXML gives me this error. parser error : Entity 'nbsp' not defined in Here is my code. Code: [Select] $feed = simplexml_load_file('URL TO API FEED'); $feed = html_entity_decode($feed); $feed = str_ireplace(array('<','>','&','\'','"'),array('<','>','&',''','"'),$feed); echo 'Game Title: ' .$feed->game. '</br>'; echo 'Ponts Earned: ' .$feed->gamerscore. '</br>'; echo 'Total Achievements: ' .$feed->totalachievements. '</br>'; foreach($feed->achievements->achievement as $ach) { $output = htmlentities($feed->title, ENT_QUOTES, "UTF-8"); echo $output; if( !empty($ach->unlockedartwork)){ echo '<img src=' .$ach->unlockedartwork. '></img></br>'; }else { echo '<img src=' .$ach->artwork. '></img></br>'; } } Here is the code im trying to retrieve. Code: [Select] <achievement id="40"> <title>Have Gun Will Travel </title> <artwork>http://</artwork> <gamerscore>20</gamerscore> <unlocked>true</unlocked> <unlockdate>7/4/2010</unlockdate> </achievement> which one is necessary while protecting form field Edited July 28, 2019 by mahendaI don't really understand what htmlentities() does and when to use it?! The manual says this... <?php $str = "A 'quote' is <b>bold</b>"; // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str); // Outputs: A &#039;quote&#039; is <b>bold</b> echo htmlentities($str, ENT_QUOTES); ?> 1.) Isn't there a way to print this... Code: [Select] $str = "A 'quote' is <b>bold</b>"; ...as this... Quote A 'quote' is <b>bold</b> That is, WYSIWYG. 2.) When and why would you want this displayed... Quote A 'quote' is <b>bold</b> I am trying to make my code more secure, and I was told to use something like this on all code that comes from the User and needs to be output, but I'm a little lost here... echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . nl2br(htmlentities($username)) . '</strong> </a>'; Debbie Think i've got my self a little confused here. htmlentities This function is designed to try and keep clients safe. If the comment the user inputs can only ever be seen by him or her, then in theory is there no need to use htmlentities as any dodgy script would only affect them. Is this correct thinking? Hi all i was just trying to test out what the effect is of htmlentities() and htmlspecialchars() with an without ENT_QUOTES, but it looks like it's not working as expected. I made a small script to compare the 2 the only thing happends that javascript isn't executed, but i though it would convert special characters into even more special ones I am running on xampp btw if that helps $plain_input = "I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script>"; $plain_input2 = htmlentities($plain_input); $plain_input2_ent = htmlentities($plain_input,ENT_QUOTES); echo '<b>htmlentities: </b>'.$plain_input2.'<br />'; echo '<b>htmlentities + entquotes: </b>'.$plain_input2_ent.'<br />'; echo '<hr /><br />'; $plain_input3 = htmlspecialchars($plain_input); $plain_input3_ent = htmlspecialchars($plain_input,ENT_QUOTES); echo '<b>htmlspecialchars:</b> '.$plain_input3.'<br />'; echo '<b>htmlspecialchars + entquotes:</b> '.$plain_input3_ent.'<br />'; echo '<hr /><br />'; this just outputs: Code: [Select] htmlentities: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> htmlentities + entquotes: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> htmlspecialchars: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> htmlspecialchars + entquotes: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> Wondering about htmlentities() as I have a rich text editor implemented on my website, how would I correctly use htmlentities() as I still want the data which was put into the rich text editor to correctly show, sorry for me being a bit vague, it is late and im tired but hope someone can shine some light on this for me Now, I'm trying to figure out some security factors of a website with a login etc. Would I need to add and strip slashes if I'm using htmlentities on anything that the user enters? I can't seem to get htmlentities working in the code below... echo "<textarea id=\"question" . $questionNo . " name=\"qaArray[\"answerText\"]\" cols=\"60\" rows=\"2\">" . (isset($questionNo) ? "htmlentities($qaArray[\"answerText\"], ENT_QUOTES" : "") . "</textarea>"; I tried using the default single quotes around answerText but that doesn't, nor do my escaped double quotes. What is wrong? Thanks, Debbie I have let say Thai language and inserted into database Code: [Select] <b>บริษัท เอส.เค.ฟู้ดส์ (ประเทศไทย) จำกัด (มหาชน) เป็นผู้นำเข้า-ส่งออกปลาทูน่าบรรจุกระป๋อง ต้องการรับสมัครพนักงานเพื่อรองรับการขยายกิจการ</b> and i retrieve it using this nl2br(htmlentities($array['message'])) the result will completely messed up as the thai language will be converted either. if i ignore the htmlentities then i will have that message in bold how can i achieve the result exactly the same like what has been written (message in thai language with that <b> html tag)?? thanks in advance When sending data via $_POST for example, I've seen the data get filtered with both mysql_real_escape_string or htmlspecialchars When should you use one or the other? Not sure how to debug this. I have the following error that is ONLY happening when our site has a PCI scan running : - ERRNO: 2 TEXT: htmlspecialchars() expects parameter 1 to be string, array given LOCATION: /home/bttorj45/public_html/smarty_templates_c/dbbe565f1731d4158472b66b75c85442498e81b9_0.file.top_menu_bar.tpl.php, line 42, at April 11, 2020, 5:05 pm Showing backtrace: htmlspecialchars(Array[1], "3", "UTF-8", true) # line 42, file: /home/siteaddress/public_html/smarty_templates_c/dbbe565f1731d4158472b66b75c85442498e81b9_0.file.top_menu_bar.tpl.php content_5e83087341d089_14126332(Object:Smarty_Internal_Template) # line 123, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_template_resource_base.php Smarty_Template_Resource_Base.getRenderedTemplateCode(Object:Smarty_Internal_Template) # line 114, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_template_compiled.php Smarty_Template_Compiled.render(Object:Smarty_Internal_Template) # line 216, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_template.php Smarty_Internal_Template.render() # line 385, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_template.php Smarty_Internal_Template._subTemplateRender("file:page_elements/top_menu_bar.tpl", null, null, "0", "120", Array[0], "0", false) # line 56, file: /home/siteaddress/public_html/smarty_templates_c/0e4c1495f7a25cef1d85553f951690964f702a5a_0.file.error404.tpl.php content_5e4ffba4a49c66_36622821(Object:Smarty_Internal_Template) # line 123, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_template_resource_base.php Smarty_Template_Resource_Base.getRenderedTemplateCode(Object:Smarty_Internal_Template) # line 114, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_template_compiled.php Smarty_Template_Compiled.render(Object:Smarty_Internal_Template) # line 216, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_template.php Smarty_Internal_Template.render(false, "1") # line 232, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_templatebase.php Smarty_Internal_TemplateBase._execute(Object:Smarty_Internal_Template, null, null, null, "1") # line 134, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_templatebase.php Smarty_Internal_TemplateBase.display("pages/error404.tpl") # line 65, file: /home/siteaddress/public_html/errors/404.php include("/home/siteaddress/public_html/errors/404.php") # line 34, file: /home/siteaddress/public_html/smarty_plugins/function.load_product.php Product.init("api") # line 5, file: /home/siteaddress/public_html/smarty_plugins/function.load_product.php smarty_function_load_product(Array[2], Object:Smarty_Internal_Template) # line 39, file: /home/siteaddress/public_html/smarty_templates_c/53725e8a2fc4b6c7c0c42e801dab2741a0994a8e_0.file.product.tpl.php content_5e579e9761f086_59385269(Object:Smarty_Internal_Template) # line 123, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_template_resource_base.php Smarty_Template_Resource_Base.getRenderedTemplateCode(Object:Smarty_Internal_Template) # line 114, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_template_compiled.php Smarty_Template_Compiled.render(Object:Smarty_Internal_Template) # line 216, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_template.php Smarty_Internal_Template.render(false, "1") # line 232, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_templatebase.php Smarty_Internal_TemplateBase._execute(Object:Smarty_Internal_Template, null, null, null, "1") # line 134, file: /home/siteaddress/public_html/include/smarty/sysplugins/smarty_internal_templatebase.php Smarty_Internal_TemplateBase.display("pages/product.tpl") # line 85, file: /home/siteaddress/public_html/dirs.php I ***think*** the scan must be inputting something in the search box to cause this (I'm awaiting info from Security Metrics with regard to this). {load_chat assign="chat"} {if $chat->mChat} <script type="text/javascript" id="763333b0f312f025d780a8f4451bf6f3" src="https://www.siteaddress.com/online-support/script.php?id=763333b0f312f025d780a8f4451bf6f3"></script> {/if} {if !$chat->mChat && $settings->mSettings[13]} <script type="text/javascript" id="aaa07817d7cd2a7dce9e0ffac6286dbb" src="https://www.siteaddress.com/online-support/script.php?id=aaa07817d7cd2a7dce9e0ffac6286dbb"></script> {/if} <div id="menu_switch"><i class="fa fa-bars fa toggler"></i></div> <form id="product_search" method="get" action="{$smarty.const.SITE_ROOT}/searchresults/"> <input type="text" name="search" placeholder=" Product Search" style="font-family: FontAwesome, Arial; font-style: normal; font-size:18px;" {if isset($smarty.request.search) && $settings->mSettings[107]}value="{$smarty.request.search|escape:'htmlall'}"{/if} /><button type="submit" class="button"><i class="fa fa-search" aria-hidden="true"></i> <i class="fa fa-caret-right" aria-hidden="true"></i></button> </form> <form id="code_search" method="post" action="{$smarty.const.SITE_ROOT}/cart/quickadd.php"> <input type="text" name="code" maxlength="14" placeholder=" Product Code" style="font-family: FontAwesome, Arial; font-style: normal; font-size:18px;" /><button type="submit" name="submit" class="orange"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Quick Add <i class="fa fa-caret-right" aria-hidden="true"></i></button> </form> {if !isset($hidecart) && isset($cartsmall) && $cartsmall->mCart.sub > 0} <p id="view_cart"><a class="button orange" href="{$smarty.const.SITE_ROOT}/cart/"><span class="hidden-xs hidden-sm"><i class="fa fa-shopping-cart" aria-hidden="true"></i> View Cart </span>£{$cartsmall->mCart.sub} <i class="fa fa-caret-right" aria-hidden="true"></i></a></p> {/if} <script> $('.toggler').click(function() { $(this).toggleClass("fa-bars fa-times"); }); </script>
function.load_search.php :-
<?php function smarty_function_load_search($params, $smarty) { $search = new Search(); $search->init(); $smarty->assign($params['assign'], $search); } class Search { // public fields public $mSearchString; public $mSearchArray; public $mProducts; public $mProductCount; // private fields private $mDoSettings; private $mDoCatalogue; function __construct() { require_once FILE_ROOT . '/data_objects/do_settings.php'; $this->mDoSettings = new DoSettings(); require_once FILE_ROOT . '/data_objects/do_catalogue.php'; $this->mDoCatalogue = new DoCatalogue(); if (isset($_REQUEST['search']) && strlen(trim($_REQUEST['search']))>0 ) { $this->mSearchString = trim(stripslashes($_REQUEST['search'])); $this->mSearchArray = explode(" ", $this->mSearchString); } else { header ("Location: /emptysearch/"); die (); } } public function init() { $this->mProducts = $this->mDoCatalogue->SearchProducts($this->mSearchArray); $this->mProductCount = count($this->mProducts); for ($i = 0; $i < count($this->mProducts); $i++) { $this->mProducts[$i]['price_inc'] = number_format($this->mProducts[$i]['price'] * (($this->mDoSettings->GetSetting(1) / 100) + 1), 2, ".", ","); } } } ?>
do_catalogue.php :-
public function SearchProducts($search) { $fields = array("code", "title", "keywords"); $query_string = "SELECT p.code, p.title, p.cattext, p.price, p.img, p.url, p.available, p.due, p.special, p.newproduct, p.discontinued, c.name, c.menulinktext FROM " . $this->mProductTable . " p " . "JOIN categories c ON p.category = c.id " . "WHERE (("; for ($f = 0; $f < count($fields); $f++) { if ($f != 0) { $query_string .= ") OR ("; } for ($s = 0; $s < count($search); $s++) { if ($s != 0) { $query_string .= " AND "; } $query_string .= "p." . $fields[$f] . " LIKE '%" . $this->mDoQuery->dbManager->DbEscape($search[$s]) . "%'"; } } $query_string .= ")) AND active=1 AND live=1 " . "ORDER BY p.rating ASC"; return $this->mDoQuery->dbManager->DbGetAll($query_string); }
Any idea's how to fix it? I can't replicate it with a specific issue as I don't know what the scan is doing to cause this! Thanks HI all, Please advice me 1. When to use htmlspecialchars() or mysql_real_escape_string? 2. what is the diffrent? Thank you for your help. Hello dears, I've tried to use htmlspecialchars or htmlentities but both no longer work ! Example1 : Code: [Select] <?php $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); echo $new; ?> Output should <a href='test'>Test</a> Code: [Select] <?php $str = "A 'quote' is <b>bold</b>"; echo htmlentities($str); ?> Output should A 'quote' is <b>bold</b> But it isn't working ? what is wrong ? So, If I want to store something like: Code: [Select] Hello<br /> <b>This is a sentence </b> I would need to use htmlentities() So I could output the HTML after it's stored in the database safely? |