Username:   Password:  

Contributo di prova foto urban

<?php
echo "all";
?>

MySQL table optimize table cron job

<?php
/**
 * Runs the query "OPTIMIZE TABLE" on each database and table
 * 
 * @author Marc Steinert <marc@bithub.net>
 * @version $Id$
 * @link http://bithub.net/
 */
 
// MySQL Data
define('SQL_HOST', '127.0.0.1');
define('SQL_USER', 'root');
define('SQL_PASS', 'xxxxxx');
 
 
$link = mysql_connect(SQL_HOST, SQL_USER, SQL_PASS);
$allDbsResult = mysql_query("SHOW DATABASES", $link);
 
while(($databaseRow = mysql_fetch_assoc($allDbsResult))) {
	// Select the found database
	mysql_select_db($databaseRow['Database'], $link);
 
	$alltablesResult = mysql_query("SHOW TABLES", $link);
 
	while (($table = mysql_fetch_assoc($alltablesResult))) {
		foreach ($table as $db => $tablename) {
 
			echo "OPTIMIZE TABLE '".$tablename."'";
 
			if (mysql_query("OPTIMIZE TABLE ".$tablename.""))
			{
				echo " - done'n";
			}
			else
			{
				echo " - failed'n";
			}
	   }
	}
}
die;
 

This script connects to a MySQL server and runs the command "optimize table" on each database and table on the MySQL server .

Tags

MySQL PHP optimize table

Simple PHP templating engine with extract

<?php
 
class Template {
 
	private $_bound = array();
 
	private $_file;
 
 
    public function __construct($tplName, $tplDir = '' ) {
        // Define template directory
        if ($tplDir == '' && defined('TEMPLATE_DIR')) {
            $tplDir = TEMPLATE_DIR;
		}
 
        // Add trailing slash
        if (substr( $tplDir, strlen($tplDir) - 1, 1 ) != '/' && $tplDir != '' ) {
            $tplDir .= '/';
		}
 
        // Get templates contents
        $this->_file = $tplDir.$tplName;
    }
 
    public function set($name, $value = null) {
        // Bind associative array
        if(is_array($name)) {
			foreach ($name as $key => $value) {
				$this->_bound[$key] = $value;
            }
        } else {
			// If instance of self then save as reference
            if ($value instanceof self) {
				$this->_bound[$name] = &$value;
			} else {
				$this->_bound[$name] = $value;
			}
        }
    }
 
    public function parse() {
        // Parse templates and bind to variables
        foreach ($this->_bound as $key => $value) {
            if ($value instanceof self) {
				$value = $value->parse();
            }
 
            $$key = $value;
        }
 
        // Start outputbuffering
        ob_start();
 
        // Include template
        if (file_exists($this->_file)) {
            require($this->_file);
        } else {
            return false;
		}
 
        // Stop buffering and get its contents
        return ob_get_clean();
    }
}

Simple template engine in PHP, which uses extract to set variables in the output. Example: $pTemplate = new Template('template.php'); $pTemplate->set('title', 'Here is a title'); echo $pTemplate->parse(); Contents of template.php: <title><?php echo $title;?></title>

Tags

PHP template extract variables templating

Check for UTF-8

<?php
/**
 * Returns true if $string is valid UTF-8 and false otherwise.
 *
 */
function is_utf8 ($string) {
	// From http://w3.org/International/questions/qa-forms-utf-8.html
	return preg_match (
		'%^(?:
              [x09x0Ax0Dx20-x7E]            # ASCII
            | [xC2-xDF][x80-xBF]             # non-overlong 2-byte
            |  xE0[xA0-xBF][x80-xBF]        # excluding overlongs
            | [xE1-xECxEExEF][x80-xBF]{2}  # straight 3-byte
            |  xED[x80-x9F][x80-xBF]        # excluding surrogates
            |  xF0[x90-xBF][x80-xBF]{2}     # planes 1-3
            | [xF1-xF3][x80-xBF]{3}          # planes 4-15
            |  xF4[x80-x8F][x80-xBF]{2}     # plane 16
        )+z%xs', $string);
}
?>

