php string concatenation "A<"."B" does not work - php

I'm writing a function to output HTML elements, the problem is: when I try to concatenate this two strings:
$tag = "<" . "tag";
The instruction echo $tag outputs nothing. What is wrong

As mentioned in comments, special characters like <, will be parsed by browser as HTML, therefore you won't see them as you expect.
Its almost the same thing:
$tag = 'p';
echo '<' . $tag '>' . Test . '</' . $tag . '>';
Which is the same as
echo '<p>' . Test . '</p>';
So after script execution you'll see just
Test
in a browser. but when viewing a source, it will be as
<p>Test</p>
If for some reason you want to see HTML tags, then you need to escape special chars using built-in function htmlentities().
In your case, you can just prepare a string, then just echo it like
echo htmlentities($string);

If by tag you mean an HTML entity then its not going to be seen in the browser. You may need to do a 'view source' to see what was created by echo call.

Related

PHP prevent html entity creation at string concatenation

How can i prevent that PHP converts a recognized part of a string to an html-entity?
So e.g. lets say i have to concat parts together to an url, like:
echo '&' . 'section=' . '<br>';
$a = '&a';
$b = 'mplitude=';
echo "{$a}{$b}" . '<br>';
echo sprintf("%s%s", '&quote', '=');
the code above prints the following:
§ion=
&litude=
"e=
instead of:
&section=
&amplitude=
&quote=
how can this be prevented without throwing filters on it trying to convert the symbols back to an string again?
You need using htmlspecialchars function:
echo htmlspecialchars('&' . 'section=' . '<br>');

Cannot output a big string block without break lines (nginx+php)

