Stefano Mtangoo 455 Senior Poster

I gave you simplest way without including any file. Just Add that div in html template file, let say {%right_content%} with all necessary css/JS. Then add this line to replace with contents of the database

<?php 
    
    $layout = new HTemplate("layout.tpl");
    $layout->set("right_content", getContentRight($id));
    echo $layout->render();

?>

So what is wrong with this?

Stefano Mtangoo 455 Senior Poster

What I'm saying is your replacing a {@body} with $body in a template, I'm not calling a template.

Take a look, the call to getContentRight is in my so called "template" file.

<div class='col-right'><? echo $page->getContentRight($page->id); ?></div>
//
// Example
//
public function getContentRight($id){
	global $mysqli;
		
	$sql = "SELECT bodyRight FROM pages WHERE id = '{$id}' LIMIT 1";
		
	if($result = $mysqli->query($sql)){
			
		$row = $result->fetch_object();
		$str = $row->bodyRight;
			
	$this->content = preg_replace_callback("/\{include %(.*?)\%}/",
function($m) {
  	return file_get_contents(CORE . 'includes/' .$m[1]);
	 }, $str);
			
	}
		
	return $this->content;
}

what do you want to achieve?

Stefano Mtangoo 455 Senior Poster

I looked at your code, but what I'm doing is completely different. Your are setting values using php manually. I'm getting the text from the database dynamically so I don't know what that value will be. Nor do i know if that value will be in the text.

did you see this?

<?php 
    
    $layout = new HTemplate("layout.tpl");
    $layout->set("title", $id);
    $layout->set("heading", $heading);
    $layout->set("body", $body);

    echo $layout->render();

?>

did you ask yourself where do variables $id, $heading and $body are coming from?

Stefano Mtangoo 455 Senior Poster

don't include file names. Iam also in process of writing themeing engine for my application wanna be. Here is what I have so far. I want to make ang engine like Joomla's where one can drop the folder and add stuffs in a panel. Those are advanced stuffs and I have reserved them for a while. Take a look here

Stefano Mtangoo 455 Senior Poster

Are you trying to make a template class?

Stefano Mtangoo 455 Senior Poster

How would this work if I don't know what will between the {%%}.

whatever will be between {% and %} will be considered as file name. That will be a syntax to be adhered!

Stefano Mtangoo 455 Senior Poster

Don't bring up old thread, start a new one!

Stefano Mtangoo 455 Senior Poster

Have a look at the Zend ACL implementations, I think they're similar to what you'll ultimately end up with, even if they only inspire whatever you create. http://framework.zend.com/manual/en/zend.acl.introduction.html

One of the most advanced acl systems I have worked with was built with Zend's ACL at its foundation, but added some layers of functionality on top. Hence my use of their terms.

It seems Zend and CakePHP are the only framework that are famous AFA framework is concerned.
I will check that!

Stefano Mtangoo 455 Senior Poster

great comment again!
Thanks. Let me do something and I will be back!

Stefano Mtangoo 455 Senior Poster

All I would suggest for you is that: Since you use JQuery, then go for JQueryUIwhich makes code cleaner and simpler taking care of nasty processing fro you!

Stefano Mtangoo 455 Senior Poster

Please don't bump old threads as I am sure this has been fixed in PHP 5.3.*

Genius bump-er hunter ;)

Stefano Mtangoo 455 Senior Poster

theres only one problem in the comment box given by naveen
whenever you refresh it..
it resubmits the form...
is there any way to fix it?
please help..

I hope the second one is me ;)
BTW Add page redirection after comment is successfully sent!

Stefano Mtangoo 455 Senior Poster
Stefano Mtangoo 455 Senior Poster

the best syntax will be {%filename%} then where simple str_replace will do a job

$temp_file = "{%news%}"; //here you have it
$file_name = str_replace(array("{%", "%}"),array("", ""), $temp_file);
include $file_name.".php";
Stefano Mtangoo 455 Senior Poster

