Output mysql as raw text - php

I have a result in the database like this
[border color=#EEE]
[pictitle]Title of your picture[/pictitle]
[image]http://tingle.fm/wiki/assets/images/default-thumb.gif[/image]
[line color=#D4D4D4][/line]
[/border]
And for some reason when I output the text it shows like this:
[border color=#EEE]
[pictitle]Title of your picture[/pictitle]
[image]http://tingle.fm/wiki/assets/images/default-thumb.gif[/image]
gif[/image]
[line color=#D4D4D4][/line]
[/border]
The code I use is this:
<?php
$query = mysql_query("SELECT FROM wiki WHERE id='1'");
$assoc = mysql_fetch_assoc($query);
echo nl2br($assoc['content']);
?>
Is there any way I can output the text as raw please so it indents? Much appreciated!

If this is the output on your page, then make sure you can see those spaces/tabs also in the source code. If you can, then you can use str_replace to replace those white characters with something that will be also visible on the page
// Replacing white space characters with HTML entities
$replacedSpaces = str_replace("\n ", "\n ", $assoc['content']);
// Replacing new line characters with <br> and printing it out
echo nl2br($replacedSpaces);

Related

Receive JSON POST in PHP with ENTER in one of the field value

When "descriptions" field has "enter" (newline) API is failing.
Image to check all parameter sent by users
Below code to get the data from posted JSON.
// get posted data
$jason_value = json_decode(file_get_contents("php://input"));
$crm_id = $jason_value->data->crmId;
$descriptions = $jason_value->data->descriptions;
I would like to accept descriptions as a string one line.
descriptions = "10+ windows modern style 7057655959".
I do not have access to the program where the user enters the description where I can add validation and convert it to \n.
Getting below string after conversion
{ "jwt": "eyJ0", "data": { "crmId": "15876047", "geoconceptAppointmentId": "15876","geoconceptCustomerId": "15876047","status": "Rejected","appointmentDateTime": "","firstName": "Nick Test","lastName": "PA","address": "9112 RUE Tom","city": "MONTREAL","state": "QC","zip": "H2N1T1","country": "CAN","phoneNumber1": "5148332222","phoneNumber2": "5148332222","email": "nbskgg#gmail.com","dateEntry": "2019-06-20 12:02","dateModify": "2019-06-20 12:02","preferredWayToContact": "","textMsgFlag": "Y","hearAboutUs": "Referral","perferredTime": "Anytime","descriptions": "I have to call at 5" pm. ","worklog": "This is the comment ","rejectReason": "Area | Region","referredByDC": "09999","referredByStoreUsername": "store215","assignedUsername": "","createdByUsername": "np","modifiedByUsername": "np","btgMarket": "Montreal"}}
You're correct that in PHP7+, a literal tab or newline is going to cause the json parsing to fail. file_get_contents("php://input") returns a single string so I see no reason why you couldn't just filter that before you attempt to parse it. But maybe I'm missing something.
//Catch Unix OR DOS line endings, but not both
$filter = Array("\n","\n\r");
$replace = " ";
$cleanJSON = str_replace($filter, $replace, file_get_contents("php://input");
$data = json_decode($cleanJSON));
I want to point out that after this point, your code is referencing a variable that does not exist: $jason_value
$crm_id = $jason_value->data->crmId;
$descriptions = $jason_value->data->descriptions;
To reference properties of the object you just created, go directly to $data:
$crm_id = $data->crmId;
$descriptions = $data->descriptions;
I expect that you'd want to replace the newline with a space but you may just want an empty string if what you're actually encountering has a space before the newline but that's impossible to tell from what we have.

PHP & JSON : Trying to write JSON to Mysql

I am having an issue where my PHP script opens a file with JSON code and needs to insert it into a MySQL database.
For some reason it only displays some of the output from the JSON.
Here is my code
$json = json_decode(file_get_contents('data.json'), true);
$data = $json;
// VAR's
$system = $data['System'];
$cid_from = $data["From"];
$cid_to = $data['To'];
//DEBUG USAGES
$array = print_r($data, true);
////// THIS ONE WORKS FINE
echo $data["System"];
////// THIS ONE DOESN'T WORK
echo $data["To"];
file_put_contents('output/json-local.txt',$array . "\r\n", FILE_APPEND);
////// BUT HERE IT ACTUALLY WORKS
file_put_contents('output/cli-from.txt',$data['From']. "\r\n", FILE_APPEND);
file_put_contents('output/cli-to.txt',$data['To']. "\r\n", FILE_APPEND);
// file_put_contents('json-sysid-local.txt',$systemid . "\r\n", FILE_APPEND);
Here is the contents of data.json
{"action":"call-data-record",
"System":"48130b83e2232f0ecd366a92d4d1261d",
"PrimaryCallID":"n1bWEfCdHcf#MSS.MTN.CO.ZA-b2b_1",
"CallID":"0440b807#pbx",
"From":"<sip:+27722080036#xxx.co.za>",
"To":"<sip:27102850816#xxx.co.za>",
"Direction":"O",
"RemoteParty":"",
"LocalParty":"",
"TrunkName":"",
"TrunkID":"",
"Cost":"",
"CMC":"",
"Domain":"xxx.co.za",
"TimeStart":"2018-08-14 16:03:21",
"TimeConnected":"",
"TimeEnd":"2018-08-14 16:03:23",
"LocalTime":"2018-08-14 18:03:21",
"DurationHHMMSS":"0:00:00",
"Duration":"0",
"RecordLocation":"",
"RecordUsers":"",
"Type":"hunt",
"Extension":"100",
"ExtensionName":"100",
"IdleDuration":"",
"RingDuration":"2",
"HoldDuration":"0",
"IvrDuration":"0",
"AccountNumber":"400",
"IPAdr":"",
"Quality":"VQSessionReport: CallTerm\r\nLocalMetrics:\r\nCallID:0440b807#pbx\r\nFromID:<sip:27102850816#xxx.co.za>\r\nToID:<sip:+27722080036#xxxx.co.za>;tag=1460166964\r\nx-UserAgent:Vodia-PBX/57.0\r\nx-SIPmetrics:SVA=RG SRD=91\r\nx-SIPterm:SDC=OK SDR=OR\r\n"}
Your "To" data is encapsulated in <>. This causes your browser to interpret it as an HTML tag and not display any content.
You can (should!) escape the special HTML control characters:
echo htmlspecialchars($data["To"]);
See http://php.net/htmlspecialchars
Edit: It doesn't hurt to precautionary add this to your other outputs aswell. If the string doesn't contain such characters, it will simply be returned onchanged. You eliminate possible XSS attack vectors this way.
The browser source clearly shows "To":"" is being written by PHP to the browser output correctly but the browser is interpreting as an HTML opening tag hence ignoring the rest of the content.
Wrap your output in the PHP htmlspecialchars() function to see the output as in the file.
Add - echo "TO : ".htmlspecialchars($data["To"]);

Trying to count characters after submitting a comment, mb_strlen gives back weird results

In my controller, I access the comment data with $this->request->data['Comment']['text']. I use CakePHP's formhelper to build the form, and a plugin called Summernote to transform the textarea into a WYSIWYG editor. I save the comment as HTML in my database.
In this case, I am trying to submit a comment with just '>'
$data = $this->request->data['Comment']['text'];
pr($data);
//returns >
pr(mb_strlen($data, utf-8));
//returns 4
pr(mb_strlen('>', utf-8));
//returns 1
//that is the one that confuses me the most,
//it seems that there's a difference between $data and '>'
mb_detect_encoding($data);
//returns ASCII
I'm already using jQuery to check the number of characters entered on the front-end, so I can deactivate the submit-button when the user goes over the limit. This uses .innerText.length and works like a charm, but if I make that the only check people can just go into the element editor and re-enable the submit button to send however long comments they like.
EDIT:
var_dump($this->request->data['Comment']['text']) gave me the following result:
Note that unlike in the examples above, I am trying to send '>>>' here
array (size=1)
'text' => string '>>>' (length=12)
EDIT:
Alex_Tartan figured out the problem: I needed to do html_entity_decode() on my string before counting it with mb_strlen()!
I've tested the case here: https://3v4l.org/VLr9e
What might be the case is an untrimmed $data (white spaces won't show up in regular print - you can use var_dump($data)).
The textarea tag will enclose formatting spaces into the value.
Check out Why is textarea filled with mysterious white spaces?
so for that, you can do:
$data = '> ';
$data = trim($data);
// var_dump(data) will output:
// string(4) "> "
echo $data."\n";
//returns >
echo mb_strlen($data, 'UTF-8')."\n";
//returns 1
echo mb_strlen('>', 'UTF-8')."\n";
//returns 1
Update (from comments):
The problem was encoded html characters which needed to be decoded:
$data = html_entity_decode($data);

remove \r\n from output

I know this question has been asked before but the answers are not the solution to my problem.
When i post a text with this code:
$info=html_entity_decode(mysql_real_escape_string($_POST['info']));
Like :
fdsa
fdsa
fasf
and when i posted this text with antered and spaces it looks like this
<?php echo $info;?>
fdsa\r\nfdsa\r\nfasf\r\n
i try this nl2br($info) but still not working.
What do I need to appear in the text in this way?
fdsa
fdsa
fasf
Replace the \r\n by <br>, the \n by <br>, then the\r by <br>:
$info = html_entity_decode($_POST['info']);
$info = str_replace('\r\n' , '<br>', $info);
$info = str_replace('\n' , '<br>', $info);
$info = str_replace('\r' , '<br>', $info);
$info = html_entities($info);
echo $info;
You have to make multiples replacements since new lines can be represented differently according to the operating system (See this page for more details)
Finally, sanitize the value with html_entities before echoing it, preventing client side attacks.
EDIT : Removed the mysql_... function, not needed (the value isn't intended to be inserted in a MySQL database, not now at least).
Also, read Lashus advice bellow and apply it ;)

PHP - Display Tags Within Tag as Text

Sorry for not being able to make the title clearer.
Basically I can type text onto my page, where all HTML-TAGS are stripped, except from a couple which I've allowed.
What I want though is to be able to type all the tags I want, to be displayed as plain text, but only if they're within 'code' tags. I'm aware I'll probably use htmlentities, but how can I do it to only affect tags within the 'code' tag?
Can it be done?
Thanks in advance guys.
For example I have $_POST['content'] which is what's shown on the web page. And is the variable with all the output I'm having problems with.
Say I post a paragraph of text, it will be echoed out with all tags stripped except for a few, including the 'code' tag.
Within the code tag I put code, such as HTML information, but this should be displayed as text. How can I escape the HTML tags to be displayed as plain text within the 'code' tag only?
Below is an example of what I may type:
Hi there, this is some text and this is a picture <img ... />.
Below I will show you the code how to do this image:
<code>
<img src="" />
</code>
Everything within the tags should be displayed as plain text so that they won't get removed from PHP's strip_tags, but only html tags within the tags.
If it's STRICTLY code tags, then it can be done quite easily.
First, explode your string by any occurences of '' or ''.
For example, the string:
Hello <code> World </code>
Should become a 4-item array: {Hello,,World!,}
Now loop through the array starting at 0 and incrementing by 4. Each element you hit, run your current script on (to remove all but the allowed tags).
Now loop through the array starting at 2 and incrementing by 4. Each element you hit, just run htmlspecialentities on it.
Implode your array, and now you have a string where anything inside the tags is completely sanitized and anything outside the tags is partially sanitized.
This is the solution I found which works perfectly for me.
Thanks everyone for their help!
function code_entities($matches) {
return str_replace($matches[1],htmlentities($matches[1]),$matches[0]);
}
$content = preg_replace_callback('/<code.*?>(.*?)<\/code>/imsu',code_entities, $_POST['content']);
Here is some sample code that should do the trick:
$parsethis = '';
$parsethis .= "Hi there, this is some text and this is a picture <img src='http://www.google.no/images/srpr/logo3w.png' />\n";
$parsethis .= "Below I will show you the code how to do this image:\n";
$parsethis .= "\n";
$parsethis .= "<code>\n";
$parsethis .= " <img src='http://www.google.no/images/srpr/logo3w.png' />\n";
$parsethis .= "</code>\n";
$pattern = '#(<code[^>]*>(.*?)</code>)#si';
$finalstring = preg_replace_callback($pattern, "handle_code_tag", $parsethis);
echo $finalstring;
function handle_code_tag($matches) {
$ret = '<pre>';
$ret .= str_replace(array('<', '>'), array('<', '>'), $matches[2]);
$ret .= '</pre>';
return $ret;
}
What it does:
First using preg_replace_callback I match all code inside <code></code sending it to my callback function handle_code_tagwhich escapes all less-than and greater-than tags inside the content. The matches array wil contain full matched string in 1 and the match for (.*?) in [2].#si` s means match . across linebrakes and i means caseinsensitive
The rendered output looks like this in my browser:

Categories