Tuesday, November 21, 2006

How to validate CSS file online?

http://jigsaw.w3.org/css-validator/

How to validate HTML file online?

http://validator.w3.org/

How to move selected items from one select box to another using Javascript?

//to move selected items from one select box to another
function move(fbox, tbox) {

var arrFbox = new Array();
var arrTbox = new Array();
var arrLookup = new Array();
var i;
if(fbox.options.length==0) {
alert('No items available to move');
return false;
}
for (i = 0; i < tbox.options.length; i++) {
arrLookup[tbox.options[i].text] = tbox.options[i].value;
arrTbox[i] = tbox.options[i].text;
}
var fLength = 0;
var sLength = arrTbox.length;
var tLength = arrTbox.length;
for(i = 0; i < fbox.options.length; i++) {
arrLookup[fbox.options[i].text] = fbox.options[i].value;
if (fbox.options[i].selected && fbox.options[i].value != "") {
arrTbox[tLength] = fbox.options[i].text;
tLength++;
}
else {
arrFbox[fLength] = fbox.options[i].text;
fLength++;
}
}
if(sLength == tLength) {
alert('Please select atleast one');
return false;
}

arrFbox.sort();
arrTbox.sort();
fbox.length = 0;
tbox.length = 0;
var c;
for(c = 0; c < arrFbox.length; c++) {
var no = new Option();
no.value = arrLookup[arrFbox[c]];
no.text = arrFbox[c];
fbox[c] = no;
}
for(c = 0; c < arrTbox.length; c++) {
var no = new Option();
no.value = arrLookup[arrTbox[c]];
no.text = arrTbox[c];
tbox[c] = no;
}
}

//Usage
<select multiple size="5" name="SB1[]" id="SB1">
<option>1</option><option>2</option>3<option></option>4<option></option><option>5</option>
</select>

<input type="button" onClick="move(this.form.SB1,this.form.SB2)" value=">>">
<input type="button" onClick="move(this.form.SB2,this.form.SB1)" value="<<">

<select multiple size="5" name="SB2[]" id="SB2"></select>

How to create thumbnail using PHP?

<?php
// useage is thumbnail.php?im=imagename.jpg
// set for 120 px thumb
$im=$_GET['imgname'];
Header("Content-type: image/jpeg");
$orig_image = imagecreatefromjpeg($im);
list($width, $height, $type, $attr) = getimagesize($im);
if ($width > 120) {
$ratio = 120 / $width;
$newheight = $ratio * $height; }
else $newheight = $height;
$sm_image = imagecreatetruecolor(120,$newheight) or die ("Cannot Initialize new gd image stream");;
Imagecopyresampled($sm_image,$orig_image,0,0,0,0,120,$newheight,imagesx($orig_image),imagesy($orig_image));
imageJPEG($sm_image);
imagedestroy($sm_image);
imageDestroy($orig_image);
?>

//Usage
$t="thumbnail.php?imgname=images/1.jpg";
<img src=".$t.">

How to validate user against LDAP using PHP?

//SCRIPT TO VALIDATE USER AGAINST LDAP

// using ldap bind *** NOTE the uid *****
$ldaprdn = 'uid=USERID,dc=DCVALUE,dc=DCDOMAIN'; // ldap rdn or dn
$ldappass = 'PASSWORD'; // associated password

// connect to ldap server
$ldapconn = ldap_connect("CONNECTIONSTRING");

if(!$ldapconn)
{
echo "Could not connect to LDAP server.";
exit;
}

ldap_set_option($ldapconn, LDAP_OPT_SIZELIMIT, 0); // Set Size Limit to 0
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); //Set Protocol Version to 3

