How to make file_get_contents recognize escape sequences as special characters? - php

I need to get content from a file so that the escape sequences (like \n) got recognized as special characters.
Consider the code:
<?php
$f = file_get_contents("test.txt");
echo "$f";
?>
while test.txt contains only:
Test\nOnly
It echoes:
Test\nOnly
while I'd like to have:
Test
Only
Is there a way to accomplish it with file_get_content or should I use something else (like output buffering)?

try using printf which the function outputs a formatted string.
<?php
$f = file_get_contents("test.txt");
printf ($f);
?>

Related

php - how to prevent echo &macr creates ¯ character,

I want to echo a string of an url variable:
echo "direct=1&closeBrowser=1&savelog=log.txt&storage=xfile&macrfile=klanta\test.html";
except the '&macr' creates the ¯ characters. How do i prevent this from happening?
htmlspecialchars function is used to convert special characters to HTML entities. See for reference, https://www.php.net/manual/en/function.htmlspecialchars.php
You can use this code :
$str = direct=1&closeBrowser=1&savelog=log.txt&storage=xfile&macrfile=klanta\test.html
echo htmlspecialchars($str);
OR you can use regular Expression :
echo preg_replace('/[^a-zA-Z0-9_ -]/s','', $str);
If you want to print a strings as raw text (ignoring any html special entities or tags), then use function htmlspecialchars($string).
Example:
echo htmlspecialchars($your_string);
Details: https://www.php.net/manual/en/function.htmlspecialchars.php

nl2br() , preg_replace , htmlspecialchars() and mysql_real_escape_string()

I have read all answers related to this but couldn't get the exact order to sanitize data
I have to input
<?php echo 'yes'; ?>
<?php echo 'yes' ?>
into a text area and submit it in database as it is with line breaks and output the code as it is with line breaks just as stackoverflow is doing.
output comes like this
<?php echo \'yes\'; ?>\r\n\r\n<?php echo \'yes\'; ?>
note : htmlspecialchars() is outputting the exact code but without line breaks ...
nl2br() is not taking /r and /n as line breaks
you can also use the below functions when inserting data
$unwanted = array("-", "_", "+"," ", etc .. );
$yourVariable = str_replace($unwanted, "NULL", $yourVariable);
or
trim($yourVariable);
This function returns a string with whitespace stripped from the beginning and end or yourVariable

Passing string to a Javascript function does not work

I am trying to pass a string to a javascript function which opens that string in an editable text area. If the string does not contain a new line character, it is passed successfully. But when there is a new line character it fails.
My code in PHP looks like
$show_txt = sprintf("showEditTextarea('%s')", $test_string);
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.$show_txt.';return false;">';
And the javascript function looks like -
$output[] = '<script type="text/javascript">
var showEditTextarea = function(test_string) {
alert(test_string);
}
</script>';
The string that was successfully passed was "This is a test" and it failed for "This is a first test
This is a second test"
Javascript does not allow newline characters in strings. You need to replace them by \n before the sprintf() call.
You are getting this error because there is nothing escaping your javascript variables... json_encode is useful here. addslashes will also have to be used in the context to escape the double quotes.
$show_txt = sprintf("showEditTextarea(%s)", json_encode($test_string));
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.htmlspecialchars($show_txt).';return false;">';
Why don't you try replacing all spaces in the php string with \r\n before you pass it to the JavaScript function? See if that works.
If that does not work then try this:
str_replace($test, "\n", "\n");
Replacing with two \ may work as it will encapsulate.
I would avoid storing HTML or JS in PHP variables as much as possible, but if you do need to store the HTML in a PHP variable then you will need to escape the new line characters.
try
$test_string = str_replace("\n", "\\\n", $test_string);
Be sure to use double quotes in the str_replace otherwise the \n will be interpreted as literally \n instead of a new line character.
Try this code, that deletes new lines:
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '', $test_string));
Or replaces with: \n.
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '\n', $test_string));

special character in PHP SOAP client

I have text values in an XML document created by the PHP SOAP client that includes an ' (that's an apostrophe). I've confirmed that the encoding is ASCII which should be valid UTF-8. I did it like this:
foreach ($myarrayofstrings as $s){
echo mb_detect_encoding($s);
}
If I remove the apostrophe like this then the server accepts my request.
$myarrayofstrings = str_replace("'", "", $myarrayofstrings);
Question:
Is there anything I can do to ensure this works every time without the str_replace?
For me always work utf8_encode function instead any replace:
$myarrayofstrings = utf8_encode($myarrayofstrings);
But i think you can use htmlspecialchars too
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>

Using a php function using a variable with delimiters

I would like to know If I can use a php function on a variable that contains delimiters like ' or ". I'm receiving a text content from my database and I would like to use: strip_tags($desc); on it but it does not work.
Here is an example of what it can contain using var dump:
string(1039) ""txt txt . txt'txt txt txtxtxtxt& " "
I guess you want to remove all tags. You should use the builtin function strip_tags() instead.
I'm assuming you want to work on the variable, not strip out the tags, then use this:
<?php
$str = "A 'quote' is <b>bold</b>";
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);
// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?>
htmlentities, will make your ' & " safe to handle, then you can convert them back after if needed.
Reference for code: http://us2.php.net/manual/en/function.htmlentities.php
Try not to use ereg_replace as it is going to be discontinued.
ereg_replace
This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
strip_tags
That said do you want to change all those chars to empty or are you trying to strip the tags? You can also convert the chars to the html_entities.
$desc = strip_tags($desc);

Categories