Never been to DZone Snippets 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

« Newer Snippets
Older Snippets »
Showing 11-20 of 330 total

Use the current filename as the HTML body id

// Makes the body id = the current filename - extension
// Useful while working on static markup that relies on styles/scripts targeting the current page

<?php
	$page = $_SERVER['PHP_SELF'];
	$page = str_replace("/","",$page);
	$page = str_replace(".php","",$page);
?>

<body id="<?php echo $page ?>">

Random password generator in PHP

A little function which generates random password of a certain length. It uses all letters, both lowercase and uppercase and all numbers.

//generates a random password which contains all letters (both uppercase and lowercase) and all numbers
function generatePassword($length) {
$password='';
for ($i=0;$i<=$length;$i++) {
	$chr='';
	switch (mt_rand(1,3)) {
		case 1:
			$chr=chr(mt_rand(48,57));
			break;
		case 2:
			$chr=chr(mt_rand(65,90));
			break;
		case 3:
			$chr=chr(mt_rand(97,122));
			
	}
	$password.=$chr;
}	
return $password;
}

Convert Code Page

// Convert from tis to utf

<?php
$content = @file_get_contents("http://www.manager.co.th/RSS/Sport/Sport.xml");
header("Content-Type: text/xml; charset=utf-8");
echo iconv('windows-874', 'utf-8', $content);
?>

Generate unique filenames in PHP

This code is from http://www.weberdev.com/get_example-3543.html.

It produces filenames similar to this: 4293d8fd-ab63-7c82.tmp

function uniqueFilename($strExt = '.tmp') {
	// explode the IP of the remote client into four parts
	$arrIp = explode('.', $_SERVER['REMOTE_ADDR']);
	// get both seconds and microseconds parts of the time
	list($usec, $sec) = explode(' ', microtime());
	// fudge the time we just got to create two 16 bit words
	$usec = (integer) ($usec * 65536);
	$sec = ((integer) $sec) & 0xFFFF;
	// fun bit--convert the remote client's IP into a 32 bit
	// hex number then tag on the time.
	// Result of this operation looks like this xxxxxxxx-xxxx-xxxx
	$strUid = sprintf("%08x-%04x-%04x", ($arrIp[0] << 24) | ($arrIp[1] << 16) | ($arrIp[2] << 8) | $arrIp[3], $sec, $usec);
	// tack on the extension and return the filename
	return $strUid . $strExt;
}

PHP redirect code (with correct header)

<?php
header ('HTTP/1.1 301 Moved Permanently');
header('Location: http://domain.com/');
exit;
?> 

[PHP] A simple error function for everyday use...

... It uses the php function "error_log".
define("PATH_LOG","./log/");

function error($line,$method,$class,$system_error,$user_error = "",$date = "",$log = true,$show = true) {
	if (empty($date)) {
		$date = date('r');
	}
	
	if (empty($user_error)) {
		$user_error = $system_error;
	}
	
	
	$error = "$date - $method at $line - $system_error\n";
	
	if ($log == true) {
		error_log($error,3,PATH_LOG."$class.log");
	}
	
	if ($show == true) {
		echo "<div class=\"error\">$user_error</div>";
	}

	return true;
}


//Example
class Test {
	private showError true;
	
	public function __construct() {
		$test = false;
		
		if ($test === false) {
			error(__LINE__,__METHOD__,__CLASS__,"sys error blub","There are internal problems. Sorry for that.","",true,$this->showError);
		}
	}
}

$test = new Test();

undo_magic_quotes and PHP 6


if(!function_exists('get_magic_quotes_gpc')) {
	// for PHP 6.x
	function get_magic_quotes_gpc() { return 0; }
}

if(get_magic_quotes_gpc()) {
	function undo_magic_quotes(&$array) {
		foreach($array as $key => $value) {
			if(is_array($value)) {
				undo_magic_quotes($array[$key]);
			} else {
				$array[$key] = stripslashes($value);
			}
		}
	}
	
	undo_magic_quotes($_GET);
	undo_magic_quotes($_POST);
	undo_magic_quotes($_COOKIE);
	undo_magic_quotes($_REQUEST);
	undo_magic_quotes($_FILES);
}



Code source magic_quotes and $_GET, $_POST, $_COOKIE, $_REQUEST ( php6 )

ZendFramework controller plugin for executing modules specific code

// This is ZF controller plugin for executing module specific code during request dispatch process.
// In this example I am setting different settings for Zend_Layout component for different modules.

class My_Controller_Plugin_ModuleSwitcher extends Zend_Controller_Plugin_Abstract
{
    private $_frontController;
    private $_moduleDirectory;
    private $_moduleName;

    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        $this->_init($request);