I think it is JS question than PHP. BTW, why don't you organize your JS code into finctions in single file and just call those functions? Your code is a mess and hard to read. May be post the relevant lines only!

Stefano Mtangoo 455 Senior Poster

Hi mschroeder,
how do you see this class here? Is it a good way?
I hope no problem with copyrights since it is open and I have linked the source

/**
 * DooAcl class file.
 *
 * @author Leng Sheng Hong <darkredz@gmail.com>
 * @link http://www.doophp.com/
 * @copyright Copyright &copy; 2009 Leng Sheng Hong
 * @license http://www.doophp.com/license
 */

/**
 * Provides Access Control List feature to the application.
 *
 * <p>DooAcl performs authorization checks for the specified resource and action. It checks against the rules defined in acl.conf.php.</p>
 * <p>Only when the user is allowed by one of the rules, will he be able to access the action.
 * If the user role cannot be found in both deny and allow list, he will not be able to access the action/resource</p>
 *
 * <p>Rules has to be defined in this way:</p>
 * <code>
 * # Allow member to access all actions in Sns and Blog resource.
 * $acl['member']['allow'] = array(
 *             'SnsController'=>'*',
 *             'BlogController'=>'*',
 *          );
 *
 * # Allow anonymous visitors for Blog index only.
 * $acl['anonymous']['allow'] = array(
 *             'BlogController'=>'index',
 *          );
 *
 * # Deny member from banUser, showVipHome, etc.
 * $acl['member']['deny'] = array(
 *             'SnsController'=>array('banUser', 'showVipHome'),
 *             'BlogController' =>array('deleteComment', 'writePost')
 *          );
 *
 * # Admin can access all except Sns showVipHome
 * $acl['admin']['allow'] = '*';
 * $acl['admin']['deny'] = array(
 *             'SnsController'=>array('showVipHome')
 *          );
 *
 * # If member is denied, reroute to the following routes.
 * …
Stefano Mtangoo 455 Senior Poster

In terms of an acl you often have the following entities, Users, Roles, Resources and Privileges. Of course everyone will have their own words for each thing but this is how I would define each for the rest of this post.

User - The Person
Role - The group 1 or more persons are in
Resources - A Noun e.g. newsletter, report, post, etc.
Privileges - The Actions e.g. edit, delete, create, view etc.

So when I have seen acl's applied to the routing it is usually handled in the FrontController via a plugin before the route is dispatched to a controller and action. Which seems to be how want it to function anyways. When this is implemented in this way, generally the Resources is in the pattern of Module.Controller.Action or Module-Controller-Action etc. and the FrontController is looking for a specific Privilege, such as view or access.

The nice thing about this naming convention is it allows you to control access at a granular or broad range. Your frontcontroller would first check the module only, than the module.controller and finally the module.controller.action.

So instead of having to enter records for every action in your system you could simple add the resource admin (admin module) with the access, view etc privilege to the user role admin.

The only thing to keep in mind is by default all users to your site either need a guest role, until they sign in, which allows access to things like login/logout controllers/actions …

Stefano Mtangoo 455 Senior Poster

Hi,
Have you heard of Simple XML? It is nice way to deal with XML
Using SimpleXML, File Upload and Little HTML is enough to make simple GUI for task like the attached image. You can add DB support but it can be done without any database interaction.

Stefano Mtangoo 455 Senior Poster

The admin should be logged in, I am assuming. So in your 'groups' or 'users' you could have a field, something like boolean isAdmin(), or isSuperUser() or, isNormalUser()

this will work with fixed groups (which I will implement if my theoretical solution I'm seeking will fail) but I want something arbitrary. Admin can create a role and assign tasks. So the tasks as well as groups (names and number of them) are theoretically unlimited. So I want to do something like

bool ACL::HasPermission(TaskObjectOrWhateverYouCallIt, UserGroup);

and use it to check permissions. I can get user group from login credentials no problem. Issue is on how Do I list Controllers/Tasks user is limited to (whitelist).

and set that field when they log in. Then when coding, base your displays (because if they are not admin, they should not be able to even see a delete button) on one (or all) of those values that you have stored in either the session or 'user' class that you are using.

I want to limit access in controller level not view. I want to do all limitations in Front Controller (index.php) using specific ACL object. I will have one page for permission denied eg. PermissionDeniedController where user will be redirected when tried to access restricted resource. Else he should proceed executing the controller he have requested

alternatively, if you use classes make a separate 'user', and 'admin' class and only make such functionality available to admin, it can even extend the user class.

Problem …

Stefano Mtangoo 455 Senior Poster
Stefano Mtangoo 455 Senior Poster

Hi,
I want to write ACL. The access groups and access tasks are arbitrary. That means that any group can be given any access and initially accesses and groups are unknown. Creating groups is easy but I have hit a wall on how do I create/Implement limiting the tasks.

Example: Admin group only should be able to delete users. Now the task will be delete user and group permitted is admin but I cannot currently understand how the concept works to limit only admins to access this task.
I use MVC pattern if that is of help.
Thanks!

EDIT:
What I need is how do I limit some controllers and/or methods to given groups?

Stefano Mtangoo 455 Senior Poster

does the form with element id exists? Mixing html and php makes it messy
check if form have element with name id

Stefano Mtangoo 455 Senior Poster

thanks pritaeas, but i don't like urlencode :D maybe is some other option to escape % like an escape char \% ?

What about encoding whole url part after 1411 with base64encode

Stefano Mtangoo 455 Senior Poster

Do you mean formatting like ckeditor? no.

Then strip off all <xxx> </xxx> tags and leave only plain text. you are safe with no tag!

Stefano Mtangoo 455 Senior Poster

Writing MVC?
I always redirect whole url into index.php and slice and rewrite it using PHP. I will be also watching for a solution but few days ago there was a discussion on like subject, .htaccesss

Stefano Mtangoo 455 Senior Poster

Thanks evstevemd and ajbest!
I really don't realize that the submit command.
Pity me..
Thanks so much for both of you.. :)

you are welcome!

Stefano Mtangoo 455 Senior Poster

More or less the following code are safe from XXS attack right? Assuming I change the form action to send_email.php

send_email.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<?php
$kepada=$_GET["kepada"];
$nama = $_GET["nama"];
$email = $_GET["email"];
$subjek = $_GET["subjek"];
$comments = $_GET["comments"];
?> 
 
<?php
// using htmlentities

$newkepada= htmlspecialchars($kepada, ENT_QUOTES);
$newnama= htmlspecialchars($nama, ENT_QUOTES);
$newemail = htmlspecialchars($email, ENT_QUOTES);
$newsubjek = htmlspecialchars($subjek, ENT_QUOTES);
$newcomments = htmlspecialchars($comments, ENT_QUOTES); 
 
?> 
 
<h1>Demo Send Email</h1>
<hr>
Kepada : <?php echo $kepada; ?>
Subject : <?php echo $subjek; ?>
Pesan : <?php echo $pesan; ?>
Dari : <?php echo $dari; ?>
<br />
<?php
ini_set("SMTP", "172.16.1.1");
ini_set("sendmail_from", "$email");
mail("$kepada", "$subjek", "$comments");
?>

Telah dilakukan!

</body>
</html>

Do email need to have formatting or not?

Stefano Mtangoo 455 Senior Poster

Guyz thank You very much for trying to solve my problem...
but i spent too much time to solve this problem but unforunately i m not able to do it.......
now finally i will deloy my sql database to mysql then i will use it...
Thanks again for giving me time....
Regards..
Farhad

Just an advice:
If you use mysql_** you will have to rewrite all lines with new db eg pg_** and migration is hard. If you use PDO, you will only have to change one string and the whole code stays intact. So I will say go for PDO.
BTW don't forget closing the thread! Mark it solved!

Stefano Mtangoo 455 Senior Poster

I'm unsure if I understand you correctly, but INSERT allows multiple rows to be added to your DB:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

This is straight from the MySQL manual.

As I see it, you need to pull the $_POST variables from your form, sanitize them with something like mysql_real_escape_string() while giving them an array item.

//LATER
Having re-read your post, you seem to have repeat form fields with no unique or array names. They will overwrite each other by the time the $_POST variable arrives. Do this:

<input type="text" name="task[]" value="..." />

This will turn your $_POST variable into an array of task values.

Your form handler with then process this via a loop (while or foreach - whichever you prefer) which can build an SQL snippet to add to your main statement.

...
$task = $_POST['task'];
$projecttitle = $_POST['title'];
...
addNewProject($projecttitle,$task);
...
function addNewProject($projecttitle, $task) {
   foreach($task as $t){
      $snippet .= ",('" . mysql_real_escape_string($projecttitle) . "," . mysql_real_escape_string($t) . ")"; 
   }
   $snippet = substr($snippet,1); //just takes off the leading comma
   $q = "INSERT INTO projects (project_title, task_title)  VALUES $snippet";
   return mysql_query($q, $this->connection);
}
...

However, this is wasteful and not 'normalized'. You should have a projects table and a tasks table:

projects
======
project_id (PK, autoincrement, int)
project_title (varchar)

tasks
====
task_id (PK, autoincrement)
project_id (FK, int)
task_title (varchar)

You should add a project to the projects table. Use the mysql_insert_id() to get the project_id so it can be used in the sql loop:

...
$task = …
Stefano Mtangoo 455 Senior Poster

PDO makes migration between database nicer. Check this thread for installing driver and PHP Manual entry

Stefano Mtangoo 455 Senior Poster

mark it solved :)

Stefano Mtangoo 455 Senior Poster

Hi,
I know you have not asked this but mysql_** is depricating and you are advised to move to mysqli or the PDO. I suggest PDO due to portability and easy. If you know OOP it is extremely easy. you can use this as skeleton to get started with PDO. Copy test and play around to fit your needs

<html>
<head>

</head>
<body>
<?php
    ini_set("display_errors", 1);//error mgt
    try{
        $db = new PDO("mysql:host=localhost;dbname=test", "root", "root");
    }catch(PDOException $e){        
        echo $e->getMessage();
    }
    
    $stmt=$db->prepare("INSERT INTO likesys(liked) VALUES(:like)");
    $stmt2=$db->prepare("SELECT SUM(liked) AS likes FROM likesys WHERE liked=:like");
    $display=false;
    if(isset($_POST["like"])){
        $stmt->execute(array(":like"=>"1")); 
        $display=true;
    }
    if(isset($_POST["dislike"])){
        $stmt->execute(array(":like"=>"-1")); 
        $display=true;
    }
    $stmt->closeCursor();
    
    //if($display){ 
        $stmt2->execute(array(":like"=>"1"));
        $res = $stmt2->fetch(PDO::FETCH_ASSOC);  
        echo "<p>Likes: ". $res['likes']."</p>";
        
        $stmt2->execute(array(":like"=>"-1"));
        $res = $stmt2->fetch(PDO::FETCH_ASSOC);  
        echo "<p>Dislikes: ". abs($res['likes'])."</p>";
   // }
    
    $db=null;
?>
    <form action=<?php echo $_SERVER["PHP_SELF"];?> method="POST" >
        <input name="like" type="submit" value="Like" />
        <input name="dislike" type="submit" value="Dislike" />
    </form>
</body>
</html>
Stefano Mtangoo 455 Senior Poster

Hi,

Thanks. I watched the videos related to phpBB posted by Alex. I found "Login Integration video" not "Registration Integration". For my case, I want to make my registration form to insert the data in both the website user's table and the forum user's table so that users can login to both the website and forum with the same username and password.

Thanks.

Why re-invert the wheel? Let the people register via PHPBB and just deal with login. Making two tables to serve the same thing is completely unnecessary IMHO

Stefano Mtangoo 455 Senior Poster

Opened up mysql in cmd and noticed that the Staff table wasn't being created and data was not being inserted.

I checked the pdo connection to the database and realised i had missed db_name= out before the database name 'library_db' which is what the cause was xD

Thanks for all of the help :)

Mark it solved then!

Stefano Mtangoo 455 Senior Poster

I just changed the entire path to the folder where the pictures are uploaded. Didn't think it liked the ENTIRE path... so yah, that's it! I rather not use config because I'm not so good or experienced with that... But thanks for all the help on the post! Really appreciate it guys!

J

:)

Stefano Mtangoo 455 Senior Poster

you didn't tell us what helped you. BTW here is alternative to putting config in root dir. Just an idea
I have just given an Idea, it is not supposed to be copy and paste. For more info read comments.

<?php
/*Conf.php must have fields defining the full path of application
* something like $conf["base_url"]="http://example.com/site/";
* Since the config is global by just including file (config.php) then 
* you dont need to store full path in database. Path can be http or C:\\something\\server\\public_html
* to make things more easier you can add to config array the images path something like
* $conf["img_url"]="http://example.com/site/images/";
*/
session_start();
include $conf["base_url"]."include/config.php";
$pic_id = $_SESSION["profile_img"];
$img_path = $conf["base_url"].$pic_id;
echo "<img alt='Profile Image' src='$img_path' />";
?>
Stefano Mtangoo 455 Senior Poster

