<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Federman Scripts</title>
	<atom:link href="http://federmanscripts.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://federmanscripts.com</link>
	<description>PHP, JavaScript, and More</description>
	<lastBuildDate>Wed, 20 Jul 2011 22:47:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>PHP Routing</title>
		<link>http://federmanscripts.com/2010/12/12/php-routing/</link>
		<comments>http://federmanscripts.com/2010/12/12/php-routing/#comments</comments>
		<pubDate>Mon, 13 Dec 2010 00:59:12 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[routing]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=77</guid>
		<description><![CDATA[<p>Routing in terms of a web application is the selection of content based on the user&#8217;s request URI. Typically, routing is very intuitive for PHP, as with most web languages; the user asks for /foo.php and the server executes and serves up /foo.php.</p> <p>However, an idea I picked up from ASP.NET MVC is their <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2010/12/12/php-routing/">PHP Routing</a></span>]]></description>
			<content:encoded><![CDATA[<p>Routing in terms of a web application is the selection of content based on the user&#8217;s request URI. Typically, routing is very intuitive for PHP, as with most web languages; the user asks for <code>/foo.php</code> and the server executes and serves up <code>/foo.php</code>.</p>
<p>However, an idea I picked up from ASP.NET MVC is their <a href="http://www.asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs" target="_blank">notion of routing</a>. In this way, urls actually look a bit more human-readable, and you can get rid of all the file extensions. Not all the concepts of MVC may translate over to PHP, but the basic idea is to have all requests go first to a routing script which will determine which code to execute from there.</p>
<p>For example, if you had a website which had a forum, you might not want to have the url look like <code>/post.php?postid=12345678</code>. You could instead, make the url <code>/post/12345678/this-is-the-posts-title</code>. This looks a lot better and is very easy to route.</p>
<p>So to set up routing for PHP, first you must get all traffic to get to your routing script. To do this, add the following to your <code>.htaccess</code> file:</p>
<pre class="code">
# Turn on the RewriteEngine
RewriteEngine On

# Rules
RewriteCond %{REQUEST_FILENAME} !/content/*
RewriteRule .? routing.php
</pre>
<p>Now let&#8217;s analyze each line of the file:</p>
<pre class="code">RewriteEngine On</pre>
<p>This turns the rewrite engine on in Apache. The <a href="http://httpd.apache.org/docs/current/mod/mod_rewrite.html">mod_rewrite</a> engine needs to be enabled for this to work, but this should come installed and enabled with most PHP installations.</p>
<pre class="code">
RewriteCond %{REQUEST_FILENAME} !/content/*
RewriteRule .? routing.php
</pre>
<p>The first line is a condition for rewriting. In the example, I have that the request filename <b>NOT</b> be <code>/content/*</code>. The reason for this is that I do not like static content to need to go through routing. So I would put all images, CSS, and JS somewhere in <code>/content/</code>.</p>
<p>The second line basically just makes all other requests now point to <code>routing.php</code>. This file is the one which will do the routing and which every request will end up going through.</p>
<p>So now let&#8217;s take a look at <code>routing.php</code></p>
<pre class="code">
session_start(); // if you are using PHP sessions on your site

// put all common included here like connecting to databases, class includes, etc.
// ...

$requestUri = $_SERVER['REQUEST_URI'];

// get rid of query params
$i = strpos($requestUri, '?');
if($i !== false)
{
	$requestUri = substr($requestUri, 0, $i);
}

$urlParts = explode('/', $requestUri);

// do your routing logic here! Here's a trivial example
$script = $urlParts[1] . 'page.php';

// execute routed script
require_once('header.php');
require_once($script);
require_once('footer.php');
</pre>
<p>The above code should be fairly self explanatory. It assumes that you want your url structure to be <code>/{pageName}</code> mapping to the file <code>/{pageName}/page.php</code>. You can put whatever you want though. Also, the above code puts the header and footer includes in so you don&#8217;t need to have them in each of your page scripts (or <code>session_start()</code>, or those common includes you put in the routing script!).</p>
<p>Here is an example of just the routing logic for the forum example earlier:</p>
<pre class="code">
// ...

// url structure was /post/{postId}/{postTitleEncoded}
if($urlParts[1] == 'post')
{
	$postId = $urlParts[2]; // $postId should be available to the included script file
	// we're ignoring the post title part of the url. It's for human-readability and SEO
	$script = 'post.php';
}
// more routing logic if needed
// ...

// ...
</pre>
<p>Now <code>post.php</code> can use <code>$postId</code> for its logic. This allows it not to have to worry about the header, footer, or any other common scripts, or sanitizing any input as the routing logic should be able to handle all that.</p>
<p>One immediate concern I had was for performance. I thought about it for a while, and I think there is minimal to no impact on performance, as long as you have that <code>!/content/*</code> exception. If PHP routing is used for anything but PHP files, that&#8217;s where the problem would lie. The routing script will probably always be in memory since it&#8217;s used for every page call and the implementation of Apache and PHP <i>should</i> (famous last words) be able to handle a single page being hit over and over just as well as several different pages being hit, if not better.</p>
<p>Some people prefer <code>mod_rewrite</code> for handling all of their routing, but sometimes you may need some logic beyond basic string matching. For example, if the user is logged in or has a certain right access, they might be routed to a different page than others. Also, some kinds or basic validation and sanitation can be done in routing that you wouldn&#8217;t be able to do in <code>mod_rewrite</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2010/12/12/php-routing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>We&#8217;re Back!</title>
		<link>http://federmanscripts.com/2010/11/07/were-back/</link>
		<comments>http://federmanscripts.com/2010/11/07/were-back/#comments</comments>
		<pubDate>Mon, 08 Nov 2010 07:48:11 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[bing]]></category>
		<category><![CDATA[hosting]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=72</guid>
		<description><![CDATA[<p>So for the past week or so the site has been down. I had some problems with my old hosting company; they ended up deleting the website with no backup.</p> <p>Luckily, there are ways to recover the HTML at least by using Bing and the site: modifier. So with the HTML content recovered, I <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2010/11/07/were-back/">We&#8217;re Back!</a></span>]]></description>
			<content:encoded><![CDATA[<p>So for the past week or so the site has been down. I had some problems with my old hosting company; they ended up deleting the website with no backup.</p>
<p>Luckily, there are ways to recover the HTML at least by using <a href="http://www.bing.com/search?q=site:federmanscripts.com" target="_blank">Bing</a> and the site: modifier. So with the HTML content recovered, I manually copy and pasted all the posts back into the site. Phew! Then came the task of actually re-styling the site, which I won&#8217;t even go into here, but rest assured that my weekend has pretty much been dominated by this.</p>
<p>The moral of the story, back your websites up. Even though your hosting company may claim to backup your files, experience has shown me that they don&#8217;t always.</p>
<p>On a lighter note, I have changed hosting to <a href="http://www.landonwisser.com" target="_blank">landonwisser.com</a>. I know the guy personally, and I know there won&#8217;t be any problems with his hosting.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2010/11/07/were-back/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sortable Table&#8230; Updated!</title>
		<link>http://federmanscripts.com/2010/07/22/sortable-table-updated/</link>
		<comments>http://federmanscripts.com/2010/07/22/sortable-table-updated/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 02:38:28 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[tables]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=57</guid>
		<description><![CDATA[<p>After using my original Sortable Table for some time now, I’ve noticed something that could be better. Namely, type-awareness! I added the ability to declare each column as containing common type of data like numbers and dates as well as giving the functionality to enable writing custom sort functions.</p> <p>Source: sortableTable.js Example: Example</p> <p>To declare a column <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2010/07/22/sortable-table-updated/">Sortable Table&#8230; Updated!</a></span>]]></description>
			<content:encoded><![CDATA[<p>After using my original <a href="http://federmanscripts.com/2010/02/01/sortable-table/">Sortable Table</a> for some time now, I’ve noticed something that could be better. Namely, type-awareness! I added the ability to declare each column as containing common type of data like numbers and dates as well as giving the functionality to enable writing custom sort functions.</p>
<p>Source: <a href="http://federmanscripts.com/scripts/sortableTable/sortableTable.js" target="_blank">sortableTable.js</a><br />
Example: <a href="http://federmanscripts.com/scripts/sortableTable/" target="_blank">Example</a></p>
<p>To declare a column as containing numbers, give the associated <code>th</code>, <code>class="number"</code>. As you may guess, it basically just parses the string as a float (using <code>parseFloat</code>) before comparing, so “11″ will come after “2″. To sort dates, add <code>class="date"</code> to the <code>th</code>. This simply uses the <code>Date.parse</code> function before comparing.</p>
<p>Now that the “easy” ones were out of the way, I thought about how to give the developer a way to define their own sorting function, since strings, numbers, and dates won’t be the only things that should exist in a sortable table, for example, move ratings.</p>
<p>To do this, add <code>class="custom_sortFunc"</code> to your <code>th</code> where sortFunc is the JavaScript function you want to use to sort. This function should take two arguments and return an integer. The return value should be less than 0 if the first argument should be before the second, 0 if they’re equal sort-wise, and greater than 0 if the first should go after the second.</p>
<p>In the example, you see the following:</p>
<pre>var movieRatings = new Array('G', 'PG', 'PG-13', 'R', 'NR');
function movieRatingSort(str1, str2)
{
	return movieRatings.indexOf(str1) - movieRatings.indexOf(str2);
}</pre>
<p>My movie ratings <code>th</code> has <code>class="custom_movieRatingSort"</code>. That’s all!</p>
<p>Note that there is no error checking in the way of checking to see that the custom sort function takes two arguments nor that the return type is an int, so funky things may happen if you give it an invalid function.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2010/07/22/sortable-table-updated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Academic Approach to Optimizing CSS</title>
		<link>http://federmanscripts.com/2010/05/08/an-academic-approach-to-optimizing-css/</link>
		<comments>http://federmanscripts.com/2010/05/08/an-academic-approach-to-optimizing-css/#comments</comments>
		<pubDate>Sat, 08 May 2010 02:30:36 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=54</guid>
		<description><![CDATA[<p>Recently, I finished my undergraduate honors thesis in computer science entitled, &#8220;Applying Formal Concept Analysis to Cascading Style Sheets.&#8221; It&#8217;s a successful attempt at optimizing CSS using a technique called Formal Concept Analysis. Note that this is not a minifier! This algorithm analyzes the structure of the code and makes optimizations on the structure, <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2010/05/08/an-academic-approach-to-optimizing-css/">An Academic Approach to Optimizing CSS</a></span>]]></description>
			<content:encoded><![CDATA[<p>Recently, I finished my undergraduate honors thesis in computer science entitled, &#8220;Applying Formal Concept Analysis to Cascading Style Sheets.&#8221; It&#8217;s a successful attempt at optimizing CSS using a technique called <a href="http://en.wikipedia.org/wiki/Formal_concept_analysis" target="blank">Formal Concept Analysis</a>. Note that this is <b>not</b> a minifier! This algorithm analyzes the structure of the code and makes optimizations on the structure, not just taking out white space and other syntactic &#8220;fluff.&#8221;</p>
<p>From a very high level, the algorithm rearranges and restructures selector-declaration pairs into different rule blocks and groups selectors and declarations in different ways. Unfortunately, specificity can get nuked sometimes, so the results should be tested to make sure they are still correct. Also, there are multiple ways to run the optimization, each of which produce very different results, so some thought and analysis is still required when using the algorithm to determine which results work best for the particular input.</p>
<p>One noteworthy result is that I ran the algorithm on a very large (150+ kb) file from a real website and the file was reduced by about 20%. On the other hand, optimizing some CSS files with certain options can also increase the file size. Again, additional analysis is needed both before and after the algorithm is run to get ideal results.</p>
<p><b>Downloads</b><br /> <br />
Paper: <a href="http://apps.cs.utexas.edu/tech_reports/reports/tr/TR-1967.pdf" target="_blank">Download PDF</a><br /> <br />
Slides for Talk: <a href="http://docs.google.com/present/view?id=dhqjmcsd_46d8wk9ndk" target="_blank">View</a> (Note that the slides are web-based, so positioning for some diagrams can be a bit off)</p>
<p><center><iframe src="http://docs.google.com/present/embed?id=dhqjmcsd_46d8wk9ndk" frameborder="0" width="410" height="342"></iframe></center></p>
<p>This paper really just skims the surface, and if I were to continue on to graduate school, I would definitely have plenty of room to expand and improve the methods I used for this research.</p>
<p>Soon I&#8217;ll get around to making the Java implementation I created public and create a nice little interface for running the algorithm on user input. Ideally, this tool could be used in addition to minification to &#8220;compile&#8221; CSS, just as JavaScript can be minified and obfuscated to produce smaller file sizes.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2010/05/08/an-academic-approach-to-optimizing-css/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX Form</title>
		<link>http://federmanscripts.com/2010/03/22/ajax-form/</link>
		<comments>http://federmanscripts.com/2010/03/22/ajax-form/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 02:29:07 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[forms]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=52</guid>
		<description><![CDATA[<p>This script will give a form on a page (or multiple forms) the ability to send off an email once complete. Zero Javascript is required on the implementer’s part, and very minimal edits need to be made to the PHP. Basic validation can be enabled, and this form is resistant to spam bots since it <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2010/03/22/ajax-form/">AJAX Form</a></span>]]></description>
			<content:encoded><![CDATA[<p>This script will give a form on a page (or multiple forms) the ability to send off an email once complete. Zero Javascript is required on the implementer’s part, and <strong>very</strong> minimal edits need to be made to the PHP. Basic validation can be enabled, and this form is resistant to spam bots since it works off AJAX (and thus Javascript, which most bots have disabled). All the different input fields should work (text box, checkbox, drop downs, text areas, password fields, etc) except for file uploads, which I’ll probably handle in a later post.</p>
<p>Example: <a href="http://federmanscripts.com/scripts/ajaxForm/" target="_blank">here</a><br />
Source: <a href="http://federmanscripts.com/scripts/ajaxForm/ajaxForm.php" target="_blank">ajaxForm.php</a></p>
<p>Although the source file is a PHP file, it needs to be included in the HTML as if it were a Javascript as shown in the example.</p>
<p>Note that there are two variables which should be edited by the implementor, both of which are at the very top of the file: $to and $from. These (pretty self-explanitorily) variables are the email addresses which the email is sent to and from. Note that the $to field may contain several email addresses separated by commas. This should be the only edit to the PHP/Javascript code that needs to be made.</p>
<p>In your HTML, add the “ajaxForm” class to your form(s) which you want to use this script. Note that the Javascript will overwrite the “action” property of the form, but this shouldn’t be a concern in most cases.</p>
<p>Two hidden fields should be included, “ajaxFormSubject” and “ajaxFormCompleteDiv”. ajaxFormSubject is the subject which you wish the email to have. ajaxFormCompleteDiv is the id of the HTML element you wish to display (display: block) after the form is successfully complete, like a “thank you” div. Note that if you want the ajaxFormCompleteDiv to be hidden initially, you should hide it with your own CSS. This is for flexibility.</p>
<p>After successful form completion, the form element will automatically be hidden (display: none) and the ajaxFormCompleteDiv automatically shown (display: block).</p>
<p>To enable validation for a field, add the class “required” to the field. The validation only consists of checking if some value was entered.</p>
<p>If a field is found to be invalid, the input, select, or textarea will be given the class “ajaxFormError”. You should add your own CSS to determine the style of this.</p>
<p>This code is meant for designers or developers with little to no programming experience and satisfies this requirement quite nicely as only 2 PHP variables should be modified and the rest is in the HTML.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2010/03/22/ajax-form/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sortable Table</title>
		<link>http://federmanscripts.com/2010/02/01/sortable-table/</link>
		<comments>http://federmanscripts.com/2010/02/01/sortable-table/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 02:19:50 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[tables]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=49</guid>
		<description><![CDATA[<p>This article will describe a javascript which will make any &#60;table&#62; sortable on all columns.</p> <p>Update: Thanks to a comment to this post, I corrected a problem with Firefox. I am now using textContext for non-IE browsers as it&#8217;s more widely supported.</p> <p>Update 2: I&#8217;ve written a follow up to this article adding additional <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2010/02/01/sortable-table/">Sortable Table</a></span>]]></description>
			<content:encoded><![CDATA[<p>This article will describe a javascript which will make any &lt;table&gt; sortable on all columns.</p>
<p><b>Update:</b> Thanks to a comment to this post, I corrected a problem with Firefox. I am now using <code>textContext</code> for non-IE browsers as it&#8217;s more widely supported.</p>
<p><b>Update 2:</b> I&#8217;ve written a <a href="http://federmanscripts.com/2010/07/22/sortable-table-updated/">follow up</a> to this article adding additional functionality not mentioned in this article.</p>
<p>Source: <a href="http://federmanscripts.com/scripts/sortableTable/sortableTable.js" target="_blank">sortableTable.js</a><br /> <br />
Example: <a href="http://federmanscripts.com/scripts/sortableTable/" target="_blank">Example</a></p>
<p>Here is an example (the above link will be better for looking at the HTML source):<br /> <br />
<script src="http://federmanscripts.com/scripts/sortableTable/sortableTable.js" type="text/javascript"></script> </p>
<div align="center">
<table class="sortable">
<thead>
<tr>
<th class="defaultSort">Name</th>
<th>Age</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jon Doe</td>
<td>21</td>
<td>jon@doe.com</td>
<td>111-111-1111</td>
</tr>
<tr>
<td>Joe Bob</td>
<td>20</td>
<td>joe@bob.com</td>
<td>222-222-2222</td>
</tr>
<tr>
<td>Fake Guy</td>
<td>25</td>
<td>fake@guy.com</td>
<td>555-555-5555</td>
</tr>
</tbody>
</table>
</div>
<p>With the javascript included, the table needs to have class <code>sortableTable</code>, exactly one &lt;thead&gt; with exactly one row, and exactly one &lt;tbody&gt;.</p>
<p>To make a particular column the default sorted column (it&#8217;s be sorted upon the initial page load), add the class <code>defaultSort</code> to the particular &lt;th&gt; in the one row in &lt;thead&gt;.</p>
<p>The javascript also automatically adds the classes <code>even</code> and <code>odd</code> to the even and odd numbered rows for ease of styling.</p>
<p>The sorting is done based off of the <del datetime="2010-04-04T04:49:00+00:00"><code>innerText</code></del> <code>textContent</code> of each cell, so if the cell contains HTML and you are expecting it to sort in that way, it may be sorted differently. For example, if one cell had <code>&lt;a href="federmanscripts.com"&gt;Z&lt;/a&gt;</code> and another had <code>&lt;b&gt;A&lt;/b&gt;</code>, the cell containing &#8220;Z&#8221; would be before the one containing &#8220;A&#8221; if <del datetime="2010-04-04T04:49:00+00:00"><code>innerText</code></del> <code>textContent</code> was used, but with <del datetime="2010-04-04T04:49:00+00:00"><code>innerText</code></del> <code>textContent</code> the &#8220;A&#8221; would come first, as expected by the user. In short, the displayed text in the cell is what the column is sorted by.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2010/02/01/sortable-table/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Form and Table Row Nesting Workaround</title>
		<link>http://federmanscripts.com/2010/01/12/form-and-table-row-nesting-workaround/</link>
		<comments>http://federmanscripts.com/2010/01/12/form-and-table-row-nesting-workaround/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 02:19:46 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[forms]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tables]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=47</guid>
		<description><![CDATA[<p>Have you ever tried to nest elements in a way that is valid as far as XML is concerned, but isn&#8217;t &#8220;valid&#8221;? For example, have a table containing a different form per table row? This article describes a workaround for that.</p> <p>So no matter how much you may hate tables in HTML, sometimes it <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2010/01/12/form-and-table-row-nesting-workaround/">Form and Table Row Nesting Workaround</a></span>]]></description>
			<content:encoded><![CDATA[<p>Have you ever tried to nest elements in a way that is valid as far as XML is concerned, but isn&#8217;t &#8220;valid&#8221;? For example, have a table containing a different form per table row? This article describes a workaround for that.</p>
<p>So no matter how much you may hate tables in HTML, sometimes it just makes life much easier. Now I don&#8217;t want to get into a Div vs Table discussion, but I think we can at least agree that tables have a place and most of us use them at some point.</p>
<p>To set the stage, basically I was making a content management system for a client, and so I had several items with several editable properties. The most straightforward way I thought to implement this is to have a table, with one item per row, one property per column. For example:</p>
<div align="center">
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th></th>
</tr>
<tr>
<td>
<input type="text" value="John Doe" /></td>
<td>
<input type="text" value="john@doe.com" /></td>
<td>
<input type="submit" value="Update" onclick="void(0);" /></td>
</tr>
<tr>
<td>
<input type="text" value="Joe Bob" /></td>
<td>
<input type="text" value="joe@bob.com" /></td>
<td>
<input type="submit" value="Update" onclick="void(0);" /></td>
</tr>
</table>
</div>
<p>The only real problem is that structurally we&#8217;d have &lt;table&gt;&lt;form&gt;&lt;tr&gt;&#8230;&lt;/tr&gt;&lt;/form&gt;&lt;/table&gt;, which is not valid, and actually doesn&#8217;t work in <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a>.</p>
<p>Now, before anyone suggests just surrounding the table with one huge form, the table was dynamic (using php in my case) and could have arbitrarily many rows. Thus the entire form, including fields that weren&#8217;t even being used, would be sent every time a row was to be updated by the user. This <i>greatly</i> increases the amount <code>POST</code>ed. Not only that, but fields would need to be named something akin to <code>name1</code>, <code>email1</code>, <code>name2</code>, <code>email2</code>, etc. and that&#8217;s just a huge mess on the back-end.</p>
<p>My solution uses an invisible form outside of the table and javascript. The gist is once the submit button is pressed, move all <code>input</code>, <code>select</code>, and <code>textarea</code> elements from the desired &#8220;virtual form&#8221; to the invisible form and submit that invisible form.</p>
<p>Example: <a href="http://federmanscripts.com/scripts/formTrNesting/" target="_blank">Here</a></p>
<p>In my example, which is basically identical to the above table, I&#8217;ve added the invisible form, the necessary javascript function, the class &#8220;form&#8221; to the table rows, and <code>onclick="submitForm(this);"</code> to the submit buttons.</p>
<p>You can add the &#8220;form&#8221; class to whichever container you want which defines your &#8220;form&#8221; as the javascript just takes the submit button and keeps going up the node tree until it hits a node with <code>class="form"</code>.</p>
<p>Do note that because the submit button isn&#8217;t actually being clicked as far as the invisible form is concerned, the javascript converts the button into a hidden field so that the button name-value pair still appear in the <code>POST</code>.</p>
<p>Also note that since elements are being shuffled around, there is a slight &#8220;flicker&#8221; after the submit button is pressed, but before the page reloads. There are workarounds to this if absolutely necessary, but most users won&#8217;t care or even notice.</p>
<p>While all the code is very straightforward and easy to understand, it can be pretty powerful and hopefully prevent a lot of headaches and/or code rearrangement/hacks.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2010/01/12/form-and-table-row-nesting-workaround/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>AJAX Made Easy</title>
		<link>http://federmanscripts.com/2009/12/21/ajax-made-easy/</link>
		<comments>http://federmanscripts.com/2009/12/21/ajax-made-easy/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 02:13:28 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=45</guid>
		<description><![CDATA[<p>While AJAX may seem scary to a novice programmer, all it really does is connect Javascript to a server-side scripting language of choice. In this article, I’ll show how to easily make use of AJAX with PHP.</p> <p>The notion of AJAX is very simple to understand. Your browser just makes a request to the <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2009/12/21/ajax-made-easy/">AJAX Made Easy</a></span>]]></description>
			<content:encoded><![CDATA[<p>While AJAX may seem scary to a novice programmer, all it really does is connect Javascript to a server-side scripting language of choice. In this article, I’ll show how to easily make use of AJAX with PHP.</p>
<p>The notion of AJAX is very simple to understand. Your browser just makes a request to the web server, just like any other request like as if you were navigating to a page, but instead of reload the page and displaying it, it just returns the markup to a specified Javascript function.</p>
<p>Example: <a href="http://federmanscripts.com/scripts/ajax/" target="_blank">Here</a><br />
JS Source: <a href="http://federmanscripts.com/scripts/ajax/ajax.js" target="_blank">ajax.js</a><br />
PHP Source (as text): <a href="http://federmanscripts.com/scripts/ajax/ajaxHandler.txt" target="_blank">ajaxHandler.php</a></p>
<p>Now the example definitely doesn’t make use of best practices for AJAX (I may write a post about that later, but the gist is that you shouldn’t return HTML or “pretty” stuff, but data that needs parsing or even better, a JSON object to be parsed), but it should give you the basics of how to pass data to PHP and then how to get the response back to Javascript. Now anything you’ll want to do, you just need to know how to do it in either Javascript or PHP.</p>
<p>If you take a look into the <a href="http://federmanscripts.com/scripts/ajax/ajax.js" target="_blank">ajax.js</a> file, there is a class called <code>ajax</code>. Even though AJAX is quite easy, this class exists so that only one call is needed to make and return an AJAX call. While I won’t go through the details of how the function works, to make an AJAX call with this code, just call <code>ajax.call</code> and pass it three things: the URL to request, the parameters to pass, and the callback function.</p>
<p>The URL should be the URL of the PHP (or whatever) code you wish to request. Note that this code uses POST to request the URL. This can fairly easily be changed to GET if needed. The main different between POST and GET is that POST requires two actual requests to be made per request, while GET has a limited size due to URL length restrictions. When sending form data, POST is recommended while when simply requesting data, GET should be used. Here I use POST to cover all bases.</p>
<p>The parameters should be an object with the property names being the parameter name and their values being the value to pass. Passing null is perfectly acceptable if no parameters are needed.</p>
<p>The callback function is a function that the response from PHP (or whatever) will be given to. This function should have one parameter which will be a String containing the response. Note that this function needs to be passed as an object.</p>
<p>Do note that there will be a slight delay from the time you click on the button to the time when the response is displayed. This is because of the latency of making requests over the internet. It is recommended to disabling buttons while the request is unanswered.</p>
<p>Something to note about AJAX is that it is entirely asynchronous. The <code>ajax.call</code> function is non-blocking, meaning that the code that follows will continue to run even before the request comes back. If you are familiar with event driven programming, this should be an easy thing to understand. If not, be cautious with how your code is set up so that it works no matter when the callback happens. Depending on latency and computer speed, the callback could fire immediately after the <code>ajax.call</code> function is called, well after the rest of the Javascript is run, or anywhere in between. Most browsers implement Javascript as single-threaded, but with AJAX it should be treated as multi-threaded and so good practices for shared objects should be used. While there are no locks in Javascript, a careful programmer can make sure the code works as intended.</p>
<p>While the example does absolutely nothing interesting, it should provide the building blocks for creating your own AJAX code for tying your Javascript and PHP knowledge together.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2009/12/21/ajax-made-easy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>“Secure” Remember Me</title>
		<link>http://federmanscripts.com/2009/12/14/%e2%80%9csecure%e2%80%9d-remember-me/</link>
		<comments>http://federmanscripts.com/2009/12/14/%e2%80%9csecure%e2%80%9d-remember-me/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 02:05:15 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=42</guid>
		<description><![CDATA[<p>To quickly explain the “Secure” part, it is as secure as it can be without using SSL. I’ll expand on explaining the security more below.</p> <p>The main purpose is to artificially extend the PHP session beyond its normal lifetime, as you see on most sites using a cookie. However, cookies are inherently insecure as <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2009/12/14/%e2%80%9csecure%e2%80%9d-remember-me/">“Secure” Remember Me</a></span>]]></description>
			<content:encoded><![CDATA[<p>To quickly explain the “Secure” part, it is as secure as it can be without using SSL. I’ll expand on explaining the security more below.</p>
<p>The main purpose is to artificially extend the PHP session beyond its normal lifetime, as you see on most sites using a cookie. However, cookies are inherently insecure as they are stored on insecure medium. I’ll explain how to make this quite a bit more secure. Again, if you <strong>REALLY</strong> need security, for example if you’re running an e-commerce site, you really should fork over the money for SSL. I only recommend the following method if you’re running some sort of forum or some other sort of non-sensitive information-accessing website.</p>
<p>First off, lets set up the database. You’ll need a table (I call mine <code>userAuthentication</code>) with three columns: <code>userId:int</code>, <code>lastUsed:datetime</code>, and <code>authString:varchar(32)</code>. The below will create this table for you:</p>
<pre>CREATE TABLE IF NOT EXISTS `userAuthentication`
(
	`userId` int(11) NOT NULL,
	`lastUsed` datetime NOT NULL,
	`authString` varchar(32) NOT NULL
)
ENGINE=MyISAM DEFAULT CHARSET=latin1;</pre>
<p>The three fields should be pretty self-explanitory, except the <code>authString</code>, which I will explain later.</p>
<p>Next let’s set up the code for logging in. I’m assuming the use on the HTML side of 3 fields: <code>userName</code>, <code>password</code>, and <code>remember</code>. The below is generally how your php login script should look:</p>
<pre>session_start();
include_once('userAuth.php'); // We'll show this later
// other includes, dbconnect, etc...

// get variables
$userName = strtolower(mysql_real_escape_string($_REQUEST['userName']));
$password = md5($_REQUEST['password']);
$remember = $_REQUEST['remember'] == '1';

// check if the credentials are correct and get the userId

// if user logged in successfully
if($userIsCorrect)
{
	if($remember)
		generateAuthString($userId); // this function will exist in userAuth.php

	$_SESSION['userId'] = $userId;
	// do whatever else you need
}</pre>
<p>Before I go on, do note that it is HIGHLY recommended to hash any password you store (I used md5 in my example). That way if your database is compromised somehow, the attacker will never be able to read your users’ passwords as plain text. This doesn’t have anything to do with the rest of this post, but is very good practice.</p>
<p>So the above code is also pretty self-explanatory. Get the credentials, checks the credentials, set the session, then call this mysterious <code>generateAuthString</code> function, which I’ll explain below.</p>
<p>So far everything we’ve done is fairly straightforward, and if you already had a login system set up, you’ve written probably almost no code so far. Now I’ll get into this <code>userAuth.php</code> code file.</p>
<p>Here is the <a href="http://federmanscripts.com/scripts/secureRememberMe/userAuth.txt" target="_blank">PHP Source</a> (as text file).</p>
<p>There are three functions in this file: <code>checkLogIn</code>, <code>generateAuthString</code>, and <code>clearAuthString</code>.</p>
<p><code>checkLogIn</code> first checks to see if the PHP session is still active to save time. This code is assuming the security of PHP sessions, so if it still is valid, it just immediately returns true. If, however, the session has expired, it checks if the <code>userAuth</code> cookie is set. If it is not, it returns false as the “remember” cookie doesn’t exist.</p>
<p>If the <code>userAuth</code> cookie does exist, the function takes the cookie, appends the user’s IP address and user agent (browser’s identification string), hashes it all together, and checks it against the <code>authString</code> string in the database. Currently, I don’t check for how long the <code>authString</code> lasts, but it is pretty straightforward to make it expire after a certain time after <code>lastUsed</code>.</p>
<p>After this is all done and everything checks out, the old <code>authString</code>is cleared and <code>generateAuthString</code> is called to create a new authentication cookie string and the session is set for the user.</p>
<p><code>generateAuthString</code> just generates the <code>authString</code> for the database using a hash of a random number, the user’s IP, and their user agent, and then sets the user’s cookie to the hash of the same random number. My example sets the cookie expiration to one month in the future.</p>
<p><code>clearAuthString</code> just clears the user’s <code>authString</code> entry in the database that corresponds to the <code>authString</code> cookie they have. This is to be used when the user logs out.</p>
<p><code>checkLogIn</code> should be used any time the user’s credentials should be checked (usually the top of every page that requires the user to be logged in).</p>
<p>So now that the code is all explained, I can further discuss why this is secure.</p>
<p>First off, the cookie that the user stores contains absolutely no identification information. All that’s stored is a hash of a random number.</p>
<p>Next, each <code>authString</code> is unique to a particular user, so if one user’s <code>authString</code> is somehow compromised, it doesn’t compromise the entire system.</p>
<p>Each <code>authString</code> is also a hash of the user’s cookie, IP, and user agent, so having the correct cookie alone is not enough to gain access.</p>
<p>Finally, each <code>authString</code> is deleted after it’s use and another generated, so although they may last a long time if not used, they are only able to be used once. I must admit, that I got this “one-use” idea from Blizzard’s <a href="http://us.blizzard.com/store/details.xml?id=1100000822" target="_blank">Blizzard Authenticator</a>. Obviously I haven’t seen their code for that nor is this really anything like that, but I just thought I’d give them credit nevertheless =P.</p>
<p>So for an attacker to gain access using the <code>authString</code> of a legitimate user, they must:</p>
<ul>
<li>Steal the user’s <code>userAuth</code> cookie.</li>
<li>Know the particular user’s IP address.</li>
<li>Spoof the particular user’s IP address</li>
<li>Know the particular user’s exact browser and version (user agent)</li>
<li>Spoof the particular user’s user agent</li>
<li>Do all this before the particular user’s PHP session expires and tries to access the site again</li>
</ul>
<p>Generally, all of that will be much harder than just scanning outgoing packets for the user’s plain-text username and password when they actually do have to type in their username and password. In fact, since the user will most likely have to log in less, they will be sending their credentials in plain-text less, and thus this “remember me” functionality actually increases the security for that user.</p>
<p>To conclude, this is <strong>NOT</strong> meant to replace SSL, but can add some security to your log in scripts as well as adding some convenience for your users.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2009/12/14/%e2%80%9csecure%e2%80%9d-remember-me/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Requests and Donations</title>
		<link>http://federmanscripts.com/2009/10/25/requests-and-donations/</link>
		<comments>http://federmanscripts.com/2009/10/25/requests-and-donations/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 02:03:43 +0000</pubDate>
		<dc:creator>David Federman</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://federmanscripts.com/?p=40</guid>
		<description><![CDATA[<p>Two new menu items have been added to the left sidebar: the Request Script page and Donations page.</p> <p>The Request Script page is a form you can fill out to request that I develop some script. Payment is optional, but the work I do for free will definitely be slower and I’m unlikely to <span style="color:#777"> . . . &#8594; Read More: <a href="http://federmanscripts.com/2009/10/25/requests-and-donations/">Requests and Donations</a></span>]]></description>
			<content:encoded><![CDATA[<p>Two new menu items have been added to the left sidebar: the Request Script page and Donations page.</p>
<p>The Request Script page is a form you can fill out to request that I develop some script. Payment is optional, but the work I do for free will definitely be slower and I’m unlikely to make specific tweaks once I’m done. Basically, it’s a way for me to get some input on what I should be posting next since right now I’m just posting stuff that I develop for other projects I’m working on and not just arbitrarily.</p>
<p>The Donations page is pretty straightforward. Websites cost money to host, and I do put a lot of time into the posts I make. So if you like what I do or find a particular post very helpful, feel free to contribute. Obviously though, since the source is all posted publicly and considering the whole notion of “donation,” it’s completely optional, but of course, greatly appreciated.</p>
]]></content:encoded>
			<wfw:commentRss>http://federmanscripts.com/2009/10/25/requests-and-donations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