        $method = '_module' . ucfirst($this->_moduleName);
        if (method_exists($this, $method)) {
            $this->$method($request);
        }
    }

    private function _init(Zend_Controller_Request_Abstract $request)
    {
        $this->_moduleName = $request->getModuleName();
        $this->_frontController = Zend_Controller_Front::getInstance();
        $this->_moduleDirectory = dirname($this->_frontController->getControllerDirectory(
            $this->_moduleName));
    }

    private function _moduleWebsite(Zend_Controller_Request_Abstract $request)
    {
        Zend_Layout::startMvc(array(
            'layoutPath' => $this->_moduleDirectory . '/views/layouts',
            'layout' => 'common',
        ));
    }

    private function _moduleAdmin(Zend_Controller_Request_Abstract $request)
    {
        Zend_Layout::startMvc(array(
            'layoutPath' => $this->_moduleDirectory . '/views/layouts',
            'layout' => 'common',
        ));
    }
}

Replace text template for parameter hash table

/*

Replace text template for parameter hash table

Ex:
$mytext = 'Hi, my name is {%name%}, and my address is {%address%}';
rep_templates($mytext, array('name'=>'Steven', 'address'=>'Rua Beira Mar, 12'));
print $text; //Output: Hi, my name is Steven, and my address is Rua Beira Mar, 12

Other ex.

$row = mysql_fetch_assoc($my_result_from_query);

$mytext = file_get_contents('./text_for_email_template.txt');

tranf_dados($mytext, $row);

sendmail($row['email', 'Subject:Hi mane!', $mytext);


*/
function rep_templates(&$t, $d){
    preg_match_all ( '/{\%(\w*)\%\}/' , $t , $matches );
    foreach($matches[1] as $m){
        if($d[$m]!=null){
            $pattern = "/{\%".$m."\%\}/";
            $t = preg_replace( $pattern, $d[$m], $t);
        }
    }
}

PHP Dynamic Checkbox Table Creator (data retrieved from MySQL DB)

Hi All.
This is a function for Dynamically Create a Checbox Table retrieving information for from a MySQL Database.
As it is quite commented, it's also good for learning how this things work :)
Hope you find it useful.
Feedback is welcome.
Cheers
Dan

function dynamic_checkbox_table ($sql_str, $col_label, $col_name, $val_checked="S", $cant_cols_tbl=3){
/*
	by Daniel Neumann
	this script creates dynamically permite a table containing checkboxes 
	getting the data for the checkboxes from a MySQL DB
	$sql_str, SQL select string to retrieve data from DB (see example in last comment line)
	$col_label, DB column that has values for the checkbox label 
	$col_name, DB column that has values for the checkbox name
	$val_checked="S", value when checked (value="" attribute) it uses the same value for all of them. If you whish to use a dynamic value from a DB, you should comment the line (it´s explained next to the code in the middle of the function) and de-comment the other line (check the code,. you'll understand what I mean). Also, you should use this parameter to specify the column name for the values
	$cant_cols_tbl=3, quantity of columns for the table, it defaults to 3
	usage example: dynamic_checkbox_table("SELECT * FROM keywords", "Keyword", "ID_Keywrd");
*/
	
	//connect DB and run query
	$db="MyDB";
	$db_user="MyUser";
	$pass="MyPass";
	$host="localhost";
	@mysql_connect($host,$db_user,$pass);
	@mysql_select_db($db) or die ("cannot connect to DB");
	$q_resultado = mysql_query($sql_str);
	mysql_close();
	if (mysql_num_rows($q_resultado)==0) exit("no rows returned");
	
	$next_row = mysql_fetch_array($q_resultado); //fetch first row
	
	$output = "<table  border=\"1\">\n"; //open table tag
	do {
		$output .= "<tr>\n"; //open row tag
		for ($i=1 ; $i <= $cant_cols_tbl ; $i++ ){ //loops as many times as $cant_cols_tbl
			$row=$next_row; //assign $row, next row will be checking next one, that avoids starting a new row when it's gonna be empty
			$output .= "<td>"; //open TD tag
			$output .= (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$val_checked.'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should comment this line if you whish to use dynamic $val_checked****)
//			echo (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$row[$val_checked].'" />'.$row[$col_label]; //create checkbox and data from $row (**** you should de-comment this line if you whish to use dynamic $val_checked****)
			$next_row = mysql_fetch_array($q_resultado); //retrieve next row
			$output .= "</td>\n"; //close TD
		} //close for loop
		$output .= "</tr>\n"; //close row
	} while ($next_row); //close do-while (and checks if there's another row)
	$output .= "</table>\n"; //close table
	return $output; 
}
« Newer Snippets
Older Snippets »
Showing 11-20 of 330 total