Returns true if $string is valid UTF-8 and false otherwise.

Tags

UTF-8 check php function

Filename checker

#!/usr/bin/php -q
<?php
 
/**
 * Filename checker.
 * Checks for invalid UTF-8 and/or ASCII names of files and folders,
 * as well as characters that causes issues with different operating systems.
 *
 * @author Hellkeepa
 * @link https://dl.getdropbox.com/u/228121/checkfile.php
 * @version 1.3
 * @copyright GPL v3
 */
 
// Follow links maks this deep.
define ('MAX_LEVEL', 50);
 
// Set this to true if symlinks should be followed.
define ('FOLLOW_SYMLINK', true);
 
function check_utf8 ($folder, &$count, $check = 1, $level = 0) {
	$errorlvl = 0;
	$level++;
 
	if ($level >= MAX_LEVEL) {
		echo "WARNING: $level nested levels, check for recursion.n";
		return 2;
	}
 
	if (substr ($folder, -1) != '/') {
		$folder .= '/';
	}
 
	$dh = opendir ($folder);
	while ($file = readdir($dh)) {
		if ($file == '.' || $file == '..' || $file == "proc") {
			continue;
		}
 
		if (!FOLLOW_SYMLINK && is_link ($folder.$file)) {
			echo "'$folder$file' is a symlink.... Skipping.n";
			continue;
		}
 
		if ($check & 1 && !is_utf8 ($file)) {
			$count[1]++;
			echo "UTF8: $folder$filen";
		}
 
		if ($check & 2 && !is_ascii ($file)) {
			$count[2]++;
			echo "ASCII: $folder$filen";
		}
 
		if (preg_match ('#[\/:?*<>"|]#', $file)) {
			$count[4]++;
			echo "Invalid character: $folder$filen";
		}
 
		$file = $folder.$file;
		if (is_dir ($file)) {
			if ($errorlvl = check_utf8 ($file, $count, $check, $level)) {
				return $errorlvl;
			}
 
			$count[3]++;
		} else {
			$count[0]++;
		}
	}
 
	return $errorlvl;
}
 
/**
 * Returns true if $string is valid UTF-8 and false otherwise.
 *
 * @since        1.14
 * @param [mixed] $string     string to be tested
 * @link http://no2.php.net/manual/en/function.utf8-encode.php#85866
 * @subpackage
 */
function is_utf8 ($string) {
	// From http://w3.org/International/questions/qa-forms-utf-8.html
	return preg_match (
		'%^(?:
              [x09x0Ax0Dx20-x7E]            # ASCII
            | [xC2-xDF][x80-xBF]             # non-overlong 2-byte
            |  xE0[xA0-xBF][x80-xBF]        # excluding overlongs
            | [xE1-xECxEExEF][x80-xBF]{2}  # straight 3-byte
            |  xED[x80-x9F][x80-xBF]        # excluding surrogates
            |  xF0[x90-xBF][x80-xBF]{2}     # planes 1-3
            | [xF1-xF3][x80-xBF]{3}          # planes 4-15
            |  xF4[x80-x8F][x80-xBF]{2}     # plane 16
        )+\z%xs', $string);
}
 
function is_ascii ($string) {
	return preg_match ("#^[x09x0Ax0Dx20-x7E]+\z#s", $string);
}
 
function show_usage () {
	echo "Usage: " . escapeshellcmd ($argv[0]) . " <folder> [type]nn";
	echo "  Where type is either 'ASCII', 'UTF8', or 'full',n";
	echo "  defaults to UTF-8 check only.nn";
	return 1;
}
 
if ($argc < 2) {
	echo "ERROR: Folder not specified.nn";
	return show_usage ();
}
 
if ($argc > 3) {
	echo "ERROR: Too many arguments.nn";
	return show_usage ();
}
 
// Check if scan type is selected, and make sure it's valid.
$check = 1;
if ($argc == 3) {
	switch (strtolower ($argv[2])) {
		case "both":
		case "full":
			$check = 3;
			break;
		case "ascii":
			$check = 2;
			break;
		case "utf8":
		case "unicode":
			$check = 1;
			break;
		default:
			echo "ERROR: Unknown check type.nn";
			return show_usage();
	}
}
 
