Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

PHP get current file name


    $currentFile = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $currentFile);
    $currentFile = $parts[count($parts) - 1];


Credit goes to:http://php.snippetdb.com/view.php?ID=42

Time Difference

Get the difference between 2 times in PHP

$start = "09:00";
$finish = "10:30";
 
 
$tempstart=explode(":",$start);
$tempEnd=explode(":",$finish);
$tt=(($tempstart[0]*60)+$tempstart[1])+2400; 
$pp=(($tempEnd[0]*60)+$tempEnd[1]);
$difference=$tt-$pp;
$difference=$difference%2400;
$difftime=intval($difference/60).":".intval($difference%60);

PHP Bitwise Comparison

Make a bitwise comparison in php.

if(($bit_comparison & $bit) == TRUE)
{
    // do something
}

Convert an object to an associative array

// Converts a php object to an associative array

function object_to_array($data) 
{
  if(is_array($data) || is_object($data))
  {
    $result = array(); 
    foreach($data as $key => $value)
    { 
      $result[$key] = object_to_array($value); 
    }
    return $result;
  }
  return $data;
}

// insert code here..

Removing <?xml version="1.0"?> from the output of XSLTProcessor->transformToXml()

Just add this as a top level element in your XSL document.

<xsl:output method="html" />


Thanks to this post on php.net for the answer:
http://us3.php.net/manual/en/xsltprocessor.transformtoxml.php#80887

Super simple XML and PHP

This is a super simple implementation of a concept found here:
http://xtech06.usefulinc.com/schedule/paper/19

This xml class provides a very simple way to open an XML file, get information from the XML file, modify information from the XML file and save the XML file. It also supports automatic creation of new XML files based on an automatically incrementing ID senerio (similar to auto incrementing primary keys in databases).

The creation of new XML files is done by looking for a "template" xml file named 0.xml in the directory passed to the create function. If the template file is found, then it is loaded into the xml class and saved to a new file whose name is one more than the highest filename (of course the xml extension is added on). Eventually, I will try and add some validation code and whatever else, but for now I'm trying to keep things simple.

This requires the DOM module to be built into PHP.
I am using PHP 5.

If anyone has any ideas on how to improve this, feel free to post comments.

<?php

class xml
{
	var $dom;
	var $uri;

	function xml($uri)
	{
		$this->dom = new DOMDocument();

		if(preg_match('/\.xml$/', $uri))
		{
			$this->uri = $uri;
		}
		else
		{
			$this->uri = $this->create($uri);
		}
		$this->dom->load($this->uri);
	}

	function set($query, $value)
	{
		$path = new DOMXPath($this->dom);
		$nodes = $path->query($query);
		$nodes->item(0)->nodeValue = $value;
	}

	function get($query)
	{
		$path = new DOMXPath($this->dom);
		$nodes = $path->query($query);
		return $nodes->item(0)->nodeValue;
	}

	function save()
	{
		$this->dom->save($this->uri);
	}

	function create($uri)
	{
		// Build the URI of the template file.
		$template = sprintf('%s/0.xml', $uri);

		// If the directory doesn't exist, we can't really
		// do anything.
		if(!is_dir($uri))
		{
			exit('No directory');
		}

		// If the template file doesn't exist, we cannot
		// create a new file automatically.
		if(!file_exists($template))
		{
			exit('No template');
		}

		// Load the template XML into our DOMDocument.
		$this->dom->load($template);

		// Scan the directory into an array.
		$dir = scandir($uri);

		// Pull out the highest ID
		$id = str_replace('.xml', '', array_pop($dir));

		// Add one to it
		$id++;

		// Construct the new path with the new ID
		$uri = sprintf('%s/%s.xml', $uri, $id);

		// Save the new file
		$this->dom->save($uri);

		// Return the URI of the new XML file.
		return $uri;
	}
}

// The following code will create a new XML file
// under the directory /var/www/data/users.
$x = new xml('/var/www/data/users');
$x->set('//user/name', 'John Doe');
$x->save();

?>

get key value using strpos

// description of your code here

foreach($check as $key=>$val) {
               if(strpos($val,$filter_value))
               {
                    $var = $key;
               }
          }

Creating tables and inserting data on database using a file

// Creating tables and inserting data on database using a file