if ($ldapconn) {

$bind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
if(!$bind)
{
echo "LDAP server bind error.";
}

//Search on the LDAP Directory
$base_dn = "BASEDNVALUE";
$filter = "uid=USERID";
$inforequired = array("uid","mail","cn","sn"); //information required from the LDAP directory

$result = ldap_search($ldapconn,$base_dn,$filter,$inforequired); //search LDAP Directory

//Get the Search Result
$info = ldap_get_entries($ldapconn,$result);
if(!$result)
{
echo "Anonymous Search Failed";
}
if($info["count"] == 0)
{
echo "No records found";
}

if($info["count"] > 1)
{
echo "More than one such user - report to CITS";
exit;
}

//Login again with the username and password posted to check authentication
$user_dn = $info[0]["dn"];
$bind = @ldap_bind($ldapconn,$user_dn,$_SERVER['PHP_AUTH_PW']);
if(!$bind)
{
echo 'Bind failed. User Not Authenticated';
exit;
}

$login_user_id=$etype . $info[0]["uid"][0];
}

Sending Mail using class in PHP

PHP Mailer

http://phpmailer.sourceforge.net/

File Uploading using class in PHP

Easy PHP Upload

http://www.finalwebsites.com/snippets.php?id=7

Function to convert time into various formats using PHP.

function time_convert($time,$type){
$time_hour=substr($time,0,2);
$time_minute=substr($time,3,2);
$time_seconds=substr($time,6,2);
if($type == 1):
// 12 Hour Format with uppercase AM-PM
$time=date("h:i A", mktime($time_hour,$time_minute,$time_seconds));
elseif($type == 2):
// 12 Hour Format with lowercase am-pm
$time=date("h:i a", mktime($time_hour,$time_minute,$time_seconds));
elseif($type == 3):
// 24 Hour Format
$time=date("H:i", mktime($time_hour,$time_minute,$time_seconds));
elseif($type == 4):
// Swatch Internet time 000 through 999
$time=date("B", mktime($time_hour,$time_minute,$time_seconds));
elseif($type == 5):
// 9:30:23 PM
$time=date("h:i:s A", mktime($time_hour,$time_minute,$time_seconds));
elseif($type == 6):
// 9:30 PM with timezone, EX: EST, MDT
$time=date("h:i A T", mktime($time_hour,$time_minute,$time_seconds));
elseif($type == 7):
// Different to Greenwich(GMT) time in hours
$time=date("O", mktime($time_hour,$time_minute,$time_seconds));
endif;
return $time;
};

How to get last inserted auto increment value using MySQL?

mysql>Select LAST_INSERT_ID();

The LAST_INSERT_ID() is unique to the login session. This can be used to update foreign keys.

If your session didn't update any records, LAST_INSERT_ID() will be zero.

Wednesday, November 08, 2006

How to delete all files in a folder and then the folder using PHP?

//Function to delete all files in a folder and then the folder too..
function DeleteFolder($dir) {
$d = dir($dir);
while($entry = $d->read()) {
if ($entry!= "." && $entry!= "..") {
unlink($dir.$entry);
}
}
$d->close();
rmdir($dir);
}

//Usage
DeleteFolder("/uploads/");

How to get filenames of a folder using PHP?

//Function to return filenames of a particular directory
function GetFileNames($dir) {
if (is_dir($dir)) {
if($dh = opendir($dir)) {
while (false !== ($file = readdir($dh))) {
if ($file != "." && $file != "..") {
$file_names[]=$file;
}
}
closedir($dh);
}
}
return $file_names;
}

//Usage
print_r(GetFileNames("/uploads/"));

Tuesday, November 07, 2006

How to rotate a image in HTML?

<HTML>
<HEAD>
<TITLE>Untitled Document</TITLE>
</HEAD>

<BODY bgcolor="#FFFFFF" text="#000000">
<DIV ID="oDiv" STYLE="position:absolute; left:300px;">
<IMG SRC="me2.jpg">
</DIV>
<BUTTON onclick="oDiv.style.filter=
'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)'">
Rotate 90 degrees
</BUTTON>
<!--rotation =
0 no rotation
1 rotate 90 degrees
2 rotate 180 degrees
3 rotate 270 degrees -->
</BODY>
</HTML>

