• Unfortunately, we have experienced significant hard drive damage that requires urgent maintenance and rebuilding. The forum will be a state of read only until we install our new drives and rebuild all the configurations needed. Please follow our Facebook page for updates, we will be back up shortly! (The forum could go offline at any given time due to the nature of the failed drives whilst awaiting the upgrades.) When you see an Incapsula error, you know we are in the process of migration.

[PHP/OOP] Write content to a html file

duck you, I'm a dragon
Loyal Member
Joined
Apr 29, 2005
Messages
6,407
Reaction score
130
So this is my first try at OOP and I think I did a pretty good job, however the only thing I did was read a tutorial so I really don't have clue if I even understood the concept of classes properly, so some suggestions would be nice. Should I use more functions? More classes? Write less terrible regexes? Put on a silly hat and jump out of a window?

What does it do?

The script reads html tags from a source which have as title "pie.something" and then displays the content of those tags in a form. You can even add indicators, :text: means that the content of the tags needs to be displayed in a text area and :nocont: indicates the beginning of editable content and should be wrapped around the tags which have "pie.something" as title, this tag is mandatory.

Then if the content is edited it can be written back to the html file.

Example
The file where content gets written to is located here (Template from freetemplates):

And the actual script in action is located here:


Look at the source and you'll get how the script works.

The script
I tried to keep the commenting to a bare minimum and as I mentioned earlier on please tell me if there's something I can improve on.
PHP:
<?php
//This class generates the form.
class createform {
    
    public $index;
    
    protected function getfile() {
    
        if(($file = @file_get_contents($this->index)) == false) {
        
            die("Failed to open index file.");
        
        }
        return $file;
    }
	//This function singles out the tags that have "pie.something" as title.
    protected function get_pie_as_title() {
    
        $file = $this->getfile();
		
        //This regex matches all tags wrapped in the <div title=pie.someting:text:> tag
        preg_match("/\<div(.*?)title\=\\\"(.*?):nocont\:\\\"(.*?)\>(.*?)\<\/div\>/is", $file, $content);
        
		//The above regex isn't able to not-match the :nocont: tag therefor it needs to be stripped away.
        $content = preg_replace("/\<div(.*?)title\=\\\"(.*?):nocont:\\\"(.*?)\>/is", "", $content[0]);
        
		//This regex singles out the tags that have "pie.something" as title and puts them in an array.
        preg_match_all("/\<(.*?)title\=\\\"pie.(.*?)\\\"(.*?)>(.*?)\<\/(.*?)\>/is", $content, $matches);
		
		return $matches;
		return $file;
        
    }
	//This function generates the actual form.		
	public function create_form() {
	
		$matches = $this -> get_pie_as_title($file);
	
		echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
		
		$i = 0;
		
		while($i < count($matches[2])) {
		
			echo "".ucfirst(str_replace(":text:", "", $matches[2][$i])).":";
				
			if(strlen($matches[4][$i]) > 50 || preg_match("/:text:/", $matches[2][$i])) {
		
				$formname = $matches[2][$i];
				$formtext = $matches[4][$i];
				
				include("editor.php");
					
			} else if(!preg_match("/:nocont:/", $matches[2][$i])) {
		
				echo "<br/><input type ='text' name='".$matches[2][$i]."' value='".$matches[4][$i]."';/><br/>";
			}
			
			$i ++;
			
		}
		
		echo "<input type='submit' name='submitentry' value='Submit new entry'>";
		echo "</form>";
		
	}
}
//This child class writes the new content to the html file.
class submitcontent extends createform {

	//This function pieces the seperate tags with their new content together. 
	protected function create_new_cont() {
	
		$matches = $this -> get_pie_as_title();
		$file = $this -> getfile();
		
		$i = 0;
		
		while($i < count($matches[2])) {
		
			$form[$matches[2][$i]] = $_POST[$matches[2][$i]];
			
			//This regex singles out the tag that has $matches[2][$i] as title.
			$spattern = sprintf('#<([a-z0-9]+)[^>]title=\"%s\"[^<]*>.*</\\1>#','pie.'.$matches[2][$i].'');
															
			preg_match($spattern, $file, $tag);
			
			//'Cause I know atleast one of you bastards is going to attempt XSS.
			$newtag = preg_replace("/\>.*\</s", ">".htmlentities($form[$matches[2][$i]])."<", $tag[0]);
			
			$newcontent = "".$newcontent."
			".$newtag."";
			
			$i ++;		
		}
		
		return $newcontent;
	}
	
