Archive for July, 2010

WordPress PHP custom theme functions.php hook

Wednesday, July 28th, 2010

In your theme (wp-content/themes/YourNewTheme) create or find functions.php

and start making whatever you need.  It’s a nice clean place to put things without hacking away at your code,

dynamically inserting with JS, or whatever other measure you’ve either employed in the past, or are considering now…

for example,

<?php
//My own footer hook
function my_footer() {

//code to execute

?><div class=”bigText”>blah blah blah</div><?

}

?>

then, wherever you like, call your new function, example, replace all <? wp_footer(); ?> calls with, you guested it, <? my_footer(); ?>

thanks to: http://www.raymondselda.com/understanding-action-hooks-in-wordpress/

Don’t forget to include the following in your new custom theme functions.php file if you want the dynamic custom drag widget sidebar!:

if ( function_exists(‘register_sidebar’) )
register_sidebar();

reference: http://codex.wordpress.org/Widgetizing_Themes

Reference variables PHP examples: &$var simple, pass by reference to function, array of reference variables

Tuesday, July 27th, 2010

& preceeds variable

$original = “foo”;
$ref = &$original;
echo $ref; \\Prints “foo”
// now we change the value of $original
$original = “bar”;
// and then print the value of the referring variable
echo $ref; \\Now prints the new value: “bar”
source: http://www.whypad.com/posts/php-what-is-the-ampersand-preceding-variables/193/

reference variable (&variable)

<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

Basically, the argument is treated, referenced by the outside variable, as global
Without the &, it would output ‘This is a string’
source: http://php.net/manual/en/functions.arguments.php

 

An Array of Reference Variables:

// We have a bunch of variables
$var1 = 10;
$var2 = 100;
$var3 = 1000;
// Let’s put references to them all into an array. That way we can loop through them all, and edit one or all of them
$array = array(&$var1, &$var2, &$var3);
foreach($array as &$var){

if($var == 1000){

$var = 2000;

}

}
echo $var1 . “<br />”; // 10
echo $var2 . “<br />”; // 100
echo $var3 . “<br />”; // 2000

Postincrement Preincrement Postdecrement Predecrement PHP careful! ++ —

Tuesday, July 27th, 2010
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

I always like to have a nice simple AJAX example on hand, you never know…

Tuesday, July 27th, 2010

reference:

http://w3schools.com/php/php_ajax_php.asp

HTML:

<html>
<head>
<script type=”text/javascript”>
function showHint(str)
{
if (str.length==0)
{
document.getElementById(“txtHint”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”gethint.php?q=”+str,true);
xmlhttp.send();
}
</script>
</head
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type=”text” onkeyup=”showHint(this.value)” size=”20″ />
</form>
<p>Suggestions: <span id=”txtHint”></span></p>

</body>
</html>

Script:

<?php
// Fill up array with names
$a[]=”Anna”;
$a[]=”Brittany”;
$a[]=”Cinderella”;
$a[]=”Diana”;
$a[]=”Eva”;
$a[]=”Fiona”;
$a[]=”Gunda”;
$a[]=”Hege”;
$a[]=”Inga”;
$a[]=”Johanna”;
$a[]=”Kitty”;
$a[]=”Linda”;
$a[]=”Nina”;
$a[]=”Ophelia”;
$a[]=”Petunia”;
$a[]=”Amanda”;
$a[]=”Raquel”;
$a[]=”Cindy”;
$a[]=”Doris”;
$a[]=”Eve”;
$a[]=”Evita”;
$a[]=”Sunniva”;
$a[]=”Tove”;
$a[]=”Unni”;
$a[]=”Violet”;
$a[]=”Liza”;
$a[]=”Elizabeth”;
$a[]=”Ellen”;
$a[]=”Wenche”;
$a[]=”Vicky”;

//get the q parameter from URL
$q=$_GET[“q”];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint=””;
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint==””)
{
$hint=$a[$i];
}
else
{
$hint=$hint.” , “.$a[$i];
}
}
}
}