Do end your URL's with a forward slash in your links

If you have a URL (web address) that does not specify an exact page, then you want to trail the URL with a forward slash:
<a href=" http://www.sitename.com/ ">Creating Web Sites</a>
In the above link, you will notice that after the '.COM' I placed a forward slash (/).
If the link were pointing to a particular page, I wouldn't add the forward slash at the end of the address:
<a href=" http://www.sitename.com/articles/index.htm ">Creating Web Sites Articles Page</a>
- By adding the forward slash (as in the first example), we remove a step that otherwise the web server and browser would have to take; removing this extra step can give you a speed boost. So to sum it up:
If your link is pointing to a particular file (an html page or a PHP page or an ASP page etc ...) you don't want to use the trailing slash. But if you are pointing to a directory like:
<a href=" http://www.sitename.com/articles/">Articles</a>
Then you want the trailing slash.

Common HTML Tags that should not be used

The following is a shortlist of commonly used tags that should not be used. Most of these tags can be replaced with CSS.

<b>...</b> Bold tag Video
<i> ... </i> Italic tag
<font> ... </font> Font tag
<center> ... </center>
<applet> ... </applet> Used to insert Java applets - mini programs written in Java. Today you should use the <object> tag. Java applets are just a pain in the neck anyway because of Java runtime compatibility issues ... use Flash MX instead.
<u> ... </u> Underlined text
<frameset> <frame src="..." /> </frameset> comments: framesets were largely used to format pages due to the limitations of HTML - limitations that no longer exist. Use CSS and iframes and forget about frames!

How to make our own PHP text box link to Google?

<?php
if($_POST){
$searchtext = $_POST['search'];
echo '<p align="center"> <meta http-equiv="Refresh" content="1;URL=http://www.google.ca/search?hl=en&q=';
echo $searchtext;
echo '&btnG=Google+Search&meta=">';
echo '<b>CONNECTING TO GOOGLE...</b>';
}
else
{
echo '<form name="form1" method="post" action="googlesearch.php">
<input type="text" name="search">
<input type="submit" name="Submit" value="Search">
</form>';
}
?>

Simplifying MySQL Results using PHP - No More Arrays

We all know this sort of query to get some simple from the Database:

include('connect.php');
$query = "SELECT * FROM table WHERE name = 'Apache'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo $row['name'];
}

Now this is a great way, but imagine you had 20 pieces of data, and don’t want to write $row[''”] every time. Well here the solution

include('connect.php');
$query = "SELECT * FROM table WHERE name = 'Apache'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result) {
extract($row);
echo $name;
}

This simple line of code pulls the $row out of the variables, so now you can call on them using the name of the mysql row, without that nasty $row[''].

What is CRC32 in php?

"A cyclic redundancy check (CRC) is a type of hash function used to produce a checksum - which is a small, fixed number of bits - against a block of data, such as a packet of network traffic or a block of a computer file."

<?php
$var = 'I like cheese dude!!';
$var = crc32($var);
echo $var;
?>

You can compare two encrypted variables too
<?php
$var2 = '1601738962';//I like cheese dude!!
$var = 'I like cheese dude!!';
$var = crc32($var);
if($var == $var2)
{
echo 'Variable 1 and Variable 2 Match';
}
else
{
echo 'Not mach';
}
?>

What is sha1 in PHP?

"The SHA (Secure Hash Algorithm) family is a set of related cryptographic hash functions. The most commonly used function in the family, SHA-1, is employed in a large variety of popular security applications and protocols, including TLS, SSL, PGP, SSH, S/MIME, and IPSec. SHA-1 is considered to be the successor to MD5, an earlier, widely-used hash function. The SHA algorithms were designed by the National Security Agency (NSA) and published as a US government standard."

How to make a basic SHA1 encryption?

This is the code

<?php
$var = 'I like cheese dude!!';
$var = sha1($var);
echo $var;
?>

