Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Justas http://www.webtoolkit.info/

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

PHP password generator

This is a random php password generator. This function is a complete, working password generator implementation for PHP. It allows the developer to customize the password: set password length and strength. Just include this function anywhere in your code and then use it.

More code snippets you can find on free code and tutorials website.

   1  
   2  function generatePassword($length=9, $strength=0) {
   3      $vowels = 'aeuy';
   4      $consonants = 'bdghjmnpqrstvz';
   5      if ($strength & 1) {
   6          $consonants .= 'BDGHJLMNPQRSTVWXZ';
   7      }
   8      if ($strength & 2) {
   9          $vowels .= "AEUY";
  10      }
  11      if ($strength & 4) {
  12          $consonants .= '23456789';
  13      }
  14      if ($strength & 8) {
  15          $consonants .= '@#$%';
  16      }
  17  
  18      $password = '';
  19      $alt = time() % 2;
  20      srand(time());
  21      for ($i = 0; $i < $length; $i++) {
  22          if ($alt == 1) {
  23              $password .= $consonants[(rand() % strlen($consonants))];
  24              $alt = 0;
  25          } else {
  26              $password .= $vowels[(rand() % strlen($vowels))];
  27              $alt = 1;
  28          }
  29      }
  30      return $password;
  31  }

Javascript sprintf

Several programming languages implement a sprintf function, to output a formatted string. It originated from the C programming language, printf function. Its a string manipulation function.

This is limited Javascript sprintf implementation. Function returns a string formatted by the usual printf conventions.

More code snippets you can find on free code and tutorials website.

   1  
   2  /**
   3  *
   4  * Javascript sprintf
   5  * http://www.webtoolkit.info/
   6  *
   7  *
   8  **/
   9  
  10  sprintfWrapper = {
  11  
  12      init : function () {
  13  
  14          if (typeof arguments == &quot;undefined&quot;) { return null; }
  15          if (arguments.length &lt; 1) { return null; }
  16          if (typeof arguments[0] != &quot;string&quot;) { return null; }
  17          if (typeof RegExp == &quot;undefined&quot;) { return null; }
  18  
  19          var string = arguments[0];
  20          var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
  21          var matches = new Array();
  22          var strings = new Array();
  23          var convCount = 0;
  24          var stringPosStart = 0;
  25          var stringPosEnd = 0;
  26          var matchPosEnd = 0;
  27          var newString = '';
  28          var match = null;
  29  
  30          while (match = exp.exec(string)) {
  31              if (match[9]) { convCount += 1; }
  32  
  33              stringPosStart = matchPosEnd;
  34              stringPosEnd = exp.lastIndex - match[0].length;
  35              strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
  36  
  37              matchPosEnd = exp.lastIndex;
  38              matches[matches.length] = {
  39                  match: match[0],
  40                  left: match[3] ? true : false,
  41                  sign: match[4] || '',
  42                  pad: match[5] || ' ',
  43                  min: match[6] || 0,
  44                  precision: match[8],
  45                  code: match[9] || '%',
  46                  negative: parseInt(arguments[convCount]) &lt; 0 ? true : false,
  47                  argument: String(arguments[convCount])
  48              };
  49          }
  50          strings[strings.length] = string.substring(matchPosEnd);
  51  
  52          if (matches.length == 0) { return string; }
  53          if ((arguments.length - 1) &lt; convCount) { return null; }
  54  
  55          var code = null;
  56          var match = null;
  57          var i = null;
  58  
  59          for (i=0; i&lt;matches.length; i++) {
  60  
  61              if (matches[i].code == '%') { substitution = '%' }
  62              else if (matches[i].code == 'b') {
  63                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
  64                  substitution = sprintfWrapper.convert(matches[i], true);
  65              }
  66              else if (matches[i].code == 'c') {
  67                  matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
  68                  substitution = sprintfWrapper.convert(matches[i], true);
  69              }
  70              else if (matches[i].code == 'd') {
  71                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
  72                  substitution = sprintfWrapper.convert(matches[i]);
  73              }
  74              else if (matches[i].code == 'f') {
  75                  matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
  76                  substitution = sprintfWrapper.convert(matches[i]);
  77              }
  78              else if (matches[i].code == 'o') {
  79                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
  80                  substitution = sprintfWrapper.convert(matches[i]);
  81              }
  82              else if (matches[i].code == 's') {
  83                  matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
  84                  substitution = sprintfWrapper.convert(matches[i], true);
  85              }
  86              else if (matches[i].code == 'x') {
  87                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
  88                  substitution = sprintfWrapper.convert(matches[i]);
  89              }
  90              else if (matches[i].code == 'X') {
  91                  matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
  92                  substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
  93              }
  94              else {
  95                  substitution = matches[i].match;
  96              }
  97  
  98              newString += strings[i];
  99              newString += substitution;
 100  
 101          }
 102          newString += strings[i];
 103  
 104          return newString;
 105  
 106      },
 107  
 108      convert : function(match, nosign){
 109          if (nosign) {
 110              match.sign = '';
 111          } else {
 112              match.sign = match.negative ? '-' : match.sign;
 113          }
 114          var l = match.min - match.argument.length + 1 - match.sign.length;
 115          var pad = new Array(l &lt; 0 ? 0 : l).join(match.pad);
 116          if (!match.left) {
 117              if (match.pad == &quot;0&quot; || nosign) {
 118                  return match.sign + pad + match.argument;
 119              } else {
 120                  return pad + match.sign + match.argument;
 121              }
 122          } else {
 123              if (match.pad == &quot;0&quot; || nosign) {
 124                  return match.sign + match.argument + pad.replace(/0/g, ' ');
 125              } else {
 126                  return match.sign + match.argument + pad;
 127              }
 128          }
 129      }
 130  }
 131  
 132  sprintf = sprintfWrapper.init;