learn to indent your codes for readability (see my code above)

Stefano Mtangoo 455 Senior Poster
<?php
$data = mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT $x, 3") or die(mysql_error());

while($info = mysql_fetch_array( $data )){
echo 
"<div id='containing'>s
    <h1>".$info['contents']."</h1>
    <div id='parent'> 
        <p >".$info['author'] ."</p>
    </div>
</div>";

echo "<a href='$info['contents'].php' >READ MORE</a>"; 
}
?>
Stefano Mtangoo 455 Senior Poster

Just tried that code and it has returned that the PDO statement is false so the query isn't working, any ideas why?

Is it that the query is wrong or could the db connection not be working?

Thanks for the help.

From PHP Manual
PDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:

So do

foreach($dbh->errorInfo() as $key=>$info){
echo "error: ".$key." ".$info."<br />";
}
Stefano Mtangoo 455 Senior Poster

have you checked $stmt = $dbh->query($sql); does not return false?
try something like this

$stmt = $dbh->query($sql);
if(!$stmt){
die("PDO Statement is false!");
}else{
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//work with your resultset here
}

PDO::query() returns a PDOStatement object, or FALSE on failure.

Stefano Mtangoo 455 Senior Poster

Hi,

I am using PHPBB for my forum. My intention is if someone registers to my website, he/she will be login to forum as well, automatically. That means no need to register twice to use the forum. Is there a way forward to achieve this?
Will greatly appreciate your suggestions.
Thanks

