is returning div from Ajax request secure? - php

this is whats i have been using but i noticed no one else is using it, which is return HTML from ajax request.
//prepared statement
while($stmt->fetch()){
#$row .= '<div class="holder">
<div class="head">'.htmlspecialchars($head).'</div>
<div class="title">'.htmlspecialchars($title).'</div>
<div class="body">'.htmlspecialchars($body).'</div>
</div>';
}
echo json_encode(array('sucLog' => #$row));
this is what most people i see is doing. then they use jquery or Javascript to format the html
$json = new stdClass();
$json->head = $head;
$json->title = $title;
$json->body = $body;
echo json_encode($json);
am just wondering if my method is wright or not

It's not really a security issue. Both methods are used, as you've seen, but really the second method is preferable because it ensures your back-end is decoupled from your front end.
If you follow the principle of SOLID code, the S means "singe responsibility". In your example, that means the PHP code should focus on reading and writing raw data, and leave it to the presentation layer to make that look however it needs to – HTML in this case.
If you decide in the future that you want to support Apple News format, Facebook Instant Articles, etc, etc, having your back-end return pure data is a smart thing, because you can create other renderers that work with the same basic data format.
So: I would suggest you return pure data from your PHP code, then have your front-end (jQuery, React, etc) convert that to HTML.

Related

call php from ajax javascript

I have a PHP-based template website that has been heavily modified.
I am in the process of adding some RSS feeds, most of which are easy to "interpret" and display satisfactorily but one is in caps with "pre" formatting as well.
I want to modify the content. I look at all the mods I make as education and invariably am able to google satisfactory solutions to the problems I come across but, despite an earlier extensive programming background, without a thorough grounding in Javascript, Ajax, PHP, CSS and HTML, there are sometimes things that just frustrate the hell out of me.
All I want to do is pass a block of text from javascript code to PHP code, massage it and get the result back.
I am at a point in a ajax/jscript function where...
items[i].content
...contains the block of text that I want massaged and I have a piece of code that I got from here, I think, that ostensibly calls the PHP code...
function compute() {
var params="session=123";
$.post('wxspellch.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
...and, unfortunately, it isn't documented so I don't have a clue what has to be customized. All I have done so far is enter the name of my PHP script.
The PHP script is written like this...
$pspell = pspell_new('en','american','','utf-8',PSPELL_FAST);
function spellCheckWord($word) {
global $pspell;
$autocorrect = TRUE;
// Take the string match from preg_replace_callback's array
$word = $word[0];
etc......
}
function spellCheck($string) {
return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}
echo spellCheck("...... the data .......")
The PHP tests out fine with hard-coded data.
I just need to know what further customizing I have to do to the javascript and php in order to facilitate the passing and recovery of the block of text.

PHP: Using a function to print content vs returning the content as a variable and then printing that instead

I have some classes to do things for a website like get news, create a discography of recordings, gig listings etc. There are functions for listGigs(), listHeadlines() etc and these print out the relevant info to the screen.
Is there a drawback to having a function return all the html as a variable and then printing this variable later instead of printing it out directly through a function call?
If I can set up all the content for each page in generic variables e.g. $maincontent then I can call these in a html template. It seems straight forward enough, I'm just wondering if this is good practice or not. Here is the general plan of what I am talking about anyway:
in the php file
$maincontent = $news->getHeadlines;
include_once 'template.php';
in the template file
<body>
<div>Some stuff</div>
<div clas="main"><?php echo $maincontent; ?></div>
</body>
I don't see any issue with creating direct to output widgets. If you wanted to be afforded a little more flexibility though you could implement something like this
function displayTemplate($template, $data, $__captureOutput = false){
if ($__captureOutput) ob_start();
extract ($data);
include($template);
if ($__captureOutput) return ob_get_clean();
}
and for your above use case you would just do either
$maincontent = $news->getHeadlines;
displayTemplate('template.php',array("maincontent"=>$maincontent));
or
$maincontent = $news->getHeadlines;
$data = displayTemplate('template.php',array("maincontent"=>$maincontent), true);
I'd question whether even returning HTML from the function would be wise.
The drawback of having the function output HTML is you've now coupled application (domain) logic with presentation logic. Suppose you want to present the same data in a different way, such as a JSON object or raw data to write to a file. You'd either have to write additional functions for each case or write a function that will parse the HTML, extract the data from it and convert it to the format you want.
If the function does the work but only returns a PHP data structure, then you can use that output as the input to another function that implements the presentation logic.
Printing HTML directly from the function is really inflexible, and you won't even have the option to reparse it into another format.
Good software is, as a rule, loosely coupled with the various concerns separated from each other. Computation of data and presentation of data are separate concerns.

Is it bad to use html inside a php class?

is there anything wrong with using html inside a class function? I call it in the DOM so I don't need a string returned.
public function the_contact_table(){
?>
<div>
some html here
</div>
<?php
}
Also when I do need the string I use this method? Is there a better way or is this relatively standard?
public function get_single(){
ob_start();?>
<div class='staff-member single'>
<div class='col left'>
<div class='thumbnail'>
thumbnail
</div>
<?php $this->the_contact_table(); ?>
</div>
<div class='col right'>
</div>
</div>
<?php
$content = ob_get_contents();
ob_end_clean();
return $content;
}
UPDATE
I should have explained why i am doing this. I'm making a Wordpress plugin and want to control a post types output. So I am using a filter like below
public function filter_single($content){
global $post;
if ($post->post_type == 'staff-member') {
$sm = new JM_Staff_Member($post);
$content = $sm->get_single();
}
return $content;
}
So as you can see, I must return a string to the wordpress core
You should be using HEREDOC instead of output buffering if you want to store a long string into a variable. It looks like this:
$content = <<<EOD
content here
EOD;
EOD can be anything, but note two important things:
It can't have any whitespace in front of it and it must be on it's own line
It shouldn't be a string that could be found within your content
If you are using PHP >= 5.3, then you should use NOWDOC, which does not parse for variable inside the doc (unless you need this). The only different with the syntax of NOWDOC is that the sentinel is enclosed in quotes:
$content = <<<'EOD'
content here
EOD;
The reason why I'd stray away from output buffering is that it prevents the server from chunking the data sent to the client. This means that requests will seem slower because instead of the content being progressively sent to the client and displayed, it is forced to be sent all at once. Output buffering is a hack for situations when functions carelessly echo data instead of returning it or a tool for certain applications with the specific need for it. I'd also imagine that you'd take a hit on execution time if you used output buffering (because it involves function calls) versus HEREDOCing the string into a variable or including a view.
Now to answer the question about whether it is appropriate, I would say that in an MVC application all HTML and other content should be contained within its own view. Then a controller can call a view to display itself and doesn't have to worry about knowing the code involved in displaying the view. You can still pass information (like titles, authors, arrays of tags, etc.) to views, but the goal here is separating the content from the logic.
That said, Wordpress templates and code looks pretty sloppy to begin with and loosely if not at all implements MVC so if it's too much work to create a view for this, I'd say the sloppiness would fit in with WP's style.
It's not a good practice in regard to the fact that you alienate front-end developers by placing what are actually "Views" inside of PHP class files. This was one of my biggest issues when I first started using PHP in general, is that I wanted to dynamically create content within classes. It's a great idea, but you want to do it in a way that allows many members of your team to work together as smoothly as possible ;].
You should probably have the content inside of a separate file called "staff-member-single.php", which you then call in your function
public function get_single(){
ob_start();
require_once('views/staff-member-single.php');
$content = ob_get_contents();
ob_end_clean();
return $content;
}
You'd refactor that into a reusable method typically though, so it'd look a little bit like..
public function get_single()
{
$string = $this->render_view_as_string('satff-member-single');
return $string;
}
public function render_view($view)
{
require('views/'.$view.'.php');
}
public function render_view_as_string($view)
{
ob_start();
$this->render_view($view);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
I think it is good practice to use PHP only for logic of application and transmission some data to view layer (template engine). In accordance with this there are some patterns like MVC.

HTML Markup in PHP vs Javascript

I've been doing a lot of things that include making AJAX requests to get information from the backend of my site when i had an interesting question. Is it better to do the html styling in php, then send to the client, or is it better to send the data as json and then style in javascript?
Since this question is kind of vauge i'll give an example:
<?php
$data = array();
$data[0] = array("username" => "Supericy", "content" => "just a sample message 1");
$data[1] = array("username" => "Supericy", "content" => "just a sample message 2");
$data[2] = array("username" => "Supericy", "content" => "just a sample message 3");
// etc...
// now this is the choice:
if ($json)
{
return json_encode($data);
}
else
{
// or
$returnString = "";
for (...)
{
$returnString .= '<div class="username">' . $data[i]["username"] . '</div>';
$returnString .= '<div class="content">' . $data[i]["content"] . '</div>';
}
return $returnString;
}
?>
And then in my javascript:
// get the information as raw json
var data = ajax_request(json = true);
var author = document.createElement('div');
author.className = "author";
author.innerHTML = data[i]["username"];
var content = document.createElement('div');
content.className = "content";
content.innerHTML = data[i]["content"];
body.appendChild(author);
body.appendChild(content);
// -- OR --
// get the information as pre-formated html
var data = ajax_request(json = false);
body.innerHTML += data;
As other users have stated, it depends greatly on who your intended audience is. If you are trying to keep startup costs low and are developing for users who generally have a cable / constant internet connection, then you can do whatever floats your boat.
However, if you are designing application and would like it to remain relatively maintainable, you should probably look into JSON. If you do go with JSON, I would also suggest your pick up a javascript library like jQuery so that you can safely and easily handle decoding of the JSON object.
In fact, anymore, even when I am returning HTML from the AJAX page, I still wrap it in a JSON object. It seems a bit more standardized that way and I can easily reuse my previous javascript code.
Here are some basic tradeoffs:
Sending HTML Straight from PHP
HTML code is visible in the code and may be easier to find validation issues.
May be easier to maintain. (Key word MAY.) If you are generating complex html, it might be easier to build in PHP.
Sending JSON to PHP and letting Javascript Convert to HTML
Less data sent to browser. This is a big plus for mobile users who are on limited connections and pay for their bandwidth usage.
Generally more maintainable.
Lets the clients computer do the processing rather than the server (reduces server load).
Appears to be a standard format for communication with a server these days. Even Google Maps API uses JSON to interact with developers. You might even consider JSON the new XML.
By the way JSON stands for Javascript Object Notation. It follows the standard syntax for objects in javascript:
For example: var blah = {'variable_name':'variable_value'};
So my answer to you would be to use JSON, no matter what, but who your viewer is should determine how much data you are sending.
For extremely simple sites/examples it doesn't matter... for larger projects I would go with always having a json response which is more portable.
Using json makes both the server call and js view logic reusable.
JSON would be my preference. It's much easier to work with HTML properly in JavaScript, and PHP's json_encode is ever so convenient. Plus, it gives a nice, clean MVC feel.
I like back end styling because then you dont have to worry about browser compatibility (ie interent explorer).

Implementing the View in MVC or MVP (in PHP)

I've experienced first hand the extent of the horror and foot-shooting that the ugliness of PHP can cause. I'm onto my next project (you may be wondering why I'm not just switching languages but that's not why I'm here) and I've decided to try doing it right, or at least better, this time.
I've got some models defined, and I've started on a main controller. I'm at a fork in my decisions about how to implement the view. So far, the main controller can be given lists of display functions to call, and then it can spew out the whole page with one call. It looks like:
function Parse_Body()
{
foreach ($this->body_calls as $command)
{
$call = $command['call'];
if (isset($command['args'])) $call($command['args']);
else $call();
}
}
My dilemma is this:
Would it be better to have all of my display functions return the HTML they generate, so that the main controller can just echo $page; or should the display files use raw HTML outside of PHP, which gets output as soon as it's read?
With the former, the main app controller can precisely control when things get output, without just relinquishing complete control to the whim of the displays. Not to mention, all those lists of display functions to call (above) can't really be executed from a display file unless they got passed along. With the latter method, I get the benefit of doing HTML in actual HTML, instead of doing huge PHP string blocks. Plus I can just include the file to run it, instead of calling a function. So I guess with that method, a file is like a function.
Any input or advice please?
Would it be better to have all of my
display functions return the HTML they
generate, so that the main controller
can just echo $page; or should the
display files use raw HTML outside of
PHP, which gets output as soon as it's
read?
One of the advantages of php is that the processing is similar to the output:
So:
<h1> <?= $myHeading; ?> </h1>
Is more clear than:
echo "<h1>$myHeading</h1>";
An even more than:
echo heading1($myHeading); //heading1() being an hypothethical user defined function.
Based on that I consider that it is better to in the view to have HTML and and just print the appropriate dynamic fields using php.
In order to get finner control over the output you can use: ob_start as gurunu recommended.
You could of course use any of the several php MVC frameworks out there.
My prefered one, now is: Solarphp
but Zend Framework and Cakephp could help you too.
And finally if you don't want to use any framework
You could still use a pretty slim templating engine: phpSavant.
That will save you a few headaches in the development of your view.
th
You can get the benefit of both, obtaining a string of HTML while also embedding HTML within PHP code, by using the output control functions:
From the PHP manual # http://www.php.net/manual/en/ref.outcontrol.php:
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
First buffer everything. then replace tags using a parser at end of script.
<?php
$page_buffer = '';
function p($s){
global $page_buffer;
$page_buffer .= $s;
}
$page_buffer = str_replace(
array('<$content$>','<$title$>'),
array($pagecontent,$pagetitle),
$page_buffer);
echo $page_buffer;
?>
Samstyle PHP Framework implements output buffering and View model this way
And did I mention about benefits of buffering your output in a variable before "echo-ing"? http://thephpcode.blogspot.com/2009/02/php-output-buffering.html

Categories