Looking at the PHP Form Post Object

I use php to talk with MySQL db server. It comes in handy for making apps. Here are the code variations for receiving POST variables from a client request and ,for debug, a quick list of the variables, names and values. Using this: print_r($_POST); this gives a breakdown of the array holding the data from the post variables…. Array ( [signindate] => 11/4/2011 [signintime] => 15:33 PM [nameofchild] => dev en [parentsignature] => don e [in] => Sign In ) to access an element of the array I use a couple methods.. to get them one by one  by name so I can put them into the database.. $myformelement=$_POST[‘form element field html id name’];

Now that the records are correctly inserting into database, my next step is to  use some ajax to call the php behind the scenes while leaving my webapp ui view intact.

  • Check if a person is selected
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server

Add a Zero (0) in front of numbers below ten (10)

In certain situation I need to add a zero in front of numbers below ten. It could be used for money, .05 and for time :05 and I’m sure there are other situations where this could be useful.

// add zer0 in front of minutes below ten 10
function pad(n) {if (n < 10) return “0” + n; return n;}

// use the pad function
for(var minute=0; minute<50;minute=minute+5){
$(“#minutes”).append(“<option value='”+pad(minute)+”‘>”+pad(minute)+”</option>”);
}

Web Form Security Practices

We have had a lot of attacks to our web forms here at SVC. I am the paperless applications developer, so the task of keeping them safe and secure falls into my daily operations. An un secure form can let an attacker do many things to ruin someones day, such as sending unsolicited emails to all the staff and students. Some of the common practices to keep the “bots” from breaking into a web form are:

CAPTCHA
This technique provides the user with a series of image “keys”  that they must “unlock” before they can submit the web form. This is a  good way to slow down the bots, but since they don’t get tired, and can hammer away at the form many times each second, they can eventually bypass this technique. Another problem with captcha, and a very important one, is regarding the user experience. Some captchas are impossible to read, and take several tries for a normal user to get correct. This can really damper the user experience and create a situation where the user will just leave instead of taking the time to keep trying to unlock the captcha keys. As stated by the w3, “This type of visual and textual verification comes at a huge price to users who are blind, visually impaired or dyslexic. Naturally, this image has no text equivalent accompanying it, as that would make it a giveaway to computerized systems. In many cases, these systems make it impossible for users with certain disabilities to create accounts, write comments, or make purchases on these sites, that is, CAPTCHAs fail to properly recognize users with disabilities as human.”

So, what else can I do to help keep the bots from submitting forms?

1: Try to make sure that the form is submitted from the form page, because the bots usually submit directly to the form action. Put some kind of trigger in the form submit actions that look for a referring address or a session variable.

In classic ASP we have the Request.ServerVariables collection that can get some important information, and if the form data has not come from the form page, we know its a bot, and can secretly send a security alert to the admin, while not letting the bot know its been busted.

Request.ServerVariables("URL"), SCRIPT_NAME, and PATH_INFO

should all contain the form’s address, and should show that the form was submitted from the proper location.

Request.ServerVariables("SERVER_NAME")

should be checked for the proper domain, indicating whether the form was properly posted from my server. I could create an include to be used before each form submission to check for coming from my server.

These could be put into hidden fields and submitted with the form, then checked for validity before processing and submitting the form. Also a session variable might be a good way to track these from form submit to data capture.

In the form capture logic, we could look for Request.ServerVariables(“HTTP_REFERER”) to ensure that the data has come from our form page.

So, lets try some of this junk and see if it helps out.
First, lets set a session of “formuser” with a value of Request.ServerVariables(“URL”) when the user accesses the form, and then check for that session in the form submit logic. If there is no session, then this data did not come from our form.

Creating dynamic selects using Javascript and JQuery

I need to have a select form element, with the options generated from dynamic content that could come from a database or an array, with an unknown number of options. Then, I need to create two more selects, with all of the options except the ones selected in the previous select. For example, a user must choose their first, second, and third choices for college.

Lets say we have a list of colleges and their abbreviations:

<input type=”checkbox” name=”scholarshipschools” value=”CWU” title=”Please select a college.” /> Central Washington Univ, Ellensburg <br />
<input type=”checkbox” name=”scholarshipschools” value=”EWU” /> Eastern Washington Univ, Cheney <br />
<input type=”checkbox” name=”scholarshipschools” value=”SVC”  /> Skagit Valley College <br />
<input type=”checkbox” name=”scholarshipschools” value=”ESC” /> The Evergreen State College, Olympia    <br />
<input type=”checkbox” name=”scholarshipschools” value=”UWB” /> Univ of Washington, Bothell <br />
<input type=”checkbox” name=”scholarshipschools” value=”UWS” /> Univ of Washington, Seattle <br />
<input type=”checkbox” name=”scholarshipschools” value=”UWT” /> Univ of Washington, Tacoma <br />
<input type=”checkbox” name=”scholarshipschools” value=”WSU” /> Washington State Univ, Pullman <br />
<input type=”checkbox” name=”scholarshipschools” value=”WWU” /> Western Washington Univ, Bellingham

 

The checkboxes don’t allow the user to choose what ones would be their first, second and third choices. Also, doesn’t let the user know that they are limited to choosing three. I have been asked to redesign this form so that the user has a better interaction with the page.

I don’t want to type the names of the schools and their abbreviations more than once while I develop this, so the first thing I want to try is to put them into an array, then I can use them when, where and in whatever container I wish. (like changing from checkboxes to selects).

 

var thecollegeabbr = [“CWU”,”EWU”, “SVC”, “ESC”, “UWB”, “UWS”, “UWT”, “WSU”, “WWU”];

var thecolleges = [“Central Washington Univ, Ellensburg”, “Eastern Washington Univ, Cheney”, “Skagit Valley College”, “The Evergreen State College, Olympia”, “Univ of Washington, Bothell”, “Univ of Washington, Seattle”, “Univ of Washington, Tacoma”, “Washington State Univ, Pullman”, “Western Washington Univ, Bellingham”];

I would like for the college name to have its abbreviation attached to it, rather than have them in two separate arrays. Using the information from my previous post on JavaScript Array Best Practices, I see that I could streamline this a little, and make a more efficient 2-dimensional array. I will use a for-if loop to push the abbreviation and title into a two dimensional array.

var thecollegechoices=[];
// combine the abbreviation and the title into a two dimensional array…
for(i=0;i<thecollegeabbr.length;i++){thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]); }