// Set output to “no suggestion” if no hint were found
// or to the correct values
if ($hint == “”)
{
$response=”no suggestion”;
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>

PHP Expat XML Parser refresher

Tuesday, July 27th, 2010

from: http://w3schools.com/php/php_xml_parser_expat.asp

example XML

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>

script to parse:

<?php
//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case “NOTE”:
echo “– Note –<br />”;
break;
case “TO”:
echo “To: “;
break;
case “FROM”:
echo “From: “;
break;
case “HEADING”:
echo “Heading: “;
break;
case “BODY”:
echo “Message: “;
}
}

//Function to use at the end of an element
function stop($parser,$element_name)
{
echo “<br />”;
}

//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}

//Specify element handler
xml_set_element_handler($parser,”start”,”stop”);

//Specify data handler
xml_set_character_data_handler($parser,”char”);

//Open XML file
$fp=fopen(“test.xml”,”r”);

//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf(“XML Error: %s at line %d”,
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}

//Free the XML parser
xml_parser_free($parser);
?>

output:

— Note —
To: Tove
From: Jani
Heading: Reminder
Message: Don’t forget me this weekend!

MySQL refresher

Tuesday, July 27th, 2010

datatypes:

http://w3schools.com/sql/sql_datatypes.asp

Order results by 2 columns:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2

Simple delete:

<?php
$con = mysql_connect(“localhost”,”peter”,”abc123″);
if (!$con)
{
die(‘Could not connect: ‘ . mysql_error());
}
mysql_select_db(“my_db”, $con);
mysql_query(“DELETE FROM Persons WHERE LastName=’Griffin'”);
mysql_close($con);
?>

PHP custom error handling, log and email and user messaging

Tuesday, July 27th, 2010

http://w3schools.com/php/php_error.asp

<?php
//error handler function
function customError($errno, $errstr)
{
echo “<b>Error:</b> [$errno] $errstr<br />”;
echo “Webmaster has been notified”;
error_log(“Error: [$errno] $errstr”,1,
“someone@example.com”,”From: webmaster@example.com”);
}

//set error handler
set_error_handler(“customError”,E_USER_WARNING);

//trigger error
$test=2;
if ($test>1)
{
trigger_error(“Value must be 1 or below”,E_USER_WARNING);
}
?>

open a file and read it line by line or character by character reference refresher

Tuesday, July 27th, 2010

from http://w3schools.com/php/php_file.asp

Reading a File Line by Line

The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.

Example

The example below reads a file line by line, until the end of file is reached:

<?php
$file = fopen(“welcome.txt”, “r”) or exit(“Unable to open file!”);
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). “<br />”;
}
fclose($file);
?>

Reading a File Character by Character

The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer moves to the next character.

Example

The example below reads a file character by character, until the end of file is reached:

<?php
$file=fopen(“welcome.txt”,”r”) or exit(“Unable to open file!”);
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

date() and timestamp refresher

Tuesday, July 27th, 2010

date(format,timestamp)

format is required, example:

date(“Y-m-d”)

of course, Y, m, and d stand for Year, month, day, and they may be separated by whatever you like, so the above example returns 2010-07-27, while date(“m/d/Y”) returns 07/27/2010

now for the timestamp parameter

MAKE what should be supplied for the timestamp, with mktime(hour,minute,second,month,day,year,is_dst)

$tomorrow = mktime(0,0,0,date(“m”),date(“d”)+1,date(“Y”))

date(“Y/m/d”,$tomorrow) returns tomorrow!

I never seem to use the “do…while” loop so here it is just to remind me…

Tuesday, July 27th, 2010

example from :

http://w3schools.com/php/php_looping.asp

<?php
$i=1;
do
{
$i++;
echo “The number is ” . $i . “<br />”;
}
while ($i<=5);
?>

Key difference, it ALWAYS executes once, and THEN evaluates

PHP variable variables $$

Tuesday, July 27th, 2010

“variable variables create variables with variable names”

$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a

$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World