I try to print a big JSON block (100k) to the browser, but the server fails without an error.
For example:
echo 'var config = ' . json_encode( $config ) . ';' . PHP_EOL;
I Have found that if i send a small piece, it's OK.
I have found that if I put line breaks in the JSON string, it's OK even if the string is 400k.
For example:
$config_json = json_encode( $config );
$config_json = str_replace( '},', '},' . PHP_EOL, $config_json );
echo 'var config = ' . $config_json . ';' . PHP_EOL;
But the breaklines breaks my JSON.
So, if it's a buffer setting, why the PHP_EOL helps?
I have tried also to split the JSON to pieces like here: https://stackoverflow.com/a/19156563/1009525, But without success, Only the breaklines helps me.
As you write
the server fails without an error
I presume you mean that the server sends a response to the client (status code: 200 - no error), but the response body (the content) is empty (this is the failure).
You should check this because if actually the server sends a response with content then the issue is not with php, nginx or buffering.
Otherwise (as suggested in comments) maybe the JSON instead of inside a <script> - </script> block may be wrapped between <pre> tags and this could be the problem (but I can't help unless you post more of your code).
From now on I assume the response sent from the server is empty
The code you posted is valid and is supposed to handle correctly the output string you're building up (that's far below PHP limits).
Said that it seems a weird buffering issue. I write "weird" because as far as I know (and I took time to do some research too) buffering should not be influenced by line breaks.
I have found that if I put line breaks in the JSON string, it's OK even if the string is 400k.
A quick workaround to solve your problem is to output a valid JSON with line breaks. You just need to specify an option to json_encode:
echo 'var config = ' . json_encode( $config, JSON_PRETTY_PRINT ) . ';' . PHP_EOL;
JSON_PRETTY_PRINT tells json_encode to format the json to be more readable and doing so will add line breaks.
(Note that this option is available for PHP 5.4.0 and above)
I hope the above solution works for you.
Anyway I strongly suggest you to investigate further the issue in order to let the original code too to work.
First you should ensure you're running a recent and stable version of both nginx and php.
Then I would check nginx configuration file, php-fpm configuration (if you're using php-fpm) and finally php configuration.
Also check php, nginx, and php-fpm error logs.
try using php heredoc for echoing http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
In case you don't have PHP version > 5.4.0 installed on your server a quick workaround could be something like this. The below snippet works for a test array. Initial test was with an array of 250Kb. Since i can't post the actual test array here is a test link with a smaller example. It is as the result of JSON_PRETTY_PRINT though.
$out = json_encode($arr,JSON_FORCE_OBJECT);
$out = str_replace( ':{', ':' . PHP_EOL . ' ' . '{', $out );
$out = str_replace( '},', PHP_EOL . ' },', $out );
$out = str_replace( ',', ',' . PHP_EOL . ' ', $out );
$out = str_replace( '},' . PHP_EOL . ' ', '},' . PHP_EOL . ' ', $out );
$out = str_replace( '}}', PHP_EOL . ' }' . PHP_EOL . '}', $out );
echo $out;

php empty string htmlspecialchars()

So, I am trying to use htmlspecialchars() to protect my website but unfortunately I got stuck in this code:
<?php
function wrap_nome($firstname, $lastname)
{
$join = htmlspecialchars($firstname, ENT_QUOTES) . ' ' . htmlspecialchars($lastname, ENT_QUOTES);
if (mb_strlen($join) > 32)
{
$text = substr($join,0,32);
return $text . " ...";
}
else
{
return $join;
}
}
$nome = wrap_nome($firstname, $lastname);
echo '<span style="color:#7F7F7F;font-family:Arial;font-size:13px;"><b>' . $nome . '</b></span>';
?>
Initially I thought that the problem maybe was the fact that the string $nome had double and single quotes, then I removed them and found out that htmlspecialchars($lastname, ENT_QUOTES) continues to be echoed and htmlspecialchars($firstname, ENT_QUOTES) continues to give me an empty string!
If I do this:
echo '<span style="color:#7F7F7F;font-family:Arial;font-size:13px;"><b>' . htmlspecialchars($nome, ENT_QUOTES) . '</b></span>';
... It wont output anything.
Any ideas of what is causing this ?
htmlspecialchars returns FALSE if it gets an error, which happens if $nome contains any characters that can't be represented in the specified character set. The character set defaults to ISO8859-1 before PHP 5.4, UTF-8 since then, try using htmlspecialchars($nome, ENT_QUOTES, 'iso8859-1').
If that doesn't work, see the list of character sets in the documentation and use the appropriate one for your names.
Simply replace
htmlspecialchars($str,ENT_QUOTES );
with
htmlentities($st ,ENT_QUOTES ,"UTF-8");

printing a php variable as it is : with all the special characters

Ok I need to find out what is contained inside a PHP variable and I have it to do it visually, is there a function to display whatever that's contained in a string as it is?
For example :
$TEST = '&nbsp' . "\n" . ' ';
if I use echo the output will be :
while i want it to be :
&nbsp\n&nbsp
is it possible? (I hope I was clear enough)
ty
You can use json_encode with htmlspecialchars:
$TEST = ' ' . "\n" . ' ';
echo json_encode(htmlspecialchars($TEST));
Note that json_encode has third agrument in PHP 5.4.
var_dump() should do the work for you?
Example:
echo "<pre>";
var_dump($variable);
echo "</pre>";
Use <pre> to keep the format structure, makes it alot easier to read.
Resources:
http://php.net/manual/en/function.var-dump.php
http://www.w3schools.com/tags/tag_pre.asp
Try print_r, var_dump or var_export functions, you'll find them very handy for this kind of needs!
http://www.php.net/manual/en/function.htmlspecialchars.php
or
http://www.php.net/manual/en/function.htmlentities.php
$TEST = '&nbsp' . "\n" . ' ';
echo htmlspecialchars(str_replace('\n','\\n', $TEST), ENT_QUOTES);
or
$TEST = '&nbsp' . "\n" . ' ';
echo htmlentities(str_replace('\n','\\n',$TEST), ENT_QUOTES);
You may have to encode the newlines manually. If you want to encode them as actual newlines you can use nl2br. Or string replace these characters with your preference. Update: as I have added to the code per request. String replace special characters you wish to see like newlines and tabs.
assuming you want it for the debugging purposes, let me suggest to use urlencode(). I am using it to make sure I don't miss any invisible character.
The output is not that clear but it works for me.

my php function strip_tags is not working according to my expectations

I am taking input as comments in my website. where i want few html tags to allow like
<h2>, <h3>, so on. . .
and few to ban.
But i am also using a function which check the part of string and replace it with smilies
let us say '<3' for heart and ':D' for lol
When i use function sanitizeHTML() which is following
public function sanitizeHTML($inputHTML, $allowed_tags = array('<h2>', '<h3>', '<p>', '<br>', '<b>', '<i>', '<a>', '<ul>', '<li>', '<blockquote>', '<span>', '<code>', '<img>')) {
$_allowed_tags = implode('', $allowed_tags);
$inputHTML = strip_tags($inputHTML, $_allowed_tags);
return preg_replace('#<(.*?)>#ise', "'<' . $this->removeBadAttributes('\${1}1') . '>'", $inputHTML);
}
function removeBadAttributes($inputHTML) {
$bad_attributes = 'onerror|onmousemove|onmouseout|onmouseover|' . 'onkeypress|onkeydown|onkeyup|javascript:';
return stripslashes(preg_replace("#($bad_attributes)(\s*)(?==)#is", 'SANITIZED ', $inputHTML));
}
It remove bad attributes and allow only valid tags but when string like <3 for heart come this function remove the part of string after <3 .
Note :
The smilies code which do not have html special chars < or > sign work fine.
You're using PCRE to parse html, which is never a good idea. The expression <(.*?)> will match everything from < up to the next >. You need something more like <[^>]+>. However, that still has problems (and will capture <3). You could use a negative lookahead (<(?!3)[^>]+>) to handle that specific case, but there are a lot of other cases to consider. You may want to consider using a DOM parser instead.

Categories