Today is Sunday
September 5, 2010

Search Results Category: Coding

August 29, 2010

How to Check and Validate a file extension with JavaScript / jQuery

From time to time comes the need in almost every coders life to use an upload form on a page they are working on. Be it a single file upload form or a full form with contact information. In either event 99% of the time the case will be that the coder is going to want to double check the extension type. Grant it your going to want to check more than just that when you offer the ability to upload a file on to any server you are running a site on. To prevent a malicious user from attempting to hijack your site. I do feel however that it is worth mentioning that this only one of at very least several precautions you should take. This function alone will not secure your uploads 100%

The Function:

function checkExtension() {
  var extension = new Array(".png",".gif",".jpg",".jpeg",".tif",".pdf");
  var fieldvalue = $('#thefile').val();
  //var fieldvalue = document.formName.fieldName.value;
  var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));
    for(>var i = 0; i < extension.length; i++) {
      if(thisext == extension[i]) { alert("File type: Allowed"); return >true; } else { alert("File type: Not Allowed"); return >false; }
    }
}

Example of use:

<form action="#none" name="testUpload">
<input type="file" name="myfile2up" value="" /> <input value="Upload" type="button" onClick="checkExtension(); return false;" />
</form>


Demo:

Extra information:
The actual upload portion of this script has been disabled, this form will not upload anything it is for demo purpose only.

Allowed file types in this demo are:
".png",".gif",".jpg",".jpeg",".tif",".pdf"

August 21, 2010

JavaScript jQuery Jump to Anchor tag automaticly

by Chris — Categories: Coding, Javascript, jQueryNo Comments

Well assuming you know standard HTML and how to use it by now you should likely know how to set an anchor and jump to it with a static link.

For Example:

<a name="news">News Header</a>
<a href="#news">View News</a>

However what you might now know is how to have it jump automatically. This little function will help you do that. I will layout 2 versions of this function both pretty much one in the same thing however one you can define the page along with the anchor name and the other just the anchor for use with the same page its being used on.

function theAnchor(anchorName) {
   var sPath = window.location.pathname;
   var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
   location.href = sPage+"#"+anchorName
}
function theAnchorX(thePage, anchorName) {
   location.href = thePage+"#"+anchorName
}

Now the idea of using either of these functions is dependent upon you. How I would be likely to use them is through a conditional statement like if-else or case. But its not limited to that, you could use it just about anywhere you would place JavaScript.

jQuery is my checkbox checked

by Chris — Categories: AJAX, Coding, Javascript, jQuery1 Comment

Ok well first off let me establish that this is just straight JavaScript and not jQuery. However I post it notably as such due to it being such a big question. How do I use jQuery to see if my checkbox is checked. Because if you search for your answer (until someone else copies this article in there own words) your only going to come up with how to find maybe at best how to count checkboxes that are checked through the .length() function. You may come up with something about using the .is() or you might be told how to retrieve the .val().

But you don’t want to do any of those do you?. You just want to know if a particular checkbox one lonely little checkbox is checked. Then if it is checked run a particular bit of code, if its not checked then you want to do something else. But you really can’t find it in your searches. Well I feel your pain, I have done the same search as you looking for the answer. I gave up on my search though, I took what I knew already combined it with the little bits here and there that I noticed and came up with own rendition of how to do it. May not be the best, but works for what its worth and its rather light weight. So without any further waste of your time, here is your solution its been tested on Chrome, IE, FF, Opera, and Safari

function isitchecked(chk){
 var theCheckBox = document.getElementById(chk);
  if(theCheckBox.checked == 1){
    alert("Checked");
  }else{
    alert("Not Checked");
    theCheckBox.checked = 1; // will check automaticly if not
  }
}

Demo:

Example of use:

<input type="checkbox" name="checkme" id="checkme" /> <input type="button" value="Push me.." onclick="isitchecked('checkme')">

August 4, 2010

Clear Form input or text when user clicks on it JavaScript

by Chris — Categories: Coding, Javascript2 Comments

Ever want to clear a text file of its default value when the user clicks on it? Best example of this would be on search boxes or login forms. Where a web developer wants to have the default values of the form fields given be examples of what they are looking for in the form element. Well I have a simple version of that you can implement by adding only a couple lines of code to your existing page.

The Code:

<script type="text/javascript"> 
function clearIt(el) {if (el.defaultValue==el.value) el.value = ""}
</script>

How to use it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="example.php" method="post" id="example">
<input tabindex="1" type="text" name="elName" id="elName" value="user@exmple.com" onfocus="clearIt(this)">
</form>
<script type="text/javascript">
function clearIt(el) {if (el.defaultValue==el.value) el.value = ""}
</script>
</body>
</html>

Demo:

August 3, 2010

Finding and Verifying U.S. Dollar amounts with PHP

by Chris — Categories: Coding, PHP — Tags: , 1 Comment

Ok so the idea is you have a user input form. In that form you have your users providing a dollar amount of some sort. But how do you verify this dollar amount is correct. Meaning is it a numeric value, is it in a dollar format, etc.. Well with this little function I hope to help you achieve finding out a little easier that the posted variable is indeed a valid dollar amount or not.

function verifyMoney($what){
   if (preg_match('#^[0-9]+(\.[0-9]{0,2})?$#', $what)){
     $monkey = number_format($what, 2);
     return $monkey;
   }else{ return FALSE; }
}

What this will do is if the dollar amount is not both numeric and in a dollar format (ie: 0.00) it will return false, otherwise it will return what its given.

Demo:
Good: 1,502.38
Bad: 10O.00 came back false.

Example of usage:

$goodmoney = "1502.38";
$badmoney = "10O.00";

if(verifyMoney($goodmoney) !== FALSE) {echo "Good: ".verifyMoney($goodmoney);}else{echo "The Dollar amount you have entered is not valid";}
echo "<br />";

if(verifyMoney($badmoney) == FALSE) {echo "Bad: ".$badmoney." came back false.";}else{echo "The Dollar amount you have entered is valid";}

How to use PHP mail() with HTML and CSS

by Chris — Categories: Coding, PHP — Tags: 1 Comment

The  php mail() function. Such a simple function with so much versatility. Now I know, I know.. trust me I know! There are dozens of tutorials out there on the subject of PHP mail() and its functionality. But how many of them are based off the core concept, and how to use it statically at best with hard coded variables. Example…

$email = "myemail@exmple.com";
$subject4email = "This is a Subject";
$message4email = "Thanks for triggering this email to be sent";
mail($email, $subject4email, $message4email);

How many “php mail” tutorials have you seen like that today while searching for your solution? Chances are they are long winded but up the ally of just giving you the above mentioned code.

Well with this short post I intend on showing you a way many people spend hours searching for to end up sitting on forums eventually waiting for an answer that may never come. PHP’s mail() function is great. But as mentioned above almost all people who give tutorials on the subject show the most core basic concept. Which is fine if you plan to send your self emails in plain text. What I want to show you here is based on the ever growing demand for wanting to send something a bit fancier to your users or even yourself (if your like me, even personal statistics and logs have to look ascetically pleasing even if its only me who will ever see it). So in this post I will give you the core basics of how to code a HTML based template using CSS and standard HTML for use with Email and being sent through PHP. Mind you basic. Im not going to provide you with a fully custom tailored solution. I want to leave it open a bit so you can build on it with ease. This example could be used for example if you have an automated mail to go to new members on your site but its far from limited to the idea of just that.

Full Code:

$mydomain = "somedomain.net";
$username = $selectusers;
$email_who = $selectusersemails;
$titlesubject = $mymessagetitle;
$messagebody = $mymessage;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
  <head>