// Make sure argument 1 is an existing folder.
$folder = $argv[1];
if (!is_dir ($folder)) {
	echo "ERROR: Not a folder.nn";
	return show_usage ();
}
 
// Set counters to zero, and start the check.
$count = array (0, 0, 0, 0, 0);
$retval = check_utf8 ($folder, $count, $check);
 
// Print out results.
echo <<<EOL
 
{$count[0]} files checked.
{$count[3]} folders checked.
 
EOL;
if ($check & 1) { echo "{$count[1]} invalid UTF-8 names.n"; }
if ($check & 2) { echo "{$count[2]} invalid ASCII-names.n"; }
echo "{$count[4]} filename(s) with invalid charactersnn";
 
// Return standard error level.
return $retval;
 
?>
 

Checks for invalid UTF-8 and/or ASCII names of files and folders, as well as characters that causes issues with different operating systems.

Tags

PHP file check utf-8

Url Filter Rev

class relativeUrlFilter extends sfFilter 
{
    public function execute($filterChain){
        $context  = $this->getContext();
        $request  = $context->getRequest();
 
        $relative = preg_replace('#/[^/]+.php5?$#', '', $request->getScriptName());
        $webDir = str_replace('\', '/', sfConfig::get('sf_web_dir'));
        $intercept = '/'.implode('/', array_intersect(explode('/',$relative), explode('/',$webDir)));       
        $position = strpos($webDir, $intercept);
        $request->setRelativeUrlRoot(substr($webDir, $position));                
        $filterChain->execute();
    }
}
 

[Funny Games](http://www.asgames.net)

Tags

relative url

Image Resizing class in PHP

<?php
Class Geo_Img_Resize {
 
    private $_image = null;
 
 
    function __construct($originalPath, $maxDim) {
        $this->process($originalPath, $maxDim);
    }
 
    private function process($path, $max) {
        $imageContent = file_get_contents($path);
        $image = imagecreatefromstring($imageContent);
 
        if ($image === false) {
            // Image corrupted
            return;
        }
 
        $imageHeight = imagesy($image);
        $imageWidth = imagesx($image);
 
        $newDim = null;
 
        if ($imageHeight > $imageWidth) {
            // Potrait
            $newDim = array(
                'height' => (int) $max,
                'width' =>  round($imageWidth * $max / $imageHeight)
            );
        } else {
            // Landscape
            $newDim = array(
                'height' => round($imageHeight * $max / $imageWidth),
                'width' => $max
            );
        }
 
        $newImage = imageCreateTrueColor($newDim['width'], $newDim['height']);
 
        imagecopyresized(
            $newImage, $image, 0,0,0,0,$newDim['width'],
            $newDim['height'],$imageWidth,$imageHeight
        );
 
        $this->_image = $newImage;
    }
 
    public function save($path) {
        if ($this->_image !== null) {
            imagepng($this->_image, $path);
        }
    }
 
    public function display() {
        imagepng($this->_image);
    }
}
?>

Tags

Image resize php

Replace all URLs with TinyUrls in a text

<?php
 
$text = 'foo bar http://maps.google.com/ foo http://somelongurlthatdoesntexist.com bar';
 
if (preg_match_all('|(http://[^s]+)|', $text, $matches, PREG_PATTERN_ORDER)) {
	foreach ($matches[0] as $match) {
		$text = str_replace($match, getTinyUrl($match), $text);
	}
}
echo $text;
 
function getTinyUrl($url) {
	return file_get_contents('http://tinyurl.com/api-create.php?url='.urlencode($url));
}
 
?>

Tags

tinyurl php short url

Render include file to variable

<?php
$GLOBALS['BufferedErrors']=Array();
function errorParse($errno, $errstr, $errfile, $errline, $errcontext) {
    $errorTypes = Array(
        E_ERROR => 'Fatal Error',
        E_WARNING => 'Warning',
        E_PARSE => 'Parse Error',
        E_NOTICE => 'Notice',
        E_CORE_ERROR => 'Fatal Core Error',
        E_CORE_WARNING => 'Core Warning',
        E_COMPILE_ERROR => 'Compilation Error',
        E_COMPILE_WARNING => 'Compilation Warning',
        E_USER_ERROR => 'Triggered Error',
        E_USER_WARNING => 'Triggered Warning',
        E_USER_NOTICE => 'Triggered Notice',
        E_STRICT => 'Deprecation Notice',
        E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
    );
    $ret=(object)Array(
        'number'=>$errno,
        'message'=>$errstr,
        'file'=>$errfile,
        'line'=>$errline,
        'context'=>$errcontext,
        'type'=>$errorTypes[$errno]
    );
    $GLOBALS['BufferedErrors'][]=$ret;
    return false;
}
function parse($fileToInclude, $argumentsToFile=false) {
    $bufferedErrorStack = $GLOBALS['BufferedErrors'];
    set_error_handler('errorParse', error_reporting());
    $GLOBALS['BufferedErrors']=Array();
 
    if (!file_exists($fileToInclude))
        return '';
    if ($argumentsToFile === false)
        $argumentsToFile = Array();
    $argumentsToFile = array_merge($GLOBALS, $argumentsToFile);
    foreach ($argumentsToFile as $variableName => $variableValue)
        $$variableName = $variableValue;
    ob_start();
    include($fileToInclude);
    $ret = ob_get_contents();
    ob_end_clean();
 
    restore_error_handler();
    $errors = $GLOBALS['BufferedErrors'];
    $GLOBALS['BufferedErrors'] = $bufferedErrorStack;
    if (count($errors)>0) {
        $ret.='<ul class="error">';
        foreach ($errors as $error)
            $ret.=
                '<li>'.
                    '<b>'.$error->type.'</b>: '.
                    $error->message.
                    '<blockquote>'.
                        '<i>file</i>: '.$error->file.'<br />'.
                        '<i>line</i>: '.$error->line.
                    '</blockquote>'.
                '</li>';
        $ret.='</ul>';
    }
    return $ret;
}

This script includes a PHP file - but render its output to a variable, rather than to the buffer. It's also set up to load the script with a variable set, and automagically loads globals into the script's namespace, making it an effective templating scheme. It also has error handling, so that you're not flying blind when using output buffering.

Tags

PHP ob_start buffering

Captcha

<?php
	function make_seed(){
		list($usec , $sec) = explode (' ', microtime());
		return (float) $sec + ((float) $usec * 100000);
	}
 
	function randomString($len) {	
		srand(make_seed());
 
		$possible = 'abcdefhijkmnprstuvwxyz23456789';
 
		$str = '';
		while(strlen($str)<$len) {
			$str .= substr($possible,(rand()%(strlen($possible))),1);
		}
 
		return($str);
	}
 
	session_start();
 
	unset($_SESSION['captcha_spam']);
 
	$text = randomString(5);
	$_SESSION['captcha_spam'] = $text;
 
	header('Content-type: image/png');
	$img = ImageCreateFromPNG('captcha.png');
	$color = ImageColorAllocate($img, 0, 0, 0);
	$ttf = getcwd().'/somefont.tff';
	$ttfsize = 20;
	$angle = rand(0,5);
	$t_x = rand(5,20);
	$t_y = 25;
	imagettftext($img, $ttfsize, $angle, $t_x, $t_y, $color, $ttf, $text);
	imagepng($img);
	imagedestroy($img);
?> 

Simple captcha image. captcha.png is the backround image for you captcha. "somefont.tff" is a random truetype font for the text in your captcha image.

Tags

PHP captcha

substr replacement that does not break words

function snippet($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}
 

This PHP function shortens a string without breaking words.

Tags

PHP substr replacement

Convert shortened URL back to original URL

<?php
function getNormalUrl($url) {
	$url = trim($url);
	$h = get_headers($url, true);
	return $h['Location'];
}
?>

This PHP function takes a shortened URL (ie TinyURL, bit.ly, etc) and converts it back to the original URL.

Tags

URL PHP web TinyURL bit ly

Create TinyURL with PHP

function getTinyUrl($url) {
	return file_get_contents('http://tinyurl.com/api-create.php?url='.urlencode($url));
}
 
// Example Use:
$url = 'http://google.com';
echo getTinyUrl($url);

This PHP function uses the TinyURL API to create a shorter URL.

Tags

PHP TinyURL function

Memcached wrapper for PHP

<?php
/**
 * Wrapper for storing and retrieving memcached data.
 *
 * Start memcached by running the following command:
 * memcached -d -m 1024 -u root -l 127.0.0.1 -p 11211
 * 
 */
class Cache_Main {
 
	/** @var int */
	const MEMCACHE_PORT = 11211;
 
	/** @var string */
	const MEMCACHE_HOST = '127.0.0.1';
 
	/**
	 * Standard-timeout (10 min)
	 *
	 * @var int
	 */
	const MEMCACHE_STD_TIMEOUT = 600;
 
	/** @var Memcache */
	private static $_memcache = null;
 
	/** @var Atom_Cache_Main */
	private static $_instance = null;
 
 
	private function __construct() {
		self::$_memcache = new Memcache();
 
		if (self::$_memcache->connect(self::MEMCACHE_HOST, self::MEMCACHE_PORT) === false) {
			throw new Exception('Could not connect', 0);
		}
	}
 
	/**
	 * Singleton accessor
	 *
	 * @return Atom_Cache_Main
	 */
	public static function instance() {
		if(self::$_instance == null) {
			self::$_instance = new self();
		}
 
		return self::$_instance;
	}
 
	/**
	 * Adds <code>$object</code> to the cache, accessable by  <code>$key</code>
	 *
	 * @param string $key
	 * @param mixed $object
	 * @param int $timeout Timespan the object is hold in the cache in seconds
	 */
	public function add($key, $object, $timeout = null) {
		self::$_memcache->set(
			$key,
			$object,
			false,
			($timeout === null ? self::MEMCACHE_STD_TIMEOUT : $timeout)
		);
	}
 
	/**
	 * Retrieves stored data
	 *
	 * @param string $key Identifier
	 * @return mixed Stored data by memcache
	 */
	public function get($key) {
		return self::$_memcache->get($key);
	}
}
?>

Wrapper for storing and retrieving memcached data.

Tags

memcached php

Test filename in PHP

/**
 * Tests, if given filename is valid
 *
 * @param string $filename
 * @return bool
 */
public static function isValidFilename($filename) {
	return (bool) preg_match('/^[a-z0-9_ ]{1,30}.[a-z]{1,3}$/i', $filename);
}

Tests, if a given filename is valid.

Tags

PHP files filename test verify

Extract the search term from google referer

$referer = strtolower($_SERVER['HTTP_REFERER']);
 
// Test if user comes from google
if (strpos($referer, 'google')) {
	// Delete all before &q=
    $tmp = substr($referer, strpos($referer, 'q='));		
 
    // Remove q=
	$tmp = substr($tmp, 2);
 
	// Remove everything after the next &
	if (strpos($tmp, '&')) {
		$tmp = substr($tmp, 0,strpos($tmp, '&'));
	}	
	// we have the results.
	$searchTerm = urldecode($tmp);
}

Takes the referer and extracts the search term, if user comes from google.

Tags

google php referer keyword search term

str_replace_once()

<?php
/**
 * @param string $search
 * @param string $replace
 * @param string $subject
 */
function str_replace_once($search, $replace, $subject) {
    $firstChar = strpos($subject, $search);
    if($firstChar !== false) {
        $beforeStr = substr($subject,0,$firstChar);
        $afterStr = substr($subject, $firstChar + strlen($search));
        return $beforeStr.$replace.$afterStr;
    } else {
        return $subject;
    }
}
?>

Works like str_replace() but replaces the first occurence of $search with $replace only.

Tags

str_replace php

Test if telephone number belongs to a cellphone

function isCellphoneNumber($tel) {
	// Remove all non relevant characters
	$tel = preg_replace("/[^0-9\+]/", '', $tel);
 
	$number = '';
	$countryCode = 0;
 
	if (preg_match("/^\+\d{2}/", $tel)) {
		// Number with country code with trailing +
		$countryCode = substr($tel, 1, 2);
		$number = substr($tel, 3, strlen($tel) - 3);
		$number = "00".$countryCode.$number;
	} elseif (preg_match("/^00/", $tel)) {
		// Country code present with trailing 00
		$landesVorwahl = substr($tel, 2, 2);
		$number = substr($tel, 4, strlen($tel) - 2);
		$number = "00".$landesVorwahl.$number;
	}
 
	switch ((int) $countryCode) {
		default:
		case 49: // Germany
			$netzvorwahlen = array(
					'0151', '0160',
					'0170',	'0171',	'0175',	'0151',
					'01520', '0162', '0172',	'0173',
					'0174',	'0152',	'0157',	'01570',
					'01577', '0163', '0177',	'0178',
					'0155',	'0159',	'0176', '0179'
				);
			break;
 
		case 43: // Austria
			$netzvorwahlen = array(
					'0664',
					'0676',
					'0650',
					'0699'
				);
			break;
 
		case 41: // Swiss
			$netzvorwahlen = array(
					'079',
					'076',
					'078',
					'077'
				);
			break;
 
		case 29: // Spanien
			$netzvorwahlen = array('6'); // In ESP beginnen alle Handynummern mit einer 6
			break;
	}
 
	foreach ($netzvorwahlen as $vorwahl)
	{
		$vorwahl = preg_replace("/^0/", '', $vorwahl);
 
		if (preg_match("/^00${landesVorwahl}${vorwahl}/", $nummer))
		{
			$tel = $nummer;
 
			return true;
		}
	}
 
	return false;
}
 

This function only supports cellphone numbers for the german speaking part of europe (swiss, germany, austria).

Tags

cellphone number php verify

US Area Codes PHP Array

<?php
//This is just a little array filled with all the area codes
//for each state. Useful for verifying phone numbers.
//Apologies for my screen name, I didn't want to bother registering
//for an account... But you guys helped me out alot so I felt
//like I had to give back. :)
$areacodes = array(780 => "AB",
                   403 => "AB",
                   907 => "AK",
                   205 => "AL",
                   256 => "AL",
                   334 => "AL",
                   251 => "AL",
                   870 => "AR",
                   501 => "AR",
                   479 => "AR",
                   480 => "AZ",
                   623 => "AZ",
                   928 => "AZ",
                   602 => "AZ",
                   520 => "AZ",
                   628 => "CA",
                   341 => "CA",
                   764 => "CA",
                   925 => "CA",
                   909 => "CA",
                   562 => "CA",
                   661 => "CA",
                   657 => "CA",
                   510 => "CA",
                   650 => "CA",
                   949 => "CA",
                   760 => "CA",
                   415 => "CA",
                   951 => "CA",
                   752 => "CA",
                   831 => "CA",
                   209 => "CA",
                   669 => "CA",
                   408 => "CA",
                   559 => "CA",
                   626 => "CA",
                   442 => "CA",
                   530 => "CA",
                   916 => "CA",
                   707 => "CA",
                   627 => "CA",
                   714 => "CA",
                   310 => "CA",
                   323 => "CA",
                   213 => "CA",
                   424 => "CA",
                   747 => "CA",
                   818 => "CA",
                   858 => "CA",
                   935 => "CA",
                   619 => "CA",
                   805 => "CA",
                   369 => "CA",
                   720 => "CO",
                   303 => "CO",
                   970 => "CO",
                   719 => "CO",
                   203 => "CT",
                   959 => "CT",
                   475 => "CT",
                   860 => "CT",
                   202 => "DC",
                   302 => "DE",
                   689 => "FL",
                   407 => "FL",
                   239 => "FL",
                   836 => "FL",
                   727 => "FL",
                   321 => "FL",
                   754 => "FL",
                   954 => "FL",
                   352 => "FL",
                   863 => "FL",
                   904 => "FL",
                   386 => "FL",
                   561 => "FL",
                   772 => "FL",
                   786 => "FL",
                   305 => "FL",
                   861 => "FL",
                   941 => "FL",
                   813 => "FL",
                   850 => "FL",
                   478 => "GA",
                   770 => "GA",
                   470 => "GA",
                   404 => "GA",
                   706 => "GA",
                   678 => "GA",
                   912 => "GA",
                   229 => "GA",
                   671 => "GU",
                   808 => "HI",
                   515 => "IA",
                   319 => "IA",
                   563 => "IA",
                   641 => "IA",
                   712 => "IA",
                   208 => "ID",
                   217 => "IL",
                   282 => "IL",
                   872 => "IL",
                   312 => "IL",
                   773 => "IL",
                   464 => "IL",
                   708 => "IL",
                   815 => "IL",
                   224 => "IL",
                   847 => "IL",
                   618 => "IL",
                   309 => "IL",
                   331 => "IL",
                   630 => "IL",
                   765 => "IN",
                   574 => "IN",
                   260 => "IN",
                   219 => "IN",
                   317 => "IN",
                   812 => "IN",
                   913 => "KS",
                   785 => "KS",
                   316 => "KS",
                   620 => "KS",
                   327 => "KY",
                   502 => "KY",
                   859 => "KY",
                   606 => "KY",
                   270 => "KY",
                   504 => "LA",
                   985 => "LA",
                   225 => "LA",
                   318 => "LA",
                   337 => "LA",
                   774 => "MA",
                   508 => "MA",
                   781 => "MA",
                   339 => "MA",
                   857 => "MA",
                   617 => "MA",
                   978 => "MA",
                   351 => "MA",
                   413 => "MA",
                   443 => "MD",
                   410 => "MD",
                   280 => "MD",
                   249 => "MD",
                   969 => "MD",
                   240 => "MD",
                   301 => "MD",
                   207 => "ME",
                   383 => "ME",
                   517 => "MI",
                   546 => "MI",
                   810 => "MI",
                   278 => "MI",
                   313 => "MI",
                   586 => "MI",
                   248 => "MI",
                   734 => "MI",
                   269 => "MI",
                   906 => "MI",
                   989 => "MI",
                   616 => "MI",
                   231 => "MI",
                   679 => "MI",
                   947 => "MI",
                   612 => "MN",
                   320 => "MN",
                   651 => "MN",
                   763 => "MN",
                   952 => "MN",
                   218 => "MN",
                   507 => "MN",
                   636 => "MO",
                   660 => "MO",
                   975 => "MO",
                   816 => "MO",
                   314 => "MO",
                   557 => "MO",
                   573 => "MO",
                   417 => "MO",
                   670 => "MP",
                   601 => "MS",
                   662 => "MS",
                   228 => "MS",
                   406 => "MT",
                   336 => "NC",
                   252 => "NC",
                   984 => "NC",
                   919 => "NC",
                   980 => "NC",
                   910 => "NC",
                   828 => "NC",
                   704 => "NC",
                   701 => "ND",
                   402 => "NE",
                   308 => "NE",
                   603 => "NH",
                   908 => "NJ",
                   848 => "NJ",
                   732 => "NJ",
                   551 => "NJ",
                   201 => "NJ",
                   862 => "NJ",
                   973 => "NJ",
                   609 => "NJ",
                   856 => "NJ",
                   505 => "NM",
                   957 => "NM",
                   702 => "NV",
                   775 => "NV",
                   315 => "NY",
                   518 => "NY",
                   716 => "NY",
                   585 => "NY",
                   646 => "NY",
                   347 => "NY",
                   718 => "NY",
                   212 => "NY",
                   516 => "NY",
                   917 => "NY",
                   845 => "NY",
                   631 => "NY",
                   607 => "NY",
                   914 => "NY",
                   216 => "OH",
                   330 => "OH",
                   234 => "OH",
                   567 => "OH",
                   419 => "OH",
                   380 => "OH",
                   440 => "OH",
                   740 => "OH",
                   614 => "OH",
                   283 => "OH",
                   513 => "OH",
                   937 => "OH",
                   918 => "OK",
                   580 => "OK",
                   405 => "OK",
                   503 => "OR",
                   971 => "OR",
                   541 => "OR",
                   814 => "PA",
                   717 => "PA",
                   570 => "PA",
                   358 => "PA",
                   878 => "PA",
                   835 => "PA",
                   484 => "PA",
                   610 => "PA",
                   445 => "PA",
                   267 => "PA",
                   215 => "PA",
                   724 => "PA",
                   412 => "PA",
                   939 => "PR",
                   787 => "PR",
                   401 => "RI",
                   843 => "SC",
                   864 => "SC",
                   803 => "SC",
                   605 => "SD",
                   423 => "TN",
                   865 => "TN",
                   931 => "TN",
                   615 => "TN",
                   901 => "TN",
                   731 => "TN",
                   254 => "TX",
                   325 => "TX",
                   713 => "TX",
                   940 => "TX",
                   817 => "TX",
                   430 => "TX",
                   903 => "TX",
                   806 => "TX",
                   737 => "TX",
                   512 => "TX",
                   361 => "TX",
                   210 => "TX",
                   936 => "TX",
                   409 => "TX",
                   979 => "TX",
                   972 => "TX",
                   469 => "TX",
                   214 => "TX",
                   682 => "TX",
                   832 => "TX",
                   281 => "TX",
                   830 => "TX",
                   956 => "TX",
                   432 => "TX",
                   915 => "TX",
                   435 => "UT",
                   801 => "UT",
                   385 => "UT",
                   434 => "VA",
                   804 => "VA",
                   757 => "VA",
                   703 => "VA",
                   571 => "VA",
                   540 => "VA",
                   276 => "VA",
                   381 => "VA",
                   236 => "VA",
                   802 => "VT",
                   509 => "WA",
                   360 => "WA",
                   564 => "WA",
                   206 => "WA",
                   425 => "WA",
                   253 => "WA",
                   715 => "WI",
                   920 => "WI",
                   414 => "WI",
                   262 => "WI",
                   608 => "WI",
                   353 => "WI",
                   420 => "WI",
                   304 => "WV",
                   307 => "WY");
?>

Tags

php array phone code area

Find out if string is serialized variable

<?php
 
$string = "a:0:{}";
if(preg_match("/(a|O|s|b)\x3a[0-9]*?
((\x3a((\x7b?(.+)\x7d)|(\x22(.+)\x22\x3b)))|(\x3b))/", $string))
{
echo "Serialized.";
}
else
{
echo "Not serialized.";
}
 
?>

If you need to check whether string is a serialized representation of variable(sic!) you can use this. But don't forget, string in serialized representation could be VERY big, so match work can be slow, even with fast preg_* functions.

Tags

regex PHP preg_match serialization

Create XML file from MySQL query

<?php
 
header("Content-type: text/xml");
 
$host = "localhost";
$user = "root";
$pass = "";
$database = "test";
 
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
 
$query = "SELECT * FROM blog ORDER BY date DESC";
$resultID = mysql_query($query, $linkID) or die("Data not found.");
 
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<entries>\n";
 
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
    $row = mysql_fetch_assoc($resultID);
    $xml_output .= "\t<entry>\n";
    $xml_output .= "\t\t<date>" . $row['date'] . "</date>\n";
        // Escaping illegal characters
        $row['text'] = str_replace("&", "&", $row['text']);
        $row['text'] = str_replace("<", "<", $row['text']);
        $row['text'] = str_replace(">", "&gt;", $row['text']);
        $row['text'] = str_replace("\"", "&quot;", $row['text']);
    $xml_output .= "\t\t<text>" . $row['text'] . "</text>\n";
    $xml_output .= "\t</entry>\n";
}
 
$xml_output .= "</entries>";
 
echo $xml_output;
 
?> 

Tags

PHP XML MySQL

Remove non alphanumeric characters

<?php
    $output = preg_replace('/[^[:alnum:]]/', '', $input);
?>

Replaces everything, thats not alphanumeric in a string. Note that spaces are not alphanumeric, too.

Tags

php regex preg_replace