Alex have made a video for that

Stefano Mtangoo 455 Senior Poster

you can do is put the config file on root dir of your project (Not root of your web se) and put something like

define("DS", DIRECTORY_SEPARATOR);
define("BASE_PATH", dirname(realpath(__FILE__)).DS);
define("IMG_PATH", BASE_PATH."images".DS);

then include this file in the profile file and then with picture name in session thne

$pic  = IMG_PATH.$_SESSION['pic_location'];
echo $pic;

I use in MVC so it might need little polish to be used in your project but it should not be that hard!

Stefano Mtangoo 455 Senior Poster

What I would do is:
I will store the full path in config file and store filename in session then I will simply concatenate the two!

Stefano Mtangoo 455 Senior Poster

why do you do this?

$explodedPath = explode("C:/xampp/htdocs/avatars" , $_SESSION['pic_location']);
echo '<img src="http://[localhost]'.$explodedPath[1].'" />';
Stefano Mtangoo 455 Senior Poster

so what so far is not working?

Stefano Mtangoo 455 Senior Poster

This is a matter of personal preference on whether to store the full file path in the db or to just store the file name. I generally like to only store the file name because if I later decide that I want the folder to be located somewhere else I wont have to go back in and fix all the links in the db. Furthermore, If I access the image from different pages in different locations in my file structure I dont have to try and correct the path to make it correctly relative to the document. If this were my script I would use this for the storage;