<title>' . $titlesubject . '</title>
</head>
<style type="text/css">
<!--
body {background: #edebea;}
#wrapper {background: #fff;border: 4px solid #ddd;}
-->
</style>
</head>
<body><table width="650" id="wrapper">
<tr>
<td>Your Sites Image Logo or slogan or text or link</td>
<td>Dear '.$username.'</td>
<td>'.$messagebody.'</td>
<td>Footer information, copyrights, other..</td>
</tr>
</table>
</body>
</html>
';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=us-ascii' . "\r\n";
$headers .= 'From: noreply@'. $mydomain . "\r\n";
$headers .= 'Reply-To: noreply@'. $mydomain . "\r\n";
$headers .= '1\r\nX-MSMail-Priority: High' . "\r\n";
$headers .= 'X-Mailer: Monkey Tooth Productions Mailer v1.0.0' . "\r\n";
mail($email_who, $titlesubject, $message, $headers);

Now with the above You can see sending an HTML based email through PHP’s mail() function is not as hard as one would have thought, yet its a pain in the arse to find information on (or was when I last looked some time ago, but then again I still see it asked in forums a lot so either way I suppose).

Now as you can see as I mentioned before this is thee absolute core concept of sending an HTML based email with CSS with PHP

$username = $selectusers;
$email_who = $selectusersemails;
$titlesubject = $mymessagetitle;
$messagebody = $mymessage;

The above four variables can be set to anything and set through any means you choose whether is something through a database query or hard coded in to a combination of the two. However only two of the four above are required with the above mentioned script. Those being $titlesubject and $email_who but you can populate them however you wish. The other two $messagebody and $username are solely for the sake of example within the $message variable.

Now its worth mentioning as you can see I added a variable for the domain $mydomain All though you could use anything its suggested that you keep it specific to your domain the main reason I added this one variable is if you look at the script you will notice that its called a few times within the headers for example. I figured one place to edit it is easier than several. Main reason you want to keep it specific to your domain is well despite what you change it to the email ISP provider will be able to track it back to your domain. So making it something different will only trigger the email provider to throw it in the spam folder. All in all since I mention the spam concept It is possible to have all your emails land directly in the spam box of any give email you send But that will almost always be due to your choice of $messagebody variable in this example. I say this because I have been using this concept for years now with very little feedback of my messages landing in someone spam bin. Mind you I specify mine as I am careful with my messages. I keep them low key with little to no references that can trigger a spam filter into throwing the email into a spam folder.

Prevention Tips try not to use to many links in your emails sent if you have to try to use full urls as you would for the link itself to go to as the links text as well if they match its good use a spell check on your message prior to sending to many misspelled words can be bad to.

Convert a Unix Timestamp to MySQL DATETIME Timestamp with PHP using date()

Well if your like me you like to diversify your usage of timestamps or just like me as well when I first got into coding with PHP I didn’t know much about how to properly mesh PHP with a MySQL Database, and to be quite frank the tutorials out there at the time and even currently (Well the ones with any search engine rankings at least) Still show how us to use a time() based timestamp on many of our elements. However a couple key issues with that now a days is if your going to make any site about anything with any form of user end input, feedback, or otherwise your going to eventually need to use a database for it. Or a part there of at the very least, that said if your using older timestamps like the time() function generates then you already know the problem. Actually you must know if your skimming through this post. Now where the time() function seems like the best bet as its the easiest to do math with for things like session time outs, its not typically prime for so many of mySQL’s features for date ranges and other various time/date functions within mySQL that make handling sessions and so much more easier now a days. So here it is, my simple little solution

function unixToMySQL($timestamp){
return date('Y-m-d H:i:s', $timestamp);
}

Unix Timestamp Example: 1283664560
Above Timestamp converted to MySQL DATETIME: 2010-09-05 05:29:20

I use it as a function just out of my own practices to call things from a global file that contain functions used widely through out sites I develop. This function can also be developed upon heavily to do various other conversions but I figured I would give you what I found most people look for specifically. Myself included at one time. The live example above is equivilant to a MySQL DATETIME date using NOW()

Example of usage:

$blah = time();
echo unixToMySQL($blah);

Display Random YouTube Videos on your site or blog with PHP

by Chris — Categories: Coding, PHP — Tags: , , 4 Comments

Well here is another random function from my little repository.. A little while back one of my clients presented me with the idea that they wanted to display a set of videos from there YouTube gallery at random on there home page and various other sections of there site. But only specific videos did they want. So from that I created a little function. That would do just that. I will say though this function is a bit toned down from what I actually gave them as they wanted a small control panel to go with it ran off a mysql database so they could add and remove videos from from randomly chosen videos they provided from there YouTube gallery they also wanted to provide a brief description on there page for each one as well amongst a couple other things with it. Which I may re-tailor that version of the script eventually and release it to the public as I think its a nice idea. Could make for a good 404 error page or like with them a good way to keep the content on there main page changing but also display some of there portfolio of videos at the same time.

Anyway back to the meat of this article I doubt you want to read more than you have to and lets face it, if you’ve seen my other articles here you would know writing isn’t really my forte. That said heres the code and a brief explanation and as always a demo of it working.

function randomTube(){
    $RVideoArray = array('q8SWMAQYQf0', 'q8SWMAQYQf0', 'q8SWMAQYQf0', 'hpxxvOU3vbI');
    $RVideoCount = count($RVideoArray);
    $RVideoSelect = rand(0, $RVideoCount - 1);
    $RVideoNum = trim($RVideoSelect);
    $RVideo = $RVideoArray[$RVideoNum];
    $theTube = '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'.$RVideo.'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'.$RVideo.'" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>';
    return $theTube;
}

In this version of the script, I have set up an array that you can add/remove you’re choice of YouTube videos from. All you need to do is obtain the YouTube short code for the video or what ever it is they call it specificly, I call it short code cause to me it resembles a familiar look/feel to that of a short URL through something like bit.ly. But thats off topic. With almost any youtube video there is always a URL construct similar to www.youtube.com/watch?v= what follows the v= and in some cases comes before the next & is the actual bit of the URL you are looking for to use with the array $RVideoArray in the function above.

Example of usage for the Random YouTube video function is.

$myRandomVideo = randomTube(); echo $myRandomVideo;

June 27, 2010

Javascript vs PHP

by Chris — Categories: Coding, Javascript, PHP — Tags: , , , 7 Comments

This is a question I often see and get. “Which one should I use, JavaScript or php?” Well in the end it all boils down to what your doing and how your are expecting it to handle. The biggest key differences between JavaScript and PHP is one runs or renders rather while the page is loading. While the other can do stuff to a page while its loading or after it has loaded.

Both languages are very similar in construct or at least they are in my opinion, and you write code almost the same way. Obviously they have different built in functions, and names for the functions, and they differ here and there. Generally you can almost do anything with JavaScript that you can with PHP and vice versa.

Now comes again the question “Which should I use?”. Well I personally like PHP for a wide array of things and will generally use it over JavaScript when possible however with todays technology always trying to push the bar up and tempting to break the barriers of just how far you can push someones browsers abilities I do favor AJAX which is the use of PHP and JavaScript together. I say “when possible” because there are times where it definitely is not wise to use AJAX. But thats only due to security concerns. But worry not, most applications you will build with AJAX if you use it wisely and properly you wont have much to worry about. Which one day I am sure I will write an article or many about that.

If you want your elements to be flashy and less bandwidth consuming I would suggest using JavaScript where and when possible to handle your pages content and how its loaded, then handled there after. If bandwidth isn’t much of an issue for you which with most hosting providers it isn’t (unless your pushing several thousands of gigs of there bandwidth a month, then you should check the fine print in there contracts). Then handle everything via PHP its a bit more static, pages have to load but if used properly its as secure as it gets, and can run pretty fast as well.

If your interested in going the AJAX route which I highly recommend I would suggest using jQuery. As its the most stable and mature of frameworks out there and has a much larger community of developers to help get answers from if you ever get stuck.

Are you recently starting out with php, javascript, ajax, mysql, or really any web related scripting language? If you are might I suggest to you a site that helped even me learn the basics years upon years ago. http://www.tizag.com they don’t cover everything, but they cover more than just the simple basics and can give you a good footing on any given scripting language.

AJAX ready frameworks that you can choose from in no particular order (obtained from Wikipedia):

jQuery
jQuery UI (used with jQuery)
Prototype
Script.aculo.us (used with prototype)
Ext (now known as Sencha)
MooTools
Yahoo! UI Library
Dojo Toolkit

Quick Question I see with these framworks mostly due to people searching for ready made scripts is can you use more than one framework. Well ultimately it depends which you use. I know jQuery (even combined with UI) you can set it up to allow other frameworks as mentioned on the jQuery site in there article/post about the subject Using jQuery with Other Libraries however outside of that I cant really vouch for the other libraries and there support on the subject as I prefer jQuery and use that over the rest when ever possible (unless I am working on a clients site and they have something different from jQuery)

June 23, 2010

PHP create a random string of Alpha/Numeric Characters

by Chris — Categories: Coding, PHP — Tags: , , No Comments

Have a need for a quick random string of any given length but want to limit it to a-z 0-9. Then this would be ideal for you, I really can’t think of any real world use for this. Well no thats wrong, you can use it as a random password generator. Or something to the effect of that.

<?php
function genRandomString($howbig) {
$length = $howbig;
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$string = '';

for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}

return $string;
}
echo "<strong>5 char string:</strong> ". genRandomString('5') ."<br />";
echo "<strong>10 char string:</strong> ".genRandomString('10')."<br />";
echo "<strong>15 char string:</strong> ".genRandomString('15')."<br />";
echo "<strong>20 char string:</strong> ".genRandomString('20')."<br />";
echo "<strong>50 char string:</strong> ".genRandomString('50')."<br />";
?>

Example of use:
5 char string: 4a6wx
10 char string: gaawbpbrux
15 char string: 16eds8dtwui1p0
20 char string: qyh1p9b7e3i88c0edh04
50 char string: oz36rujz3i7tmslcqb21eoqaj5bhuo7ve2zl7tpmhmq809xn

© 2010 Monkey Tooth Productions All rights reserved - Wallow theme by TwoBeers Crew - Powered by WordPress - Have fun!