Now that I have an array of data to populate the selects, I will create an algorithm to  put the data into the “First Choice” selector:
// now put the data into a select element
for(i=0;i<thecollegechoices.length;i++){
$(“#firstcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);
} // end for loop to put the data into a select element

screen shot of dynamic selectThe results are very effective, as I now have a select that was dynamically populated using the array of data that I was provided. The next step is where this really starts to get fun. Now I need to create a “Second Choice” selector using all of the choices from the first one, except for the one that was chosen by the user in the “First Choice” selector. This will need an algorithm that is a bit more complex, and will be triggered by the event of the user choosing the first choice.

From my previous article about using JQuery to handle events, I know that I can access the onchange event handler and give it a method that will run my function when the user changes the value of the select. I will build the algorithm into this method as so:

  • Get the value of the college that the user has chosen.
  • Rebuild my array of “thecollegechoices”, eliminating the option that was previously chosen.
  • Populate the options of the “Second Choice” selector using the new data that has been  put into thecollegechoices array.

Here is a snippet of what this looks like now…

$( ‘#firstcollegechoice’ ).on(“change”, function(){
var thecollegechoices=[];
for(i=0;i<thecollegeabbr.length;i++){
// check here to see if the choice is used in the first select.
if(thecollegeabbr[i]!=$(“#firstcollegechoice :selected”).val())                                {thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]);}
}

for(i=0;i<thecollegechoices.length;i++){$(“#secondcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

}); // end first choice change functions

 

Dang, this is lookin good. I now have a second choice selector with all the options except for the one that was chosen by the user in the first selector.

It seems like an easy path to our goal, a “Third Choice” selector with all of the options except what was chosen in one and two. Then we are left with some ui clean up to ensure a good user experience. I like to use responsive disclosure to guide the user through a form whenever possible. For this instance, I will disable the second and third choice drop-downs until they are needed, so the user will easily see what they need to do.

———————————– here is the dev code ———————————–

<select name=”scholarshipschools” id=”firstcollegechoice” ><option value=””>First Choice</option></select>
<select name=”scholarshipschools” id=”secondcollegechoice” disabled=”disabled”><option value=””>Second Choice</option></select>
<select name=”scholarshipschools” id=”thirdcollegechoice” disabled=”disabled”><option value=””>Third Choice</option></select>

<script>
// make an array to hold the college choices.
var thecollegeabbr = [“CWU”,”EWU”, “SVC”, “ESC”, “UWB”, “UWS”, “UWT”, “WSU”, “WWU”];
var thecolleges = [“Central Washington Univ, Ellensburg”, “Eastern Washington Univ, Cheney”, “Skagit Valley College”, “The Evergreen State College, Olympia”, “Univ of Washington, Bothell”, “Univ of Washington, Seattle”, “Univ of Washington, Tacoma”, “Washington State Univ, Pullman”, “Western Washington Univ, Bellingham”];
var thecollegechoices=[];

// combine the abbreviation and the title into a two dimensional array…
for(i=0;i<thecollegeabbr.length;i++){thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]); }

// now put the data into a select element
for(i=0;i<thecollegechoices.length;i++){$(“#firstcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

$( ‘#firstcollegechoice’ ).on(“change”, function(){
//$(“#debugzone”).html($(this).val() + ” chosen now build the second select<br />”);
$(“#secondcollegechoice”).html(“<option value=”>Second Choice</option>”).removeAttr(“disabled”);$(“#thirdcollegechoice”).html(“<option value=”>Third Choice</option>”).attr(“disabled”, “disabled”);
var thecollegechoices=[];
for(i=0;i<thecollegeabbr.length;i++){
// check here to see if the choice is used in the first select.
if(thecollegeabbr[i]!=$(“#firstcollegechoice :selected”).val()){thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]);}
}

for(i=0;i<thecollegechoices.length;i++){$(“#secondcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

});

$( ‘#secondcollegechoice’ ).on(“change”, function(){
//$(“#debugzone”).html($(this).val() + ” chosen now build the third select<br />”);
$(“#thirdcollegechoice”).html(“<option value=”>Third Choice</option>”).removeAttr(“disabled”);
var thecollegechoices=[];
for(i=0;i<thecollegeabbr.length;i++){
// check here to see if the choice is used in the first select.
if(thecollegeabbr[i]!=$(“#firstcollegechoice :selected”).val() && thecollegeabbr[i]!=$(“#secondcollegechoice :selected”).val()){
thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]);
}
}

for(i=0;i<thecollegechoices.length;i++){$(“#thirdcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

});

</script>
<!– end new content dev area –>

PHP expression and comparison techniques

Ternary operations:

If ($username !== “Deedubs”){$username=$newusername;}  You know what, this doesn’t need a shorthand notation, its nice and compact.

 

Search for a string within a string using php

Need to compare or discover a certain text inside a string on the server side? PHP has some great stuff for this.

strpos() will find the position of the first occurrence of a substring in a string. For example:
I want to find if the text “blue” is in the sentence “My blue heaven”.
$mystring=”My blue heaven”;
$findme=”blue”;
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// if the position  was the 0th (first) character.
if ($pos === false) {
echo “The string ‘$findme’ was not found in the string ‘$mystring'”;
} else {
echo “The string ‘$findme’ was found in the string ‘$mystring'”;
echo ” and exists at position $pos”;
}

find file extension using php

lets learn the search capabilities of php to find if the file is a jpg or a png file, and then perform an action.

$filename=”myfile.png”;
$fileextension = pathinfo($filename, PATHINFO_EXTENSION);

if($fileextension == “png”){echo(“we got a png to display.”)}else{echo(“jpg image display”);}

Works great for what I have goin on. Can’t reveal the deets, but it’s huge, of course.

 

Saving user data with cookies

The user needs to have a small amount of data saved so they don’t have to fill the same fields of a form out over and over. The best way to do this would be with a cookie set for the life of the form, for example, they will fill out a form frequently for three months, entering their name and personal info over and over. So, lets allow them to save the info, on click of a button, and load it in on return visits to the form.

I can set cookies with javascript or server side code. In this case I think that js would be the best. We need to have some basic functions for setting and getting cookies…

function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(” ” + c_name + “=”);
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + “=”);
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf(“=”, c_start) + 1;
var c_end = c_value.indexOf(“;”, c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
} // end get cookie function

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? “” : “; expires=”+exdate.toUTCString());
document.cookie=c_name + “=” + c_value;
} // end set cookie function

Once we have our basic cookie setting, reading and deleting functions, we can set up a function to save the user’s data, called when they click a button…

function saveInfo(){
//alert(‘lets gather the data and save to cookie’);
var nominator_firstname = $(“#nominator_firstname”).val();
var nominator_lastname = $(“#nominator_lastname”).val();
var nominator_org = $(“#nominator_org”).val();
var nominator_title = $(“#nominator_title”).val();
var nominator_address = $(“#nominator_address”).val();
setCookie(“nominator_firstname”,nominator_firstname,90);
setCookie(“nominator_lastname”,nominator_lastname,90);
setCookie(“nominator_org”,nominator_org,90);
setCookie(“nominator_title”,nominator_title,90);
setCookie(“nominator_address”,nominator_address,90);
alert(” Nominator Info Saved for 90 days”);
}

 

When the user comes back to the page,  I can check for the cookies and put them into the right place in the form using this function:

function checkCookie()
{
var nominator_firstname=getCookie(“nominator_firstname”);
var nominator_lastname=getCookie(“nominator_lastname”);
if (nominator_firstname!=null && nominator_firstname!=””) { $(“#nominator_firstname”).val(nominator_firstname); }
if (nominator_lastname!=null && nominator_lastname!=””) { $(“#nominator_lastname”).val(nominator_lastname); }

} // end check cookie function

Efficient JavaScript Best Practice:Arrays

I am going to research and document best practice to use js arrays.

Declare an array in JavaScript:

var myarray = [];

To assign a value to the array:

myarray[0] = “The first value”;
myarray[1] = “The second value”;

to insert a value at end of array:

myarray.push(“The third value”);
myarray.push(“The fourth”, “The fifth”);

The array.toString() will list the variables separated by a comma

 

 

Suppose I have a list of items that I would like to put into an array:


myarrayfromlist=[];
  • My list item one
  • My list item two
  • My list item three

$("#mylist li").each(
   function(){
     myarrayfromlist.push($(this).html())
  }
);

 

For a less complex situation where you don’t need custom keys, a standard array can be written as so… var coinsIhave = [1950, 1960, 1970, 1980, 1990, 2000, 2010];

then coinsIhave[0] is  1950.

How to I access the key of an item in the array, for example, what key is 1980?
Well, unfortunatley JavaScript doesn’t have a function for that. We can make our own, and in a less complex scenario, this would be ok.

[code]function findKey(whatkey, whatarray){
for(a=0;a<whatarray.length;a++){
if(whatarray[a].id==whatkey){
$(“#debuglog”).append(“<p>Array Item:”+whatarray[a].id+” || Key: ” + a +”</p>”);
return a;}
}

}[/code]

So if I were to execute findKey(coinsIhave, ‘1980’) it would return 3.

But if I want to know what kind of coin it is, as well as the year, I would like to use a dictionary object or associated array.

var coinsIhave=new Object();
coinsIhave.silverdollar=”1950″;
coinsIhave.centenialquarter=”1960″;

Although they can be called associated arrays, we are creating a JavaScript object and assigning properties. These properties can be assigned and accessed using dot or bracket notation. It is important to note that any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects#Indexing_object_properties

 

It is possible to “fake” a multidimensional array in JavaScript, using notation such as this:

var thecollegechoices=[[“CWU”,”Central University”], [“EWU”,”Eastern Wa University”]];

You would then access the data as so:

thecollegechoices[0][0] would contain the text “CWU”
thecollegechoices[0][1] would contain the text “Central University”
thecollegechoices[1][0] would contain the text “EWU”
thecollegechoices[1][1] would contain the text “Eastern Wa University”

So as we loop through the index of the array, we see the pattern that the abreviations would be in the 0, and the college name would be in the 1. This is going to come in very handy over the course of project development.

After reading the mozzilla docs, I have found a great way to loop through the array to use the items in the array:
[code]

var a = [“dog”, “cat”, “hen”];
for (var i = 0, item; item = a[i++];) {
// Do something with item
console.log(item);
}

[/code]

Note that this trick should only be used for arrays which you know do not contain “falsy” values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use the i, len idiom instead:

[code]
for (var i = 0, len = a.length; i < len; i++) {
// Do something with a[i]
}[/code]

[code]for (var i in a) {
// Do something with a[i]
}[/code]

HTML 5 template

here is marketing style template  page for an html5 project. this includes templates for favicon and apple touch icons as well as google analytics.

 

Here is the dwstyles html5 template. Basic seo header. Includes the dw styles library. No other librarys installed. Head to vendor site for latest JQuery, JQueryMobile etc.