$filename = "database.sql";

          $filesize       = filesize($filename);
          $file_position  = isset($HTTP_GET_VARS['pos']) ? $HTTP_GET_VARS['pos'] : 0;
          $errors         = isset($HTTP_GET_VARS['ignore_errors']) ? 0 : 1;

          if (!$fp = fopen($filename,'rb')) {
               echo "Unable to open file $filename";
          }
          
          $buffer = '';
          $inside_quote = 0;
          $quote_inside = '';
          $started_query = 0;

          $data_buffer = '';

          $last_char = "\n";

          // Sets file position indicator
          fseek($fp,$file_position);

          while ((!feof($fp) || strlen($buffer))) {
               do {
                    // Deals with the length of the buffer
                    if (!strlen($buffer)) {
                         $buffer .= fread ($fp,1024);
                    }

                    // Fiddle around with the buffers
                    $current_char = $buffer[0];
                    $buffer = substr($buffer, 1);


                    if ($started_query) {
                         $data_buffer .= $current_char;
                    }  elseif (preg_match("/[A-Za-z]/i",$current_char) && $last_char == "\n")  {
                         $started_query = 1;
                         $data_buffer = $current_char;
                    } else {
                         $last_char = $current_char;
                    }
               } while (!$started_query && (!feof($fp) || strlen($buffer)));


               if ($inside_quote && $current_char == $quote_inside && $last_char != '\\') {
                    // We were inside a quote but now we aren't so reset the flag and carry on
                    $inside_quote = 0;
               
               } elseif ($current_char == '\\' && $last_char == '\\')     {
                    $current_char = '';     
               
               } elseif (!$inside_quote && ($current_char == '"' || $current_char == '`' || $current_char == '\'')) {
                    // We have just entered a new quote
                    $inside_quote = 1;
                    $quote_inside = $current_char;
               
               } elseif (!$inside_quote && $current_char == ';') {

                    // edit database
                    $db_prefix = $boardname."_".$sel_domain."_phpbb_";
                    $data_buffer = str_replace("phpbb_", "$db_prefix", $data_buffer);
                    $data_buffer = str_replace("{domain}", "$sel_domain_name", $data_buffer);
                    $data_buffer = str_replace("{path}", "$sel_domain_path", $data_buffer);                         
                    $data_buffer = str_replace("{language}", "$language", $data_buffer);
                    $data_buffer = str_replace("{boardadmin}", "$boardadmin", $data_buffer);
                    $data_buffer = str_replace("{admin_pass_md5}", "$admin_pass_md5", $data_buffer);                         
                    $data_buffer = str_replace("{email}", "$email", $data_buffer);                         
                    $data_buffer = str_replace("{timing}", "$timing", $data_buffer);
                    $data_buffer = str_replace("{boardname}", "$boardname", $data_buffer);
                    $data_buffer = str_replace("{initial_forum}", "$initial_forum", $data_buffer);
                    $data_buffer = str_replace("{initial_forum_desc}", "$initial_forum_desc", $data_buffer);
                    $data_buffer = str_replace("{initial_post_subject}", "$initial_post_subject", $data_buffer);
                    $data_buffer = str_replace("{initial_post}", "$initial_post", $data_buffer);                              
               
                    // End of query so execute query, clear data buffer and advance counter
                    mysql_query($data_buffer);

                    $data_buffer = '';
                    $last_char = "\n";
                    $started_query = 0;
               }

               $last_char = $current_char;
          }


          $new_position = ftell($fp) - strlen($buffer) - strlen($data_buffer);

          fclose($fp);

Select all tables with a certain prefix in a database and remove them

// Select all tables with a certain prefix in a database and remove them

mysql_query("SHOW TABLES LIKE '[table_prefix_here]\_%'");

#Delete Data from old database
define("TABLE_PREFIX", [table_prefix]);
define("TABLE_PREFIX_LEN", strlen(TABLE_PREFIX));

$tables = array();
$r = mysql_query("SHOW TABLES");

while (($row = mysql_fetch_row($r)) !== FALSE) {
     if (TABLE_PREFIX == substr($row[0], 0, TABLE_PREFIX_LEN)) {
          $tables[] = $row[0];
          mysql_query("DROP TABLE $row[0];");
          }
     }

Fix for EE Multi-relationship field in PHP4

// http://expressionengine.com/forums/viewreply/192755/

Open your /system/modules/weblog/mod.weblog.php file and find from this line:
    
    // -------------------------------------------
    // 'weblog_entries_tagdata' hook.

to this line:
    
    //
    // -------------------------------------------

Replace between those comments with this:

    if (isset($EXT->extensions['weblog_entries_tagdata']))
    {
        // -- PHP4 Fix For call_user_func_array not passing by reference
        global $Weblog; $Weblog = $this;
        // -- End Fix
        
        $tagdata = $EXT->call_extension('weblog_entries_tagdata', $tagdata, $row, $this);
        if ($EXT->end_script === TRUE) return $tagdata;
        
        // -- PHP4 Fix For call_user_func_array not passing by reference
        $this = $Weblog; unset($Weblog);
        // -- End Fix