PHP doesn't recognise symbol ' - php

Sorry to ask this question, Im sure this question has been asked, but because I dont know the name of this symbol ' I cant really search.
The problem, I have a mysql database with text in it those text might have something like this (Hi I've no idea how to fix this). Once I query that text using php and echo on html, it display this.
Hi I�ve no idea how to fix this
Code:
$sql = mysqli_query($connection,"SELECT Something FROM something WHERE ID = '1';");
$row = mysqli_fetch_object($sql);
$description = $row->DESCRIPTION;
<p style="margin-top: 3%">
<?php echo$description?>
</p>

Always try to set MySQL encoding to UTF-8 as a first step. It will solve most of the issue.
At PHP end you can do like this:-
mysqli_set_charset($connection, "utf8")
If above not used then
Either You have to use htmlentities()
<?php echo htmlentities($description);?>
Or you have to use htmlspecialchars()
<?php echo htmlspecialchars($description, ENT_QUOTES);?>

Take a look at
mysqli_real_escape_string
It should help you with your issue and also improve security of your script (SQL injections).
htmlentities() should also help.
Edit: As mentioned in the comments: Instead of mysqli_real_escape_string, it is actually even more secure to use prepared statements.

Related

htmlentities are breaking hyperlinks

I am trying to do some htmlentities. However, the hyperlinks are now broken due to them being converted to the html codes, wanting to do this as for some stupid reason the university has given us all the same password for the servers.
Last year I almost failed as someone went onto my server and filled with the javascript and css hacks, so this will prevent it, however it's not much use if the hyperlink won't work, so how do I prevent this? Here's the code I have so far for this specific area:
$sub = substr($row['content'],0,300).'.......... See full article';
echo htmlentities($sub,ENT_QUOTES,"UTF-8");
If anyone can help, it's much appreciated, thanks.
I think you're applying htmlentities() on too much of your output. Just do it like this:
<?php echo htmlentities(substr($row['content'],0,300)).
'…See full article'; ?>
Don't apply htmlentities over the whole link, but on the values you actually want to escape, like this
$sub = htmlentities(substr($row['content'],0,300), ENT_QUOTES, 'UTF-8') . '.......... See full article';
echo $sub;

PHP echo-ing a PHP code inside an echo

I'm quite new here. I'm trying to make a blog/journal site that allows users to post their own journal. I'm still quite reluctant on making it because I am really afraid of malicious code injections.
So here's a sample code:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo "$test";
?>
What will come out is just the word "blah" in bold right? What I was trying to achieve was to echo "<b>blah</b>" instead. I don't want people to put some PHP codes that can actually mess up my whole web page. Please keep in mind that the variable $test is actually a MYSQL query, so that variable will be needed as an example. I know you can do echo '$test'; but it just comes out as "$test" instead. I feel like pulling my hair out I can't figure it out yet.
The second solution I know of is the htmlspecialchars(); function, but I want the strings to display as what I typed, not the converted ones...
Is there any way I can do that?
I think the OP wants the HTML itself to be output to the page, and not have the tags stripped. To achieve this, you can run the string first through htmlentities()
$test = '<b>blah</b>';
echo htmlentities($test);
This will output:
<b>blah</b>
Which will render in the page as
<b>blah</b>
Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.
You can use a template engine like Twig for exemple.
If htmlspecialchars(); is not the one you are looking for, try the header() option.
header('Content-type: text/plain');
When you are gonna give <b>Hi</b> to a browser, it will be displayed in Bold and not the text be returned. But you can try this way, outputting it inside a <textarea></textarea>.
Or the other way is to use htmlentities():
<?php
$test = "<b>blah</b>"; //User input from SQL
echo htmlentities("$test");
?>

nl2br() won't output line breaks, just 'n'

It's pretty simple, I have a text area post on my website, and if I input:
line 1
line 2
line 3
into it, it outputs:
line 1nline 2nline 3
My insert code is:
$status = strip_tags(stripslashes(htmlentities(mysql_real_escape_string($_POST['status']))));
$uid = strip_tags(stripslashes(htmlentities(mysql_real_escape_string($_POST['uid']))));
//more stuff
$sid = rndTxt(16);
$status = nl2br($status);
if (!get_magic_quotes_gpc()) {
$status = addslashes($status);
}
$insert = mysql_query("INSERT INTO mingle_status (uid,sid,status,`timestamp`) VALUES ('$uid','$sid','$status',now())") or
print mysql_error();
and my output code:
while($st = mysql_fetch_assoc($statussql)) {
$status = stripslashes($st['status']);
$sid = $st['sid'];
$td = $st['timestamp'];
?>
<div id="n">
<div id="statuses" class="<?php echo $sid; ?>">
<p><?php echo $status; ?></p>
<div id="statuscomadd" style="background:#E0E0E0;">
Like Dislike<?php echo time_since($td) . " ago"; ?>
</div>
</div>
Any help would be greatly appreciated!:)
you dont need to use nl2br() on insert, you will have to use it while displaying in html
and will have to remove stripslashes before insert
When inserting just do a mysql_real_escape_string() over the values. You only want to change the data (e.g. by using htmlentities() when you are going to display it).
Please also consider to stop using mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is a good PDO tutorial.
Another thing: do you realy need htmlentities()? Because imo a better solution is to use htmlspecialchars(). Otherwise all html entities will be replaced.
Also I don't think you need to use strip_tags(), because you are already doing htmlspecialchars() to protect you against XSS.
Now for you problem is it because you are using stripslashes() which breaks the \n linebreaks. I think you can just drop those add/stripslashes.
You use strip_tags(stripslashes(htmlentities(mysql_real_escape_string()))); which strips the slashes from \n.
Just use mysql_real_escape_string(), or htmlentities( ,ENT_QUOTES) for HTML.
Also, if it's possible use an UTF-8 encoding and htmlspecialchars() instead of htmlentities(). htmlentities() converts every character which has an HTML-representation, while htmlspecialchars() converts only the necessary characters. There's no need to convert everything. See: htmlentities vs htmlspecialchars

Run PHP coming into a mySQL result

This is maybe about the 4 time I ask this question all over the web without having a working solution.
It is driving me crazy.
I will try to make it as easier as possible to understand.
I have some code inside a database table, that looks like this:
<div> Hello my name is {$name}</div>
<span> I come from {$city}</span>
<div>I am {$age} years old</div>
I repeat, this text come from a mySQL table that I SELECT with the following code:
function getPageContent($page) {
$q='SELECT * FROM pages WHERE Page="'.$page.'"';
$r=mysql_query($q) or die(mysql_error());
while($row = mysql_fetch_array($r)) {
$content= $row['Content'];
}
return $content;
}
As you may see there are some PHP variables in the above code, such as {$age} or {$city}, they are only samples because I won't know the exact content.
What I need to do is to find a way for PHP to get the contents of the $content variable ( string coming from the DB SELECT ), to recognize the variables inside the brackets {$foo} as normal PHP variables and to run them before echoing the final code.
As you may see the $content variable may have different and unknown variables inside it, so I must find a way to get those variables whatever they represent.
I do not know if the right thing to use here is eval(). But seems that eval() works only with something like {echo 'value'} and not with variables {$foo}, or {echo $foo} because variables won't be recognized at all.
Does anyone have a solution for this?
This is driving me crazy.
The concept is to give to the users the possibility to enter HTML text inside my mySQL DB and to include whatever PHP code they want inside brackets {}. This can be very useful for example for multi-language websites..etc..
I hope you understand my point.
Thanks
Do not use eval for this. Just do a simple search and replace.
From your question, tt's hard to understand where exactly the values for $name, $city and $age are stored. So, I'll just start from the point where you've retrieved that info. Let's say it's something like this:
$content = '<div> Hello my name is {$name}</div>
<span> I come from {$city}</span>
<div>I am {$age} years old</div>
';
$city = 'Kansas City';
echo str_replace('{$city}', $city, $content);
Also, in the sample code you've provided, the $content variable keeps getting over-written on each iteration of the while loop. Perhaps, that's what you want to happen or perhaps you wish to concatenate it.
Edit
After reading some of your comments, it seems that you will need a more dynamic solution. You can do so with something along the lines of:
if (preg_match_all('/{\$\w+}/', $content, $matches)) {
foreach ($matches[0] as $var) {
// var now contains the {$variableName}.
}
}
This will find the variables within your HTML, which you can then loop over, comparing against your file that contains the actual name/value pairs. Then use str_replace as shown above.
Why not just do this?
<div> Hello my name is <?=$name?></div>
<span> I come from <?=$name?></span>
<div>I am <?=$age?> years old</div>
For this to work, of course, you need the short_open_tag directive enabled. You can accomplish the same thing in more code without this enabled too:
<div> Hello my name is <?php echo $name ?></div>
<span> I come from <?php echo $name ?></span>
<div>I am <?php echo $age ?> years old</div>
You should really watch out for malicious users gaining access to this script though, because the way you envisioned it, they would be able to execute any code they so desired. Be sure to sanitize input and output of this script!

Best practice for PHP output

I was wondering, whats the best practice on the example below.
<?php
if(isset($_POST['query'])){
$out = $_POST['query'];
}
?>
<div><?php echo $out; ?></div>
<input type="text" value="<?php echo $out; ?>" />
Using the above code would this pose a threat to website. Or would I need to prepare the output before using it as above. By prepare I mean encode it or escape special characters.
I am aware you need to escape it and validate inputs for db use, how about for outputting it?
Yes, since you’re putting it out into HTML you should use encode HTML’s special characters appropriately with htmlspecialchars:
if (isset($_POST['query'])) {
$out = htmlspecialchars($_POST['query']);
}
Besides that, $out is only defined when $_POST['query'] exists; you should think about having a default value if $_POST['query'] does not exist. Because otherwise, when register globals are enabled (that alone is a bad idea) you could set that variable via the URL query string with ?out=….
Yes, you should be using the php function htmlspecialchars
http://php.net/manual/en/function.htmlspecialchars.php
also, see this (accepted answer)
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
dont know about best practise and that depend on the coder i like turnary
echo (isset($_POST['query']))? htmlspecialchars($_POST['query']):"";

Categories