//… and so on …//

From:

http://www.php.net/manual/en/language.variables.variable.php

 

Simpler example:

$var = “oldVarName”;
$$var = “newVarName”;

echo $var; //Returns oldVarName
// create a new var with the value of var as it’s var name
echo $oldVarName; //Returns newVarName

 

Handy in Queries idea example:

$fields = array(“AccessLevels”, “AnswerType”,”Language”, “StatusWithType.Status”, “Categories”, “Products”); // ex. result returned categories RQL from RNT

foreach($fields as $key => $field){

$$field = array(1,2,3,4,5,6); // creates $AccessLevels[], $Language[], $StatusWithType.Status[], etc…

}

print_r($AccessLevels); // more useful, do a subsequent query foreach value now in this array, or a query to fill it, and so on…

using a PHP variable in a MySQL IN batch query example

Friday, July 16th, 2010

Note the ‘s

$product_list = “‘1869’, ‘1929’, ‘549’, ‘189’, ‘419’, ‘176’, ‘192’, ‘310’, ‘291’, ‘514’, ‘1643’, ‘1033’;

$db_name = “dbName”;
//conditional platform logic to support multiple connection scenarios

switch($_SERVER[‘HTTP_HOST’])
{
case ‘localhost’:
$db_host = “localhost”;
$db_username = “userName”;
$db_password = “Password”;
$dblink = mysql_connect ($db_host, $db_username, $db_password);
mysql_select_db($db_name, $dblink);
break;
case ‘www-staging.site.com’: break;
case ‘www.site.com’:
include(‘/var/www/includes/connection_script.php’);
break;
}

$result = mysql_query(”
SELECT
product_id,
product_name
FROM
tableNameHere
WHERE
product_id IN
(“.$product_list.“)
“);
if (!$result) { echo “Could not successfully run query ($sql) from DB: . mysql_error(); exit; }


//let’s break out the resource so that it can be singularly requested when needed

while($one = mysql_fetch_assoc($result))
{
$prod_id = $one[‘product_id‘];
$product_name[$prod_id] = $one[‘product_name‘];
}
@
mysql_close($dblink);

Flash Session Cookie SharedObject

Wednesday, July 7th, 2010

http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/net/SharedObject.html

http://en.wikipedia.org/wiki/Local_Shared_Object

http://www.adobe.com/support/flash/action_scripts/actionscript_tutorial/actionscript_tutorial05.html

to change settings:

right click on any flash swf

or

http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager02.html

stored here:

  • Windows XP:
    • For Web sites: %APPDATA%\Macromedia\Flash Player\#SharedObjects\<random code>\<domain>\<path – maybe°>\<object name>.sol
    • And Also: %APPDATA%\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys
  • Windows Vista and later:
    • For Web sites: %APPDATA%\Macromedia\Flash Player\#SharedObjects\<random code>\<domain>\<path – maybe°>\<object name>.sol
    • And also: %APPDATA%\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys
    • For AIR Applications: unknown, likely similar to the above

PHP sprintf() quick example

Thursday, July 1st, 2010

$template = ‘<div class=”%designIt”><img src=”%s” /><br />%s<br />by %s</div>’;
$designIt = “className”;
$imgSrc = “http://www.imageLivesHere.com/yo.jpg”;
$copyText = “What fabulous and interesting placeholder copy!”;
$sourceAuthor = “Me”;
$altogetherNow = sprintf ( $template, $imgSrc, $linkText, $sourceAuthor);

//Result

<div class=”className“>
<img src=”http://www.imageLivesHere.com/yo.jpg“/>
<br />
What fabulous and interesting placeholder copy!
<br />
by Me
</div>

Close Fancybox from within, old (1.2) and new (1.3)

Thursday, July 1st, 2010

In 1.2 this worked:

onclick=”$(“#fancy_outer”,window.parent.document).hide(); $(“#fancy_overlay”,window.parent.document).hide();

1.3+ this has changed to:

onclick=”parent.$.fancybox.close();