Like MD5, we can compare two variables.
<?php
$var2 = '73f859db5ab9bc7c3733b0f1792d3e5a316e0f97';//I like cheese dude!!
$var = 'I like cheese dude!!';
$var = sha1($var);
if($var == $var2)
{
echo 'Variable 1 and Variable 2 Match';
}
else
{
echo 'Not mach';
}
?>

How to create security code image in PHP?

<?php
$string = rand ( 00000,99999 ) ;
$string = str_replace ( '2', 'F', $string ) ;
$string = str_replace ( '6', 'e', $string ) ;
$string = str_replace ( '7', 'L', $string ) ;
echo '<img src="securitycodeimage.php?code='.$string.'"/><br /> Code: '.$string;
?>

Securitycodeimage.php
---------------------
<?php
header ( "Content-type: image/gif" ) ;
$string = htmlspecialchars ( strip_tags ( stripslashes ( $_GET [ 'code' ] ) ) , ENT_QUOTES ) ;
$image = @imagecreate ( 50, 15 ) ;
$black = imagecolorallocate ( $image, 0, 0, 0 ) ;
$white = imagecolorallocate ( $image, 255, 255, 255 ) ;
imageline ( $image, 0, 7.5, 50, 7.5, $white ) ;
imagestring ( $image, 2, 10, 1, $string, $white ) ;
imagegif ( $image ) ;
imagedestroy ( $image ) ;
?>

How to Create a dynamic signature using the GD Library in PHP?

<?php
header ("Content-type: image/png");
$background = imagecreatefrompng("gdimg.png");
$white = imagecolorallocate($background, 255, 255, 255);
imagettftext($background,9,0,10,18,$white,"verdana.ttf","My Name is: Pugalenthi Manian");
imagettftext($background,9,0,10,33,$white,"verdana.ttf","Current Location: Hyderabad");
imagepng ($background);
?>

What is the difference between is_numeric() and ctype_digit() in PHP?

In PHP, there are two easy ways to determine whether a particular string is numerical is_numeric() and ctype_digit().
The difference is subtle, but important one. Which function you use depends on the condition for which you’re testing.
is_numeric tests whether the string in question is a number. ctype_digit(), on the other hand, tests whether the string in question contains all numeric characters.
Confused? Perhaps the code below will help.
$n = '1234.5';
var_dump(is_numeric($n)); // returns bool(true)
var_dump(ctype_digit($n)); // returns bool(false)
In the above example $n is a number. But see that decimal point? That’s not a numeric character, therefore ctype_digit($n) is false.

How to stream the file directly using PHP?

<?php
header("Content-type: application/msword");
header("Pragma: no-cache");
header("Expires: 0");
echo "<html><head></head><body><b>Say hello</b> to my http server</body></html>";
?>

Monday, November 06, 2006

How to create microsoft excel(.xls) worksheet(If u need formatted worksheet)?

<?php
$filepnt = fopen("newfilehtml.xls", 'w+');
$content = '<table border="1"><tr><td bgcolor="#CCCCCC"><b>Id</b></td><td bgcolor="#CCCCCC"><b>Username</b></td></tr> <tr><td>1</td><td>Webmaster</td></tr> <tr><td>2</td><td>mysql_fan</td></tr> <tr><td>3</td><td>slackware</td></tr></table>';
fwrite($filepnt, $content);
fclose($filepnt);
echo '<a href="newfilehtml.xls">Download as .xls</a>';
?>

How to create microsoft word(.doc) file using PHP?

<?php
$filepnt = fopen("hellohtml.doc", 'w+');
$content = "<html><head></head><body><b>Say hello</b> to my http server</body></html>";
fwrite($filepnt, $content);
fclose($filepnt);
echo '<a href="hellohtml.doc">Download as .doc</a>';
?>

How to generate Microsoft Word Documents using PHP and COM?

COM is available only in Windows (for example if you are running Apache on Windows XP). By using COM you can launch Microsoft Word or any other available component (or custom component made by you and registered with regsvr32), fill in a document template and save the result as a Word document (as .doc, .rtf or other available formats) and send it to the users of your website.
It's very easy to use it. The code below shows how to create a Word .doc file:
<?php
$word = new COM("word.application");
//To see the version of Microsoft Word, just use $word->Version
echo "I'm using MS Word {$word->Version}<br>";
//It's better to keep Word invisible
$word->Visible = 0;
//Creating new document
$word->Documents->Add();
//Setting 2 inches margin on the both sides
$word->Selection->PageSetup->LeftMargin = '2"';
$word->Selection->PageSetup->RightMargin = '2"';
//Setup the font
$word->Selection->Font->Name = 'Verdana';
$word->Selection->Font->Size = 8;
//Write some text
$word->Selection->TypeText("Hello, universe!");
//Save the document as DOC file
$word->Documents[1]->SaveAs("D:\hello.doc");
// or use: $word->Documents[1]->SaveAs("C:htdocshello2.rtf",6); to save as RTF file
// or use: $word->Documents[1]->SaveAs("C:htdocshello2.htm",8); to save as HTML file
//And of course, quit Word
$word->quit();
//$word->Release();
$word = null;
//Give the user a download link
echo '<a href="hello2.doc">Download file as .doc</a>';
?>

How to create microsoft excel(.xls) file using PHP?

<?php
$filepnt = fopen("newfile.xls", 'w+');
$content = "Id\tUsername\tE-mail\tLevel\n"; //"\t" means a TAB and "\n" is a New line
$content .= "1\tWebmaster\twebmaster@example.com\t1\n"; //every new line is a new row in the table
$content .= "2\tmysql_fan\tmysql@php.be\t3\n";
$content .= "3\tfedora\tfedora@redhat.com\t3\n";
fwrite($filepnt, $content);
fclose($filepnt);
echo '<a href="newfile.xls">Download as .xls</a>';
?>

How to create a PowerPoint .ppt file using COM and PHP?

If you need to create a presentation using some dynamic data, here is how to create a PowerPoint .ppt file. You can create as many slides as you want and then add elements inside by using "Slides[number_of_slide]":
$powerpnt = new COM("powerpoint.application");
//Creating a new presentation
$pres=$powerpnt->gt;Presentations->gt;Add();
//Adds the first slide. "12" means blank slide
$pres->gt;Slides->gt;Add(1,12);
//Adds another slide. "10" means a slide with a clipart and text
$pres->gt;Slides->gt;Add(2,10);
//Adds a textbox (1=horizontal, 20=left margin, 50=top margin, 300=width, 40=height)
$pres->gt;Slides[1]->gt;Shapes->gt;AddTextbox(1,20,50,300,40);
//Adds a 16-point star (94=16 point star, 100=left margin, 200=top margin, 300=width, 300=height)
$pres->gt;Slides[1]->gt;Shapes->gt;AddShape(94,100,200,300,300);
//Save the document as PPT file
$powerpnt->gt;Presentations[1]->gt;SaveAs("D:\byeworld.ppt");
//And of course, quit Power Point
$powerpnt->gt;quit();
//Give the user a download link
echo 'gt;Download file as .pptgt;';
?>gt;
Note: To understand the meaning of each function, just open the Object Browser. It's on the place in Microsoft PowerPoint (Alt+F11) to open Visual Basic Editor, F2 to open Object Browser).

How to create a excel worksheet with COM and PHP?

<?php
$excel = new COM("excel.application");
//Keep Excel invisible
$excel->Visible = 0;
//Create a new workbook
$wkb = $excel->Workbooks->Add();
$sheet = $wkb->Worksheets(1);
//This code adds the text 'Test' on row 2, column 4
$sheet->activate;
$cell = $sheet->Cells(2,4);
$cell->Activate;
$cell->value = 'Test';
//Save the file just like the Word file above
$wkb->SaveAs("excel123.xls");
//Quit MS Excel
$wkb->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
unset($sheet);
unset($excel);
?>