Javascript trim

In programming, trim is a string manipulation function or algorithm. The most popular variants of the trim function strip only the beginning or end of the string. Typically named ltrim and rtrim respectively.

Javascript trim implementation removes all leading and trailing occurrences of a set of characters specified. If no characters are specified it will trim whitespace characters from the beginning or end or both of the string.

More code snippets you can find on free code and tutorials website.

   1  
   2  /**
   3  *
   4  * Javascript trim, ltrim, rtrim
   5  * http://www.webtoolkit.info/
   6  *
   7  *
   8  **/
   9  
  10  
  11  function trim(str, chars) {
  12      return ltrim(rtrim(str, chars), chars);
  13  }
  14  
  15  function ltrim(str, chars) {
  16      chars = chars || "\\s";
  17      return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
  18  }
  19  
  20  function rtrim(str, chars) {
  21      chars = chars || "\\s";
  22      return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
  23  }

Javascript open window

Javascript open window sometimes is useful for adding a popup window to your pages. When the user clicks on a link, a new window opens and displays a page. Demo can be found on this script homepage - free code and tutorials website.

   1  
   2  /**
   3  *
   4  *  Javascript open window
   5  *  http://www.webtoolkit.info/
   6  *
   7  **/
   8  
   9  function openWindow(anchor, options) {
  10  
  11  	var args = '';
  12  
  13  	if (typeof(options) == 'undefined') { var options = new Object(); }
  14  	if (typeof(options.name) == 'undefined') { options.name = 'win' + Math.round(Math.random()*100000); }
  15  
  16  	if (typeof(options.height) != 'undefined' && typeof(options.fullscreen) == 'undefined') {
  17  		args += "height=" + options.height + ",";
  18  	}
  19  
  20  	if (typeof(options.width) != 'undefined' && typeof(options.fullscreen) == 'undefined') {
  21  		args += "width=" + options.width + ",";
  22  	}
  23  
  24  	if (typeof(options.fullscreen) != 'undefined') {
  25  		args += "width=" + screen.availWidth + ",";
  26  		args += "height=" + screen.availHeight + ",";
  27  	}
  28  
  29  	if (typeof(options.center) == 'undefined') {
  30  		options.x = 0;
  31  		options.y = 0;
  32  		args += "screenx=" + options.x + ",";
  33  		args += "screeny=" + options.y + ",";
  34  		args += "left=" + options.x + ",";
  35  		args += "top=" + options.y + ",";
  36  	}
  37  
  38  	if (typeof(options.center) != 'undefined' && typeof(options.fullscreen) == 'undefined') {
  39  		options.y=Math.floor((screen.availHeight-(options.height || screen.height))/2)-(screen.height-screen.availHeight);
  40  		options.x=Math.floor((screen.availWidth-(options.width || screen.width))/2)-(screen.width-screen.availWidth);
  41  		args += "screenx=" + options.x + ",";
  42  		args += "screeny=" + options.y + ",";
  43  		args += "left=" + options.x + ",";
  44  		args += "top=" + options.y + ",";
  45  	}
  46  
  47  	if (typeof(options.scrollbars) != 'undefined') { args += "scrollbars=1,"; }
  48  	if (typeof(options.menubar) != 'undefined') { args += "menubar=1,"; }
  49  	if (typeof(options.locationbar) != 'undefined') { args += "location=1,"; }
  50  	if (typeof(options.resizable) != 'undefined') { args += "resizable=1,"; }
  51  
  52  	var win = window.open(anchor, options.name, args);
  53  	return false;
  54  
  55  }

Javascript cookies

Learn how to use an object with methods to save, read and erase cookies. Using these methods you can manipulate cookies on your site.
Demo can be found on this script homepage - free code and tutorials website.


   1  
   2  /**
   3  *
   4  *  Javascript cookies
   5  *  http://www.webtoolkit.info/
   6  *
   7  **/
   8  
   9  function CookieHandler() {
  10  
  11  	this.setCookie = function (name, value, seconds) {
  12  
  13  		if (typeof(seconds) != 'undefined') {
  14  			var date = new Date();
  15  			date.setTime(date.getTime() + (seconds*1000));
  16  			var expires = "; expires=" + date.toGMTString();
  17  		}
  18  		else {
  19  			var expires = "";
  20  		}
  21  
  22  		document.cookie = name+"="+value+expires+"; path=/";
  23  	}
  24  
  25  	this.getCookie = function (name) {
  26  
  27  		name = name + "=";
  28  		var carray = document.cookie.split(';');
  29  
  30  		for(var i=0;i < carray.length;i++) {
  31  			var c = carray[i];
  32  			while (c.charAt(0)==' ') c = c.substring(1,c.length);
  33  			if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
  34  		}
  35  
  36  		return null;
  37  	}
  38  
  39  	this.deleteCookie = function (name) {
  40  		this.setCookie(name, "", -1);
  41  	}
  42  
  43  }

