I wrote a php script that pulls some data from a database and displays it in XML format. For some reason it halts output when it gets to an apostrophe in the data. This is a SELECT statement, and a simple one at that, so I don't understand why there are any issues with apostrophes or quotation marks. I've tried using addslashes() and mysql_real_escape_string(), even though my understanding is that those are for sanitizing data being inserted into the database, and it did not help. I'm stumped. Below is the code and thanks in advance for any advice!
<? if($result = $mysqli->query("SELECT * FROM ".$tbl)){
while($row = $result->fetch_object()){ ?>
<slide>
<id><?= $row->id ?></id>
<title><?= $row->title ?></title>
<chatter><?= $row->description ?></chatter>
<image><?= $row->path ?></image>
<link><?= $row->href ?></link>
<active><?= $row->active ?></active>
</slide>
<? }
}else{
echo $mysqli->error;
}
EDIT:
It turns out I have misunderstood the problem. They are not apostrophes but instead are right single quotes. If I change them to actual apostrophes the script works but I still don't understand why it doesn't simply output them though.
Try with str_replace("'", "\'", $field_to_be_replaced);
You can replace the ' char with a blank space if you prefer, just for testing.
Are you sure it halts on the output of the data, and not when the data is processed? Apostrophe's have special meaning in XML, so if they are included in your XML data you have to replace them with an entity reference. There are 5 predefined entity references in XML, for less than, greater than, ampersand, apostrophe, and one for quotation mark. Alternatively, you can mark the text as CDATA so that the XML parser doesn't try to parse it.
Try making your program output the XML data to a text file instead of to wherever it is going now. Does it still halt on the apostrophe? If not, then it's definitely because of a problem parsing the data. If your program still halts on the apostrophe even when outputting the data only to a text file, there may be a problem somewhere else in the program where that data is processed. Check all the references to the variable containing the data, and see if you can find the exact line the program breaks on.
the apostrophe (') is an invalid character for XML!
You must call $safe_string = str_replace("'","'",$string) in all your fields before
outputting the .XML file.
Check here to learn about these characters and build a more complete str_replace
EDIT:
What im using:
// save ubercart products in XML
function replace_characters_for_xml($str) {
return str_replace(
array("&",">","<","'",'"'),
array("&",">","<","'","""),$str
);
}
...
$row->title = replace_character_for_xml($row->title);
$row->href = replace_character_for_xml($row->href);
...
Related
I have a form where I can also write HTML tags. I must save this textarea preserving every single HTML tag. So here's the code:
foreach($_POST["comment"] AS $key => $value)
{
mysql_query("UPDATE comments SET title= '".$value["title"]."', comment = '".$value['comment']."' WHERE id = '".$value["id"]."'");
}
When I try to save this:
<b>Hello</b>
In MySQL I get this result:
<b>Hello</b>
I must keep every single HTML as it is. If I write <b> I must save exactly <b> in database. I tryed escaping, html etities, quotes, strip slashes (...) but this guy keep saving everything in the wrong way.
p.s. Before you ask yes, description field is TEXT tupe with UTF-8 encoding.
Have you tried using http://php.net/manual/en/function.htmlspecialchars-decode.php on the mentioned value? This should do exactly what you're asking.
try running:
$sStr = '<b>Hello</b>';
echo htmlspecialchars_decode($sStr);
And it will be encoded properly. Feeding that to the database stores the value correct.
Also, but this is more of a side-notice, you really shouldn't save post data without validating the input. I do assume this is just a quick example and not production code? However, just a suggestion.
You need to escape the entry. If you are using the mysql method, you need the mysql_escape_string function like:
$string = mysql_escape_string("<br>Hello</br>");
Edit: I think %27 is actually the wrong kind of quote. I am still stuck though, I cannot find a PHP function that does the conversion I want.
Edit (again): I found a solution where I stick %26rsquo%3bs into the URL and it turns into ’. It works so I posted it as an answer below but I'd still be interested in knowing how it'd be done with PHP functions.
I'm working on a website that uses a PHP tree as if it were a directory. For example, if someone types index.php?foo=visual programming (or index.php?foo=visual%20programming) then the website opens the item "Visual Programming" (I'm using strtolower()).
Another working example would be index.php?foo=visual programming&bar=animated path finder which opens "Animated Path Finder", a child of "Visual Programming".
The problem is that some of the items are named things like "Conway’s Game of Life" which uses a HTML entity. My guess of what someone should type to open this would be index.php?foo=visual%20programming&bar=conway%27s%20game%20of%20life. The problem is that ' is not === to ’.
What do I need to do to make this work? Here is my code that selects an item based on $_GET (the PHP is inside of <script type="text/javascript">):
<?php
function echoActiveDirectory($inTree) {
// Compare $_GET with PhpTree
$itemId = 0;
foreach ($_GET as $name) {
if ($inTree->children !== null) {
foreach ($inTree->children as $child) {
if (strtolower($child->title) === strtolower($name)) {
$itemId = $child->id;
$inTree = $child;
break;
}
}
}
}
// Set jsItems[$itemId].selected(), it will be 0 if nothing was found
echo "\t\tjsItems[".$itemId."].selected();\n";
}
echo "// Results of PHP echoActiveDirectory(\$root)\n";
echoActiveDirectory($root);
?>
The website is a work in progress, but it can be tested here to see $_GET working: http://alexsimes.com/index.php
The hex code %27 (39 decimal) will never translate to ’, since it is a completely different entity (Wikipedia). It could be translated to ', but PHP doesn't do that (although I don't know the reason for that).
Edit
While there is no standard for URL-encoding multibyte character sets, PHP will treat a string as just a set of bytes, and if those match an UTF-8 sequence, it will work:
php -r 'echo htmlentities(urldecode("%E2%80%99"), ENT_QUOTES|ENT_HTML401);'
should output
’
You can use html_entity_encode() and html_entity_decode() PHP functions to convert those characters to html entities or decode them back to desired characters before comparison.
You can try the htmlentities function to convert special characters to corresponding html entity. But in your case if data is already stored in db as html entity form, the data from $_GET parameter must be first passed through htmlentities before using it in your query.
I'm storing HTML and text data in my database table in its raw form - however I am having a slight problem in getting it to output correctly. Here is some sample data stored in the table AS IS:
<p>Professional Freelance PHP & MySQL developer based in Manchester.
<br />Providing an unbeatable service at a competitive price.</p>
To output this data I do:
echo $row['details'];
And this outputs the data correctly, however when I do a W3C validator check it says:
character "&" is the first character of a delimiter but occurred as data
So I tried using htmlemtities and htmlspecialchars but this just causes the HMTL tags to output on the page.
What is the correct way of doing this?
Use & instead of &.
What you want to do is use the php function htmlentities()...
It will convert your input into html entities, and then when it is outputted it will be interpreted as HTML and outputted as the result of that HTML...For example:
$mything = "<b>BOLD & BOLD</b>";
//normally would throw an error if not converted...
//lets convert!!
$mynewthing = htmlentities($mything);
Now, just insert $mynewthing to your database!!
htmlentities is basically as superset of htmlspecialchars, and htmlspecialchars replaces also < and >.
Actually, what you are trying to do is to fix invalid HTML code, and I think this needs an ad-hoc solution:
$row['details'] = preg_replace("/&(?![#0-9a-z]+;)/i", "&", $row['details']);
This is not a perfect solution, since it will fail for strings like: someone&son; (with a trailing ;), but at least it won't break existing HTML entities.
However, if you have decision power over how the data is stored, please enforce that the HTML code stored in the database is correct.
In my Projects I use XSLT Parser, so i had to change to (e.g.). But this is the safety way i found...
here is my code
$html = trim(addslashes(htmlspecialchars(
html_entity_decode($_POST['html'], ENT_QUOTES, 'UTF-8'),
ENT_QUOTES, 'UTF-8'
)));
And when you read from DB, don't forget to use stripslashes();
$html = stripslashes($mysq_row['html']);
I am trying to convert a drupal installation into a front end driven by Code Igniter. This is an experimental project to check the performance boost I can get. But the biggest problem I am facing is that few fields in Drupal store php string as it is. For example
<?php print "A"; ?>
This is normal
Now I am able to see the text "This is normal" which comes from the query that I run in Code Igniter, but I don't see the php function which is saved inside the table. I can see the text when I view the record through phpmyadmin. But somehow not inside the CI query result.
I hope U've got the solution. But just in case if you haven't try this:
I created a table with two columns
//$result Contains the data fetched from the table using a model.
foreach ($result as $key=>$val) {
if($key == 'code') {
$val = str_replace('<?php','',$val); //Remove PHP's opening tag.
$val = str_replace('?>','',$val); //Remove PHP's closing tag.
$val = rtrim($val); //Remove leading and trailing spaces.
echo $key.': ';
eval($val.';'); //Execute the PHP code using eval.
} else {
echo $key.': '.$val.PHP_EOL;
}
}
I tried
echo $result['code']
print_r($result)
var_dump($result)
highlight_string($result['code'])
eval($result['code'])
and finally str_replace followed by eval($result['code']).
Check the screen shot of the result obtained from: here
There you can see that the Result produced by 1,2, and 5 are empty. But when you inspect element against the empty space It'll clearly show that the string that's echoed/print is commented out.
Screen-Shot. This is has nothing to do with codeigniter. Its done by HTML Parser.
So the solution is to remove the opening and closing tags of PHP and then use eval. I hope this helps.
Thanks for the help. Yes, the last resort was the eval function and that is the one which helped me attain which I was wanting it to do.
The data which was inside the database had PHP function and only eval function was able to treat that part as a PHP code and execute it when I was getting the data inside my view.
I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.