	public function write_to_file() {
	
		$file = $this -> getfile();
		$newcontent = $this -> create_new_cont();
	
		preg_match("/\<div(.*?)title\=\\\"(.*?):nocont\:\\\"(.*?)\>/is", $file, $main);
		
		$newcontent = "".$main[0]."".$newcontent."";
		
		//This variable contains the entire source with the new content that's going to be written to the file.
		$file = preg_replace("/\<div(.*?)title\=\\\"(.*?):nocont\:\\\"(.*?)\>(.*?)\<\/div\>/is", $newcontent, $file);
		
		if(file_put_contents($this->index, stripslashes($file)) == false) {	
		
			die("Failed to write to index file.");
			
		} else {
		
			header("Location: /pielite/");
			
		}
	}
}
	
if(!isset($_POST['submitentry'])) {	
	
	$form = new createform;
	$form -> index = "index.htm";
	$form -> create_form();
	
} else {

	$scont = new submitcontent;
	$scont -> index = "index.htm";
	$scont -> write_to_file();
}
?>
 
hello
Loyal Member
Joined
Jun 24, 2004
Messages
726
Reaction score
158
Are you sure that is working perfectly ? If i remember well the function can return only one variable, unless it's an array of course.
 
duck you, I'm a dragon
Loyal Member
Joined
Apr 29, 2005
Messages
6,407
Reaction score
130
Well I'm not getting any error messages and it seems to work perfectly as you can see people seem to enjoy them selves with the editor.
 
Custom Title Activated
Loyal Member
Joined
Jun 28, 2007
Messages
2,986
Reaction score
3
Looks al right, but you should be aware that whenever a return is met, the function will end immediatly and will return only that value. Anthing after the return will not be executed.

Also, why did you extend the previous class? Extending would be used whenever you have a base class and want to derive from that class. The base class would give base functions (and mostly private functions) which should not be used by the developer (you in this case) as an object, while extended classes would make the base class specific for one purpose. It would extend the functionality and serve one sort of goal.

Think of a base class as a script that will receive data from the internet. With each connection a different protocol would be used (HTTP, FTP, etc). For each protocol you would make a class, but to prevent duplicated code (such as creating a socket, handling user input w/e) you extend them from a base class. The idea is that one can use an extended class without knowing which one he picked, he would simply call open_connection(), or send_message() no matter what derived class is used, since all those protocol classes should provide the same function with specific instructions for that certain goal.

Oops, bit lengthy :p

Also, this is probably over-looked, but will mention it anyways:
PHP:
echo "".$blablabla...
->
PHP:
echo $blablabla...
 
duck you, I'm a dragon
Loyal Member
Joined
Apr 29, 2005
Messages
6,407
Reaction score
130


Awesome site for tutorials.

Looks al right, but you should be aware that whenever a return is met, the function will end immediatly and will return only that value. Anthing after the return will not be executed.

Also, why did you extend the previous class? Extending would be used whenever you have a base class and want to derive from that class. The base class would give base functions (and mostly private functions) which should not be used by the developer (you in this case) as an object, while extended classes would make the base class specific for one purpose. It would extend the functionality and serve one sort of goal.

Think of a base class as a script that will receive data from the internet. With each connection a different protocol would be used (HTTP, FTP, etc). For each protocol you would make a class, but to prevent duplicated code (such as creating a socket, handling user input w/e) you extend them from a base class. The idea is that one can use an extended class without knowing which one he picked, he would simply call open_connection(), or send_message() no matter what derived class is used, since all those protocol classes should provide the same function with specific instructions for that certain goal.

Oops, bit lengthy :p

Also, this is probably over-looked, but will mention it anyways:
PHP:
echo "".$blablabla...
->
PHP:
echo $blablabla...

Hmm good point, only I thought that if I didn't extend it I wouldn't be able to use the protected functions anymore. Or should I just make them public?
 
Back
Top