This is the good way! Don't store full path. You can store folder path to images in config file and retrieve it from there (A technique common in frameworks but will do great help here too)

Stefano Mtangoo 455 Senior Poster

this minimal code works for me (DB thing removed, assuming they are not the issue)

<?php

if (isset($_SESSION['uid']) && $_SESSION['uid']) {
    echo "You are already logged in, if you wish to log out, please <a href=\"./logout.php\">click here</a>!\n";
} else {

    if (!$_POST['submit']) {
	?>
		<table border=0 cellspacing=3 cellpadding=3>
		<form method='post' action=<?php echo $_SERVER['PHP_SELF'];?>>
		<tr><td>Username</td><td><input type='text' name='username'></td></tr>
		<tr><td>Password</td><td><input type='password' name='password'></td></tr>
		<tr><td colspan=2 align='right'><input type='submit' name='submit' value='Login'></td></tr>
		</form></table>
		
		<?php
    }else {
		$user = $_POST['username'];
		$pass = $_POST['password'];
		print_r($_POST);
		die();
			
	}

}
?>
Stefano Mtangoo 455 Senior Poster

Since you are beginning, it is better you forget mysql_** and use mysqli or the more portable PDO. I would recommend PDO after reading several threads and try it out. Here is a workig script I did for a thread in this forum:

change username password and db to match yours

<html>
<head>

</head>
<body>
<?php
    ini_set("display_errors", 1);//error mgt
    try{
        $db = new PDO("mysql:host=localhost;dbname=xxx", "xxxx", "xxxx");
    }catch(PDOException $e){        
        echo $e->getMessage();
    }
    
    $stmt=$db->prepare("INSERT INTO likesys(liked) VALUES(:like)");
    $stmt2=$db->prepare("SELECT SUM(liked) AS likes FROM likesys WHERE liked=:like");
    $display=false;
    if(isset($_POST["like"])){
        $stmt->execute(array(":like"=>"1")); 
        $display=true;
    }
    if(isset($_POST["dislike"])){
        $stmt->execute(array(":like"=>"-1")); 
        $display=true;
    }
    $stmt->closeCursor();
    
    //if($display){ 
        $stmt2->execute(array(":like"=>"1"));
        $res = $stmt2->fetch(PDO::FETCH_ASSOC);  
        echo "<p>Likes: ". $res['likes']."</p>";
        
        $stmt2->execute(array(":like"=>"-1"));
        $res = $stmt2->fetch(PDO::FETCH_ASSOC);  
        echo "<p>Dislikes: ". abs($res['likes'])."</p>";
   // }
    
    $db=null;
?>
    <form action=<?php echo $_SERVER["PHP_SELF"];?> method="POST" >
        <input name="like" type="submit" value="Like" />
        <input name="dislike" type="submit" value="Dislike" />
    </form>
</body>
</html>
Stefano Mtangoo 455 Senior Poster

for PHP I suggest W3Schools. I also love Videos from Youtube user PHPAcademy plus my favorite PHP 101
As for JavaScript I think w3Schools is enough! For JQuery just start with their home page. Also Check JQuery From Novice to Ninja from site point.

Python have tons of free books out there: Thinking Python, Dive into Python, A Byte of Python et al. Also the official Pytutorial is wonderful!

Stefano Mtangoo 455 Senior Poster

no magic follow security rules. here is one of them concerning the question:

Before putting user input in HTML output, ALWAYS CONVERT control chars to HTML entities. This protects against cross-site scripting (XSS) or messing up your output with custom HTML

Source:
I would add to that, since it is a form, then limit HTML tags to a fixed list (bold Italic et al look at stack overflow comments) and then filter out anything else. That is, you have a whitelist and discard any other tag as invalid. you can use BB code also and convert BB tag to HTML on your server side script. Just note the rule above and choose your own remedy!