Since I’ve been working with a lot of different data sources lately, I’ve found myself needing an easy to use CSV Export class. So, here it is, CSVMaker.php
This class makes it very easy to create CSV files on the fly, from any type of data. Here’s a usage example:
$CSV = new CSVMaker();
// Optionally Change the Format
$CSV->csvDelimeter = ","; // (What seperates each value in a set Foo,Bar,Etc)
$CSV->csvLine = "\n"; // (What ends one set of data - usually a new line)
$CSV->csvCapsule = '"'; // (What comes before and after each piece of data "Foo","Bar","Etc")
$CSVHeader = array();
$CSVHeader['first_name'] = "First Name";
$CSVHeader['last_name'] = "Last Name";
$CSV->createTemplate($CSVHeader);
$CSVLine = array();
$CSVLine['first_name'] = "Michael";
$CSVLine['last_name'] = "Hartmayer";
$CSV->addEntry($CSVLine);
file_put_contents("MyCSVFile.csv",$CSV->buildDoc);
Here’s a quick and dirty solution I threw together to fetch how many pages of a site google has index. I needed this for one of my control panels, so my work group could track this and other metrics on the fly.
gpindex.php
<?php
// Some arbitrary access code so not everyone can access it. Not "real" security :)
if($_GET['accessCode']!="some_password") { echo "Access Denied"; exit; }
$site = $_GET['site'];
$gurl = "http://www.google.com/search?q=site:";
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,$gurl.$site);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
preg_match_all("#Results(.*)of about <b>(.*)</b> from <b>$site</b>#",$buffer,$matches,0);
echo $matches[2][0];
?>
And here’s the Ajax via jQuery that is used to fetch the information:
<script type="text/javascript" src="js/patch/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url:"http://www.example.com/path/to/gpindex.php?accessCode=some_password&site=example.com",
success:function(d){$("#googleIndexed").html(d+" Pages");}
});
});
</script>
<p style="font-size:11px;">Indexed on Google</p>
<p style="font-size:11px; font-weight:bold;" id="googleIndexed">( Fetching Data )</p>
Here’s the first ‘tutorial’-esque video that I’ve published in my new Channel Scripting for Smarties.
Enjoy~
I just recently wrote a brand new Database class to add to my PHP library. The old one was starting to get stale. This class is capable of taking advantage of the Singleton design pattern.
<?php
/**
* @author Michael Hartmayer (michaelhartmayer[at]gmail.com)
* @copyright 2009
*/
class Db {
static $ref; // Database Resource
private $user = 'root'; // Username
private $pass = ''; // Password
private $host = 'localhost'; // Host
private $db = 'test'; // Database
private $err = array(); // Error Log
private $errHalt = true; // Toggle: Halt on DB Error?
static $q; // Last Query
static $r; // Last Results
static $singleton;
public function Db() {
return true;
}//endMethod
public function getInstance() {
if(!self::$singleton)
self::$singleton = new self;
return self::$singleton;
}//endMethod
public function setUser($i) {
$this->user = $i;
return true;
}//endMethod
public function setPass($i) {
$this->pass = $i;
return true;
}//endMethod
public function setHost($i) {
$this->host = $i;
return true;
}//endMethod
public function setDb($i) {
$this->db = $i;
return true;
}//endMethod
public function setAll($h,$u,$p,$d) {
$this->host = $h;
$this->user = $u;
$this->pass = $p;
$this->db = $d;
return;
}//endMethod
public function doConnect(){
if(!empty($this->ref))
$this->doDisconnect();
if(!$this->ref = @mysql_connect($this->host,$this->user,$this->pass))
return $this->dbErr(mysql_error());
if(!@mysql_select_db($this->db,$this->ref))
return $this->dbErr(mysql_error($this->ref));
return true;
}//endMethod
public function doDisconnect() {
if(empty($this->ref)) return false;
mysql_close($this->ref);
$this->ref = null;
return true;
}//endMethod
public function getRef() {
return($this->ref);
}//endMethod
public function dbSet($q) {
$this->q = $q;
if($this->r=@mysql_query($this->q,$this->ref))
return true;
return $this->dbErr(mysql_error($this->ref));
}//endMethod
public function dbGet($q,$type='') {
switch($type) {
case 'STR':
$resultType = MYSQL_ASSOC;
break;
case 'INT':
$resultType = MYSQL_NUM;
break;
default:
$resultType = MYSQL_BOTH;
break;
}
$this->q = $q;
if(!$this->r = mysql_query($this->q,$this->ref))
return $this->dbErr(mysql_error($this->ref));
$resultArr = array();
while($makeDbArr = mysql_fetch_array($this->r,$resultType)) {
$resultArr[] = $makeDbArr;
}//endWhile
return $resultArr;
}//endMethod
public function dbCount($table, $matchPartialQuery='') {
$this->q = "SELECT COUNT(*) AS 'COUNT' FROM `$table` $matchPartialQuery;";
if($this->r = $this->dbGet($this->q))
return $this->r[0]['COUNT'];
return $this->dbErr(mysql_error($this->err));
}//endMethod
private function dbErr($err) {
if(empty($err)) return false;
$this->err[] = $err;
if($this->errHalt==true) {
echo ">> System has halted on Db Error. <br />";
echo ">> Error Log:<br /><br />";
print_r($err);
exit;
}
return err;
}//endMethod
public function strClean($str) {
return mysql_real_escape_string($str,$this->ref);
}//endMethod
}//endClass
?>
This is a really handy class I wrote that loads all your scripts Server Side so that when your page loads there aren’t so many HTTP Requests. Useful if you’re trying to load 6 different js files and 4 different style sheets, or whatever. That’s 10 requests, completely gone. Just keep in mind that it dumps all your files straight into the html document- so, as long as you don’t have a problem with that, this is a great tool.
In addition, it’s really easy to add your own script types. Check out the script for details.
( Available At: PasteBin: LoadScript Class )
Usage:
<?php
# Include Class
include_once('class.scriptloader.php');
# Instantiate
$jsLoader = new ScriptLoader('JS');
# Add Scripts
$jsLoader->addScript('my-javascript.js');
$jsLoader->addScript('jquery.js');
$jsLoader->addScript('other-scripts.js');
# Dump into Document
$jsLoader->echoScripts();
?>
On a quick note, it’d probably be a lot ‘neater’ to mod-rewrite a php file to handle at least one request per script type. That way it doesn’t all get dumped straight into the page.
Something like:
RewriteRule ^script\.(.*)$ script-loader.php?type=$1 [L]
And for script-loader.php
<?php
switch($_GET['type']) {
case 'js':
// Load all of the JavaScript files here
break;
}
?>
That way when you load something like script.js it will dump all of your java scripts into a ‘fake’ file. Just make sure to use the default $ScriptLoader->type (don’t set one when instantiating) if you are loading it from a src=”foo.bar”.
.. or something like that xD
** EDIT **
I found some problems with my code. =) Did some research on PHP’s crypt() and found out that the salt doesn’t quite work they way I had expected it to. Going to post a revision soon.
This is my version of a PHP TripCode (that I will be using for No-Mess-Enger). The way it works is, the user chooses a name, and a key. That information along with the randomly generated URI generate an integer that will eventually be used to select a random animal or something like that. This will allow users to remain anonymous while upholding the integrity of the users authenticity, in case another user tries to choose the same name.
function utilMakeTripcode($alias,$key,$uri) {
# generate tripcode
$s = crypt($alias,"$key#$uri");
$r = '';
for($i=0;$i<strlen($s);$i++) {
$r.= hexdec(substr($s,$i,1));
}
return bindec($r);
}
Example:
- User enters the Alias: Jon
- User enters the Key: SecretWord
- The TripCode Int generated is 101
At this point I can use something like this to select the users animal:
$usersAnimal = $allAnimals[$maxAnimals-$maxAnimals%$tripCodeInt];
In this example $allAnimals is an array holding every Animal name. $maxAnimals is the array size, and $tripCodeInt is the integer generated from the utilMakeTripCode() function.
So now when the user talks in Chat he might be called:
Jon the Koala
** Note **
I’ve only TESTED the function. Can’t verify that the second snippet works exactly that way. It’s more pseudo code.. so don’t hate me if it’s not quite right. ^.^
I’ve been working on some new software.. Below is a prototype version of my proprietary itemScript parser, written in PHP. The goal is to have a pseudo-scripting language available for game-items that can be read dynamically by the server, so that new items can be added without additional hard coding.
function scriptToArr($str) {
# Parse for Whitespace
$str = preg_replace("#(\r\n|\r|\n|\t|\s)#","",$str);
# Event Handlers
preg_match_all("#(.*?)\{(.*?)\}(,|)#is",$str,$findEventHandlers);
$arrEvents = array();
for($j=0;$j<sizeof($findEventHandlers[1]);$j++) {
# this event
$thisEvent = $findEventHandlers[1][$j];
# these functions
$getFunctions = $findEventHandlers[2][$j];
$allFunctions = explode(";",$getFunctions);
# get all parameters
foreach($allFunctions as $function) {
# read and parse function
preg_match("#(.+?)\((.*)\)#",$function,$functionAndPara);
$thisFunction = $functionAndPara[1];
$thisParaSet = $functionAndPara[2];
# parse and arr strings
while(preg_match("#\'(.+),(.+)\'#",$thisParaSet)) {
$thisParaSet=preg_replace("#\'(.+?),(.+?)\'#","'$1\0COMMA\0$2'",$thisParaSet);
}
$thisParaSet = explode(",",$thisParaSet);
# get each parameter
foreach($thisParaSet as $parameter) {
if($addPara = str_replace("\0COMMA\0",",",$parameter))
$arrEvents[$thisEvent][$thisFunction][] = $addPara;
}
}
}
return $arrEvents;
}
Here is a sample script I created:
onDraw {
setMana( 1, thisPlayer() );
doOtherThing( 5, thisPlayer() );
},
onExert {
sendToHand( thisTile(), thisPlayer(), x, y, z, 0 );
},
onDestroy {
setMana( 5, thisPlayer() );
}
The script then gets torn apart and dumped into a multi-dimensional array. See Screenshot.
