Is this a viable back-end for a project?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tmac25
Forum Newbie
Posts: 21
Joined: Fri Dec 28, 2012 5:24 pm

Is this a viable back-end for a project?

Post by tmac25 »

I'm currently working on a personal project of building a portal from scratch to assist in understanding php better, it's a consolidation of certain tasks I perform.

Originally, I discovered jQuery and quickly implemented it into everything I did. What I was doing before was for every task I created, I made two php scripts. The first one consisting of the actual PHP and HTML elements, the second was a parser that was used when it was called via AJAX, which quickly became very annoying to manage with the different queries and javascript on different pages, when these I started added more and more tasks. So, I consolidated a lot of the functions into a two files.

Now, my new setup is that I still have specific PHP files for the content/HTML, but the back-end now consists of an AJAX.js and AJAX.php. So, the process would be. User visits website, runs a task, which is typically an onClick residing on an HTML button, that executes a JavaScript function located in AJAX.js. The function is comprised of an ajax request sent to AJAX.PHP where the data is parsed and on success, an HTML <div> is updated to display the results on the original page. From a performance standpoint, assuming I wanted to continually scale this. Is this viable?

AJAX.js consists of all my ajax request functions and AJAX.PHP utilizes a case/switch based on a variable passed along from the AJAX.js AJAX request. To give you a visualization of these two files, I edited them a bit to make it easier to understand since some of these tasks are specific to things I'm working on.

ajax.js

Code: Select all

function task1()
{$(function(){
		var taskid=task;
			$.ajax(
				{
					url: 'inc/ajax.php?p=' + taskid,
					type: 'POST',
					data: '',
                                        success: function(html) 
					{				
					     $('#container').html(html);
					}
				});			
            });
}
ajax.php (This is just an example, typically the task will actually perform a query or run a task here.)

Code: Select all

switch($_GET['p']){
	case 'task1':{
		echo "success!";
	}
	break;

Bonus question: Any pointers on this index page I created? It uses a MySQL database where the name, file and access level is stored. This allows a dynamic page creation, where the portal will stay the same, but I can manipulate the Main <div> to display content I'd like to view based on the switch function. It also serves as access control to view certain tasks based on the user's access level.

EDIT: requinix if you read this - I just read a post by you about SQL injection and not putting "$_GET" directly into a query, I'm going to be adjusting this later tonight. :)

Code: Select all

<?php
// require_once to have HTML headers and menu wrapper.
require_once('inc/header.php');

// require_once wrapper, menu bar.
require_once('inc/wrapper.php');

// start main div.
echo "<div id='main'> ";

// sets access_level variable.
$access = $_GET['p'];

// prepares the query for access_level_control and stores it in an array.
$query = "select * from users_access_control WHERE file='$access'"; 
$result=mysqli_query($db,$query);
$row = mysqli_fetch_array($result);

// uses the above array to pull a case/switch with access_level to arrange content for website, on an access level.
if(!isset($_GET['p']))
{
?>

	<script type='text/javascript'>
		//<![CDATA[
		document.title = 'Portal';
		$(document).ready(function(){
			document.getElementById('subpagetitle').innerHTML='Main';
		});
		//]]>
	</script>

Please choose a task from the menu to the left.</br>
<?php
}
elseif($_SESSION['accesslevel'] < $row['access_level'])
{
	echo "You are not authorized to use this task."; // unauthorized message for users.
}
else
{
	require_once $_GET['p'] . ".php"; // opens the php file based on request.
}

// end main.div.
echo "</div>";

// require_once footer.
require_once("inc/footer.php"); 
?>
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Is this a viable back-end for a project?

Post by social_experiment »

I'm not sure if this is helpful but you could look at creating a class (once you have more experience) for all this;

re. the bonus question -
1. any input going to the database should be escaped, use mysqli_real_escape_string();
2. don't select * if you aren't going to use *; rather go for specific fields instead of selecting all the data and then only using certain values (disregard this if you're using all the data)

Currently even if $_GET['p'] has no value, it will be assigned to $access; this could cause problems for your script as it becomes a potential SQL injection option. isset() is to see if $_GET['p'] exists but it doesn't check if it contains a value

Code: Select all

<?php
$access = $_GET['p'];
// try something like
if (!empty($_GET['p'])) {
  // security checks ?
  $access = $_GET['p'];
}
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Is this a viable back-end for a project?

Post by Christopher »

tmac25 wrote:AJAX.js consists of all my ajax request functions and AJAX.PHP utilizes a case/switch based on a variable passed along from the AJAX.js AJAX request.
Keep going because you are one the road to learning best practices ways to solve this problem. There is no better way to learn why the right way is the right way than going through your first design and this design and a few more tries.

By the way, there is a name for the thing you described above. It is called a Front Controller (that's the pattern name). So validate you inputs form $_GET and get this code to work. Then turn the code in ajax.php into a class. After that ... Front Controller.
(#10850)
tmac25
Forum Newbie
Posts: 21
Joined: Fri Dec 28, 2012 5:24 pm

Re: Is this a viable back-end for a project?

Post by tmac25 »

Social - You're exactly right, I wasn't using everything from that query, I have changed that and implemented the a code to validate if a value is set in my $_GET. Now, I'm going to go through my user inputs to ensure that they're properly escaped.

Christopher - I keep seeing Front Controller being tossed around when I do more research, but I never got into what exactly it was. Thank you for clarifying that I sort of already stumbled into it. :P

Thank you both. :)
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Is this a viable back-end for a project?

Post by s.dot »

This is a very common way for data to be processed. Eventually you will find that your switch cases and file is getting too long and too many options. You will probably begin separating it out into related functions and switches (which would logically be the next step). After that, you will probably start breaking it down further for php to automatically invoke the functions you want/need based on parameters, such as in the URL or POST and group them together into objects.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
tmac25
Forum Newbie
Posts: 21
Joined: Fri Dec 28, 2012 5:24 pm

Re: Is this a viable back-end for a project?

Post by tmac25 »

s.dot wrote:This is a very common way for data to be processed. Eventually you will find that your switch cases and file is getting too long and too many options. You will probably begin separating it out into related functions and switches (which would logically be the next step). After that, you will probably start breaking it down further for php to automatically invoke the functions you want/need based on parameters, such as in the URL or POST and group them together into objects.
Ya, that's kind of the feeling I'm getting already as some of the case/switches in the ajax.php, have their own case/switches to differentiate between what data should be sent back based on the user's access level when the function is called. I've already started looking at queries that are similar so that I can roll those into functions to minimize my code.

Thanks for the post!
Post Reply