This question already has answers here:
How to avoid echoing character 65279 in php?
(12 answers)
Closed 6 years ago.
I see this character in Firebug .
I don't know why this is happening, there's no such character in my code. For Firefox it's OK, but in IE everything breaks. I can't even search for this character in Google.
I saved my file with utf-8 encoding without bom.
The character in question  is the Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). It may be that you copied it into your code via a copy/paste without realizing it. The fact that it's not visible makes it hard to tell if you're using an editor that displays actual unicode characters.
One option is to open the file in a very basic text editor that doesn't understand unicode, or one that understands it but has the ability to display any non-ascii characters using their actual codes.
Once you locate it, you can delete the small block of text around it and retype that text manually.
Just use notepad ++ with encoding UTF-8 without BOM.
yeah, its so simple to fix that, just open that file by notepad++ and step follow --> Encoding\ encoding UTF-8 without BOM.
then save that.
It work for me as well!
Try:
<?php
// Tell me the root folder path.
// You can also try this one
// $HOME = $_SERVER["DOCUMENT_ROOT"];
// Or this
// dirname(__FILE__)
$HOME = dirname(__FILE__);
// Is this a Windows host ? If it is, change this line to $WIN = 1;
$WIN = 0;
// That's all I need
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>UTF8 BOM FINDER and REMOVER</title>
<style>
body { font-size: 10px; font-family: Arial, Helvetica, sans-serif; background: #FFF; color: #000; }
.FOUND { color: #F30; font-size: 14px; font-weight: bold; }
</style>
</head>
<body>
<?php
$BOMBED = array();
RecursiveFolder($HOME);
echo '<h2>These files had UTF8 BOM, but i cleaned them:</h2><p class="FOUND">';
foreach ($BOMBED as $utf) { echo $utf ."<br />\n"; }
echo '</p>';
// Recursive finder
function RecursiveFolder($sHOME) {
global $BOMBED, $WIN;
$win32 = ($WIN == 1) ? "\\" : "/";
$folder = dir($sHOME);
$foundfolders = array();
while ($file = $folder->read()) {
if($file != "." and $file != "..") {
if(filetype($sHOME . $win32 . $file) == "dir"){
$foundfolders[count($foundfolders)] = $sHOME . $win32 . $file;
} else {
$content = file_get_contents($sHOME . $win32 . $file);
$BOM = SearchBOM($content);
if ($BOM) {
$BOMBED[count($BOMBED)] = $sHOME . $win32 . $file;
// Remove first three chars from the file
$content = substr($content,3);
// Write to file
file_put_contents($sHOME . $win32 . $file, $content);
}
}
}
}
$folder->close();
if(count($foundfolders) > 0) {
foreach ($foundfolders as $folder) {
RecursiveFolder($folder, $win32);
}
}
}
// Searching for BOM in files
function SearchBOM($string) {
if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
return false;
}
?>
</body>
</html>
copy this code to php file upload to root and run it.
for more about this: http://forum.virtuemart.net/index.php?topic=98700.0
"I don't know why this is happening"
Well I have just run into a possible cause:-) Your HTML page is being assembled
from separate files. Perhaps you have files which only contain the body or banner portion of your final page. Those files contain a BOM (0xFEFF) marker. Then as part of the merge process you are running HTML tidy or xmllint over the final merged HTML file.
That will cause it!
If you are using Notepad++, "Menu" >> "Encoding" >> "Convert to UTF-8" your "include" files.
If you have a lot of files to review, you can use this tool:
https://www.mannaz.at/codebase/utf-byte-order-mark-bom-remover/
Credits to Maurice
It help me to clean a system, with MVC in CakePhp, as i work in Linux, Windows, with different tools.. in some files my design was break.. so after checkin in Chrome with debug tool find the  error
Before clear space (trim)
Then replace with RegEx .replace("/\xEF\xBB\xBF/", "")
I'm working on Javascript, I did with JavaScript.
An old stupid trick that works in this case... paste code from your editor to ms notepad, then viceversa, and evil character will disappears !
I take inspiration from wyisyg/msword copypaste problem.
Notepad++ utf-8 w/out BOM works as well.
Here's my 2 cents:
I had the same problem and I tried using Notepad++ to convert to UTF-8 no BOM, and also the old "copy to MS notepad then back again" trick, all to no avail. My problem was solved by making sure all files (and 'included' files) were the same file system; I had some files that were Windows format and some that had been copied off a remote Linux server, so were in UNIX format.
Related
I've been searching far and wide, but couldn't find exactly what I needed, so here I am.
I have a php script that uploads an xml file - no issue here.
With the uploaded file, I need to open it and replace text inside the tags.
Example below
<Styles>
<Style p3:ID="Default" p3:Name="Normal" xmlns:p3="urn:schemas-microsoft-com:office:spreadsheet">
<p3:Font p3:FontName="Arial" p3:Size="10" />
<p3:Alignment p3:Vertical="Top" p3:WrapText="1" />
</Style>
<Style p3:ID="Percent" p3:Name="Percent" xmlns:p3="urn:schemas-microsoft-com:office:spreadsheet">
<p3:NumberFormat p3:Format="0%" />
</Style>
</Styles>
Anywhere you see p2 or p3 I need to replace these with a different syntax ss.
I have php 7.3 installed which broke compatibility with a script I was using (https://pear.php.net/package/File_SearchReplace/redirected) which is no longer maintained unfortunately. Does anyone know either how to update this script or how to achieve the same result using simpleXML maybe?
Many thanks!
You can try this solution. Algorithm for reading a file line by line and working with a string type. You can change the search pattern or method.
Maybe this will help
<?php
// faster replace word in file
function replaceWordInnerFile($pathToFile, $needleRegEx, $replace = null)
{
if (!\is_file($pathToFile)) {
throw new ErrorException('File not found');
}
if (!\is_writable($pathToFile)) {
throw new ErrorException('File not writable');
}
$newFilePath = $pathToFile.'_new';
$fileStream = \fopen($pathToFile, 'r');
$newFileStream = \fopen($pathToFile.'_new', 'w'); # create new file
while ($row = \fgets($fileStream)) {
// use any pattern for search
if (!$replace) {
// empty case
\fwrite($newFileStream, \preg_replace("/\<p[0-9]+:NumberFormat p3:Format=\"${needleRegEx}\"\s+\/\>/", '', $row));
continue;
}
\fwrite($newFileStream, \preg_replace("/\<p([0-9]+):NumberFormat p3:Format=\"${needleRegEx}\"\s+\/\>/", '<p${1}:NumberFormat p3:Format="'.$replace.'">', $row));
}
\fclose($fileStream);
\fclose($newFileStream);
\rename($pathToFile, $pathToFile.'.bak'); // backup original content
\rename($newFilePath, $pathToFile);
}
replaceWordInnerFile('/tmp/file-name', '[0-9]+\%', '669977');
Result
<Styles>
<Style p3:ID="Default" p3:Name="Normal" xmlns:p3="urn:schemas-microsoft-com:office:spreadsheet">
<p3:Font p3:FontName="Arial" p3:Size="10" />
<p3:Alignment p3:Vertical="Top" p3:WrapText="1" />
</Style>
<Style p3:ID="Percent" p3:Name="Percent" xmlns:p3="urn:schemas-microsoft-com:office:spreadsheet">
<p3:NumberFormat p3:Format="669977">
</Style>
</Styles>
Docs:
https://www.php.net/manual/en/function.fopen.php
https://www.php.net/manual/en/function.fputs.php
https://www.php.net/manual/en/function.fgets.php
https://www.php.net/manual/en/function.rename
https://www.php.net/manual/en/function.unlink
https://www.php.net/manual/en/function.preg-replace - Example #1
Is there a way I can insert < or > in HTML file using PHP. Here is a a part of code
<?php
$custom_tag = $searchNode->nodeValue = "<";
$custom_tag = $searchNode->setAttribute("data-mark", $theme_name);
$custom_tag = $dom->saveHTML($searchNode);
$root = $searchNode->parentNode;
$root->removeChild($searchNode);
$test = $dom->createTextNode("<?php echo '$custom_tag'; ?>");
$root->appendChild($test);
$saved_file_in_HTML = $dom->saveHTML();
$saved_file = htmlspecialchars_decode($saved_file_in_HTML);
file_put_contents("test.html", $saved_file);
The problem is that I get < using above method and I would like to have <.
EDIT:
Full code:
if($searchNode->hasAttribute('data-put_page_content')) {
$custom_tag = $searchNode->nodeValue = "'; \$up_level = null; \$path_to_file = 'DATABASE/PAGES/' . basename(\$_SERVER['PHP_SELF'], '.php') . '.txt'; for(\$x = 0; \$x < 1; ) { if(is_file(\$up_level.\$path_to_file)) { \$x = 1; include(\$up_level.\$path_to_file); } else if(!is_file(\$up_level.\$path_to_file)) { \$up_level .= '../'; } }; echo '";
$custom_tag = $searchNode->setAttribute("data-mark", $theme_name);
$custom_tag = $dom->saveHTML($searchNode);
$root = $searchNode->parentNode;
$root->removeChild($searchNode);
$test = $dom->createTextNode("<?php echo '$custom_tag'; ?>");
$root->appendChild($test);
$saved_file_in_HTML = $dom->saveHTML();
$saved_file = htmlspecialchars_decode($saved_file_in_HTML);
file_put_contents("../THEMES/ACTIVE/". $theme_name ."/" . $trimed_file, $saved_file);
copy("../THEMES/ACTIVE/" . $theme_name . "/structure/index.php", "../THEMES/ACTIVE/" . $theme_name ."/index.php");
header("Location: editor.php");
}
FINAL EDIT:
If you want to have > or < using PHP DOMs methods, it is working using createTextNode() method.
The original question appears to concern how to use PHP to manufacture an HTML tag, so I'll address that question. While it is a good idea to use htmlentities(), you also need to be aware that it's primary purpose is to protect your code so that a malicious user doesn't inject it with javascript or other tags that could create security problems. In this case, the only way to generate HTML is to create HTML and PHP provides at least three ways to accomplish this feat.
You may write code such as the following:
<?php
define("LF_AB","<");
define("RT_AB",">");
echo LF_AB,"div",RT_AB,"\n";
echo "content\n";
echo LF_AB,"/div",RT_AB,"\n";
The code produces start and end div tags with some minimal content. Note, the defines are optional, i.e. one could code in a more straightforward fashion <?php echo "<"; ?> instead of resorting to using a define() to generate the left-angle tag character.
However, if one is wary of generating HTML in this manner, then you may also use html_entity_decode:
<?php
define("LF_AB",html_entity_decode("<"));
define("RT_AB",html_entity_decode(">"));
echo LF_AB,"div",RT_AB,"\n";
echo "content\n";
echo LF_AB,"/div",RT_AB,"\n";
This example treats the arguments to html_entity_decode as harmless HTML entities and then converts them into HTML left and right angle characters respectively.
Alternately, you could also take advantage of the DOM with PHP, even with an existing HTML page, as follows:
<?php
function displayContent()
{
$dom = new DOMDocument();
$element = $dom->createElement('div', 'My great content');
$dom->appendChild($element);
echo $dom->saveHTML();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<style>
div {
background:#ccbbcc;
color:#009;
font-weight:bold;
}
</style>
</head>
<body>
<?php displayContent(); ?>
</body>
</html>
Note: the Dom method createTextNode true to its name creates text and not HTML, i.e. the browser will only interpret the right and left angle characters as text without any additional meaning.
If I understand you correctly, I think you could use < and > in the first place. They should be rendered as HTML. Might save you some coding. Let me know if it works.
I am saving and editing data in text files through a text area using CKeditor and everything is working smoothly. Everything except new lines ("<br />") that don't show when I try to edit/update the text file via my update.php. I really can't find out what is the issue, I have tried to replace tag after tag and did not manage to solve the problem.
Code for reading and writing on the text file:
$text1 = "../conteudos/start/text1.txt";
if (isset($_POST['body1'])) {
$newData = nl2br($_POST['body1']);
$handle = fopen($text1, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text1)) {
$myData1 = file_get_contents($text1);
$myData1 = strip_tags($myData1);
}
Code for editing the text contents:
<textarea class="ckeditor" name="body1" id="body1">
<?php echo str_replace("<br />","",$myData1); ?>
</textarea>
As mentioned before, the text shows up nicely on my index.php with no html tags whatsoever, but when I try to edit it via the text area above I still get no tags, but I get all the text into one single line. This really should be working because I am using "nl2br" function, but apparently something is canceling it.
What can I do?
I think what you are trying to do is:
$text1 = "../conteudos/start/text1.txt";
if (isset($_POST['body1'])) {
$newData = nl2br($_POST['body1']);
$handle = fopen($text1, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text1)) {
$myData1 = file_get_contents($text1);
//Change it here first
str_replace("<br />","\n",$myData1); //You also forgot the new line character I think.
$myData1 = strip_tags($myData1);
}
Then you can do this:
<textarea class="ckeditor" name="body1" id="body1">
<?php echo $myData1; ?>
</textarea>
You made a small logic error according to what I see. According to my understanding, you want to strip out the tags but preserve the new line. So change the "< br />" first before you strip out the tags. Hopefully that's what you want I guess.
You are stripping the tags from your file ($myData1 = strip_tags($myData1)). <br /> is a tag, so you're stripping it out too!
This makes your str_replace useless, since the tag has already been stripped. In any case, you shouldn't need that nl2br in the first place, since newline characters are perfectly valid inside text files...
Something very strange happened because according to the user Touch, his method was working on his computer. Unfortunately it wasn't working on mine! So after a while thinking I came to the conclusion that I was over doing some process of replacement of tags. In order to confirm or not this theory of mine I decided do "back-engineer" Touch's method by erasing line by line and seeing what the result was. In the end I saw that my conclusion was correct, I was over doing process of tag replacement because this code:
$text2 = "../conteudos/start/text2.txt";
if (isset($_POST['body2'])) {
$newData = nl2br($_POST['body2']);
$handle = fopen($text2, "w");
fwrite($handle, $newData);
fclose($handle);
}
// ------------------------------------------------
if (file_exists($text2)) {
$myData2 = file_get_contents($text2);
$myData2 = $myData2;
}
worked in perfection. I can only think that this was due to I was using KCEditor...
A big thanks to all that answered, maing me think and helping me this way to achieve my goal!
Error deleting file if there are multiple connections to multiple page.
Error:Warning: unlink(folder/1.txt.txt) [function.unlink]: Permission denied in C:\htdocs\fopen.php on line 7
Note: If only one connection to access everything normally occurs (no error occurs).
PHP code fopen.php:
<?php
function fastWrite($a){
echo 'Coping file: "',$a,'" to "',$a,'.txt"<br>';
copy($a,$a.'.txt');
echo 'Delete file: "',$a,'.txt"<br>';
unlink($a.'.txt');
}
for($i=0;$i<10;$i++){
fastWrite('folder/1.txt');
echo '<hr>';
}
?>
html/javascript code (to simulate multiple connections):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<title>my test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function myTest(z){
$.ajax("fopen.php?time="+(new Date().getTime()),{"success":function(data){
$("<div></div>").addClass("sty").html(data).appendTo("body");
},"error":function(a,b,c){
$("<div></div>").addClass("sty").html([a,b,c]).appendTo("body");
}});
}
</script>
<style>
.sty{
border:1px #000 solid;
overflow:auto;
margin:5px 0 0 5px;
}
</style>
</head>
<body>
<p>New test</p>
<script type="text/javascript">
var dd = "";
for(var i=0;i<10;i++){
dd += "myTest(\"#a"+(i+1)+"\");\n";
}
eval(dd);
</script>
</body>
</html>
What did I do wrong?
Thanks.
Solution: clearstatcache
You're having a problem because two processes are trying to copy and delete the same file at the same time. Because they are separate processes, you can't easily control the order in which they do things.
Imagine two processes, running fastWrite() at the same time:
t1 copies 'a' to 'a.txt'
t2 copies 'a' to 'a.txt'
t2 deletes 'a.txt'
t1 tries to delete 'a.txt', but fails because it does not exist
This is called a "race condition".
If you don't mind that the unlink call will sometimes fail, you can ignore the error by using the '#' symbol in front of the command:
#unlink("$a.txt");
I'm pretty sure that saving user-generated data into the same file over and over again isn't your ultimate goal. You obviously encountered this problem in the pursuit of something larger. Maybe you should start a new question more focused on that problem.
If you just need a temporary file to work with during the connection, don't always name the file the same. Instead, you could:
function doStuffToFile($fname) {
$tempName = $fname . "." . getmypid() . "." . rand();
copy($fname, $tempName);
// do stuff to your temporary file
unlink($tempName);
}
The problem is that you have two or more scripts that write to and delete 1.txt.txt. This is called a race condition. Script1.php has no direct way of knowing if Script2.php is using a file, you need to implement this mechanism yourself.
A simple solution is to create a lock file before using the shared file and delete the lock file once you are done with it.
There is a new problem then: how do you ensure that the two scripts do not create the lock file at once? Script1.php might find that lock file isn't there but before it actually creates the file, the processor switches to Script2.php which also finds the lock file missing. What then?
PHP provides a useful flock function. I am not aware of the gory details but I believe it should solve your problem, to some extent, on some platforms at least.
<?php
function fastWrite($a)
{
# //// LOCK \\\\
$fp = fopen("fastwrite.lock", "w");
if (flock($fp, LOCK_EX) === false) { # PHP will stop at this line until the lock is acquired
die("flock failed");
}
# \\\\ LOCK ////
echo 'Coping file: "', $a, '" to "', $a, '.txt"<br>';
copy($a, $a . '.txt');
echo 'Delete file: "', $a, '.txt"<br>';
unlink($a . '.txt');
# //// UNLOCK \\\\
if (flock($fp, LOCK_UN) === false) {
die("flock failed");
}
fclose($fp);
# \\\\ UNLOCK ////
}
for ($i = 0; $i < 10; $i++) {
fastWrite('1.txt');
echo '<hr>';
}
PS: I was not able to reproduce the race condition on my system.
I am reading one Persian text file (using PHP) with the help of below code:
/* Reading the file name and the book (UTF-8) */
if(file_exists($SourceDirectoryFile))
{
$NameBook = "name.txt";
$AboutBook = "about.txt";
$myFile = "Computer-Technolgy/2 ($i)/".$NameBook;
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo 'Name file: '. $theData.'<hr/>';
}
name.txt file contents :
آموزش شبكه هاي کامپيوتري (LEARNING NETWORK)
Name file: ����� ���� ��� ��������� (LEARNING NETWORK)
The reason you are seeing this is because you are just echoing the contents raw. Your browser will need more information, in order to display the message in its correct form.
The easiest way is to use the snippet below.
/* Reading the file name and the book (UTF-8) */
if (file_exists($SourceDirectoryFile))
{
$NameBook = "name.txt";
$AboutBook = "about.txt";
// Using file_get_contents instead. Less code
$myFile = "Computer-Technolgy/2 ($i)/" . $NameBook;
$contents = file_get_contents($myFile);
// I want my browser to display UTF-8 characters
header('Content-Type: text/html; charset=UTF-8');
echo 'Name file: ' . $contents . '<hr/>';
}
Please note that the header function needs to be executed at the beginning of the output to the browser. So for instance if you have additional data that is displayed prior to this function, you need to move the header statement at the top. Otherwise you will end up with warnings on screen that the headers have already been set.
You'll need to make sure that the page where you're displaying the text file has correct encoding.
final and best solution is this:
use this line under your connect
mysqli_set_charset( $con, 'utf8');
like this:
$con = mysqli_connect("localhost","root","amirahmad","shoutit");
mysqli_set_charset( $con, 'utf8');
and at the end add this line right under the head tag in your html to make sure your page have utf-8 charset,like this:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
and that's it . you can read formal document here : pph.net charset