AJAX file upload

Ever wanted to upload files using AJAX like in GMAIL, without reloading the page? Now you can. Cross browser method to upload files using AJAX in only 1Kb of code.
How to use AJAX file upload you can find on this script homepage - free code and tutorials website.

   1  
   2  /**
   3  *
   4  *  AJAX IFRAME METHOD (AIM)
   5  *  http://www.webtoolkit.info/
   6  *
   7  **/
   8  
   9  AIM = {
  10  
  11  	frame : function(c) {
  12  
  13  		var n = 'f' + Math.floor(Math.random() * 99999);
  14  		var d = document.createElement('DIV');
  15  		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
  16  		document.body.appendChild(d);
  17  
  18  		var i = document.getElementById(n);
  19  		if (c && typeof(c.onComplete) == 'function') {
  20  			i.onComplete = c.onComplete;
  21  		}
  22  
  23  		return n;
  24  	},
  25  
  26  	form : function(f, name) {
  27  		f.setAttribute('target', name);
  28  	},
  29  
  30  	submit : function(f, c) {
  31  		AIM.form(f, AIM.frame(c));
  32  		if (c && typeof(c.onStart) == 'function') {
  33  			return c.onStart();
  34  		} else {
  35  			return true;
  36  		}
  37  	},
  38  
  39  	loaded : function(id) {
  40  		var i = document.getElementById(id);
  41  		if (i.contentDocument) {
  42  			var d = i.contentDocument;
  43  		} else if (i.contentWindow) {
  44  			var d = i.contentWindow.document;
  45  		} else {
  46  			var d = window.frames[id].document;
  47  		}
  48  		if (d.location.href == "about:blank") {
  49  			return;
  50  		}
  51  
  52  		if (typeof(i.onComplete) == 'function') {
  53  			i.onComplete(d.body.innerHTML);
  54  		}
  55  	}
  56  
  57  }

javascript drag and drop

Ever wanted to drag an element or image on your webpage? You can try using this very lightweight javascript drag and drop. You can attach this drag handler to any relative or absolute positioned element. More code snippets you can find on free code and tutorials website.

   1  
   2  /**
   3  *
   4  *  Crossbrowser Drag Handler
   5  *  http://www.webtoolkit.info/
   6  *
   7  **/
   8  
   9  var DragHandler = {
  10  
  11  
  12  	// private property.
  13  	_oElem : null,
  14  
  15  
  16  	// public method. Attach drag handler to an element.
  17  	attach : function(oElem) {
  18  		oElem.onmousedown = DragHandler._dragBegin;
  19  
  20  		// callbacks
  21  		oElem.dragBegin = new Function();
  22  		oElem.drag = new Function();
  23  		oElem.dragEnd = new Function();
  24  
  25  		return oElem;
  26  	},
  27  
  28  
  29  	// private method. Begin drag process.
  30  	_dragBegin : function(e) {
  31  		var oElem = DragHandler._oElem = this;
  32  
  33  		if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
  34  		if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
  35  
  36  		var x = parseInt(oElem.style.left);
  37  		var y = parseInt(oElem.style.top);
  38  
  39  		e = e ? e : window.event;
  40  		oElem.mouseX = e.clientX;
  41  		oElem.mouseY = e.clientY;
  42  
  43  		oElem.dragBegin(oElem, x, y);
  44  
  45  		document.onmousemove = DragHandler._drag;
  46  		document.onmouseup = DragHandler._dragEnd;
  47  		return false;
  48  	},
  49  
  50  
  51  	// private method. Drag (move) element.
  52  	_drag : function(e) {
  53  		var oElem = DragHandler._oElem;
  54  
  55  		var x = parseInt(oElem.style.left);
  56  		var y = parseInt(oElem.style.top);
  57  
  58  		e = e ? e : window.event;
  59  		oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
  60  		oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';
  61  
  62  		oElem.mouseX = e.clientX;
  63  		oElem.mouseY = e.clientY;
  64  
  65  		oElem.drag(oElem, x, y);
  66  
  67  		return false;
  68  	},
  69  
  70  
  71  	// private method. Stop drag process.
  72  	_dragEnd : function() {
  73  		var oElem = DragHandler._oElem;
  74  
  75  		var x = parseInt(oElem.style.left);
  76  		var y = parseInt(oElem.style.top);
  77  
  78  		oElem.dragEnd(oElem, x, y);
  79  
  80  		document.onmousemove = null;
  81  		document.onmouseup = null;
  82  		DragHandler._oElem = null;
  83  	}
  84  
  85  }
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS