September 6, 2010

10 code snippets for PHP developers

10 code snippets for PHP developers

I've compiled a small list of some useful code snippets which might help you when writing your PHP scripts...

Email address check
Checks for a valid email address using the php-email-address-validation class.
Source and docs: http://code.google.com/p/php-email-address-validation/


include('EmailAddressValidator.php');

$validator = new EmailAddressValidator;
if ($validator->check_email_address('test@example.org')) {
// Email address is technically valid
}
else {
// Email not valid
}


Random password generator
PHP password generator is a complete, working random password generation function for PHP. It allows the developer to customize the password: set its length and strength. Just include this function anywhere in your code and then use it.
Source : http://www.webtoolkit.info/php-random-password-generator.html




function generatePassword($length=9, $strength=0) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength & 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength & 2) {
$vowels .= "AEUY";
}
if ($strength & 4) {
$consonants .= '23456789';
}
if ($strength & 8) {
$consonants .= '@#$%';
}

$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) { if ($alt == 1) { $password .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $password .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } } return $password; } Get IP address
Returns the real IP address of a visitor, even when connecting via a proxy.
Source : http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html


function getRealIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
//check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
//to check ip is pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}


XSL transformation
PHP5 version
Source : http://www.tonymarston.net/php-mysql/xsl.html


$xp = new XsltProcessor();

// create a DOM document and load the XSL stylesheet
$xsl = new DomDocument;
$xsl->load('something.xsl');

// import the XSL styelsheet into the XSLT process
$xp->importStylesheet($xsl);

// create a DOM document and load the XML datat
$xml_doc = new DomDocument;
$xml_doc->load('something.xml');

// transform the XML into HTML using the XSL file
if ($html = $xp->transformToXML($xml_doc)) {
echo $html;
}
else {
trigger_error('XSL transformation failed.', E_USER_ERROR);
} // if


PHP4 version


function xml2html($xmldata, $xsl){
/* $xmldata -> your XML */
/* $xsl -> XSLT file */

$arguments = array('/_xml' => $xmldata);
$xsltproc = xslt_create();
xslt_set_encoding($xsltproc, 'ISO-8859-1');
$html = xslt_process($xsltproc, $xmldata, $xsl, NULL, $arguments);

if (empty($html)) {
die('XSLT processing error: '. xslt_error($xsltproc));
}
xslt_free($xsltproc);
return $html;
}

echo xml2html('myxmml.xml', 'myxsl.xsl');


Force downloading of a file
Forces a user to download a file, for e.g you have an image but you want the user to download it instead of displaying it in his browser.


header("Content-type: application/octet-stream");

// displays progress bar when downloading (credits to Felix ;-))
header("Content-Length: " . filesize('myImage.jpg'));

// file name of download file
header('Content-Disposition: attachment; filename="myImage.jpg"');

// reads the file on the server
readfile('myImage.jpg');


String encoding to prevent harmful code
Web applications face any number of threats; one of them is cross-site scripting and related injection attacks. The Reform library attempts to provide a solid set of functions for encoding output for the most common context targets in web applications (e.g. HTML, XML, JavaScript, etc)
Source : http://phed.org/reform-encoding-library/


include('Reform.php');
Reform::HtmlEncode('a potentially harmful string');


Sending mail
Using PHPMailer
PHPMailer a powerful email transport class with a big features and small footprint that is simple to use and integrate into your own software.
Source : http://phpmailer.codeworxtech.com/


include("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = 'noreply@htmlblog.net';
$mail->FromName = 'HTML Blog';
$mail->Host = 'smtp.site.com';
$mail->Mailer = 'smtp';
$mail->Subject = 'My Subject';
$mail->IsHTML(true);
$body = 'Hello
How are you ?';
$textBody = 'Hello, how are you ?';
$mail->Body = $body;
$mail->AltBody = $textBody;
$mail->AddAddress('asvin [@] gmail.com');
if(!$mail->Send())
echo 'There has been a mail error !';

Uploading of files
Using class.upload.php from Colin Verot
Source : http://www.verot.net/php_class_upload.htm


$uploadedImage = new Upload($_FILES['uploadImage']);

if ($uploadedImage->uploaded) {
$uploadedImage->Process('myuploads');
if ($uploadedImage->processed) {
echo 'file has been uploaded';
}
}


List files in directory
List all files in a directory and return an array.
Source : http://www.laughing-buddha.net/jon/php/dirlist/


function dirList ($directory) {
// create an array to hold directory list
$results = array();

// create a handler for the directory
$handler = opendir($directory);

// keep going until all files in directory have been read
while ($file = readdir($handler)) {

// if $file isn't this directory or its parent,
// add it to the results array
if ($file != '.' && $file != '..')
$results[] = $file;
}

// tidy up: close the handler
closedir($handler);

// done!
return $results;
}


Querying RDBMS with MDB2 (for e.g MySQL)
PEAR MDB2 provides a common API for all supported RDBMS.

Source : http://pear.php.net/package/MDB2


// include MDB2 class
include('MDB2.php');

// connection info
$db =& MDB2::factory('mysql://username:password@host/database');
// set fetch mode
$db->setFetchMode(MDB2_FETCHMODE_ASSOC);

// querying data
$query = 'SELECT id,label FROM myTable';
$result = $db->queryAll($query);

// inserting data
// prepare statement
$statement = $db->prepare('INSERT INTO mytable(id,label) VALUES(?,?)');
// our data
$sqlData = array($id, $label);
// execute
$statement->execute($sqlData);
$statement->free();

// disconnect from db
$db->disconnect();



Enjoy...

Shyam-D Man U Love-

Move the mouse with your keyboard in KDE

File this under "I should have known about this but didn't." Let's say you don't have a mouse, or your mouse is having problems, yet you still need to somehow move your pointer from A to B. It's easy in KDE: press Alt-F12. You can now move the pointer with your arrow keys. When you're finished, press Alt-F12 again, & you're back to the mouse.

Enjoy Guyz..
Shyam -D Man U Love-

How to include a Flashfile into a HTML Website?

Flashbanners (*.swf) can't be included with the IMG tag. For displaying Flashfiles a special HTML-code is needed.
For unskilled users it might look a bit strange but it's very easy. Just copy and paste the HTML-code in the box below to your HTML file.

The only thing you have to do is:

* Change the banner address (red letters) into the address where your banner is stored on the internet.
* If you want to display the banner in another size make your changes to the values in green letters.


Shyam-D Man U Love-

August 31, 2010

WordPress (Version 3.0.1)

The latest stable release of Word Press (Version 3.0.1) is available in two formats from the link ?Download it..ShYaM?

Enjoy the Power of Theme WordPress (Version 3.0.1)

August 19, 2010

Open Source Graphic Programs-45 Best

http://www.snap2objects.com/
Following the great success of the 45 Best Freeware Design Programs and attending requests of more open source apps, here is a new extensive list of Open Source Graphic Programs that you may take into consideration for production use. There is a lot of technicalities when we talk about The Open Source movement, and we are not covering them here on detail, so please forgive with me if I am not being formal enough with all the terminology.


ShYaM....

PHP Functions..ShYaM..

The $_POST Function
The built-in $_POST function is used to collect values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

"form action="welcome.php" method="post"
Name: input type="text" name="fname"
Age: input type="text" name="age"
input type="submit"
form"

The $_GET Function
The built-in $_GET function is used to collect values from a form sent with method="get".

"form action="welcome.php" method="get"
Name: input type="text" name="fname"
Age: input type="text" name="age"
input type="submit"
form "

PHP Form Handling
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

"html
body

form action="welcome.php" method="post"
Name: input type="text" name="fname"
Age: input type="text" name="age"
input type="submit"
form

body
html"

By ShYaM...

August 12, 2010

How To Change Your IP Address..Shyam

If your connection is direct to your computer and your computer gets the public IP and not a router, you can try this:
For Windows 2000, XP, and 2003
1. Click Start
2. Click Run
3. Type in cmd and hit ok (this opens a Command Prompt)
4. Type ipconfig /release and hit enter
5. Click Start, Control Panel, and open Network Connections
6. Find and Right click on the active Local Area Connection and choose Properties
7. Double-click on the Internet Protocol (TCP/IP)
8. Click on Use the following IP address
9. Enter a false IP like 123.123.123.123
10. Press Tab and the Subnet Mask section will populate with default numbers
11. Hit OK twice
12. Right click the active Local Area Connection again and choose Properties
13. Double-click on the Internet Protocol (TCP/IP)
14. Choose Obtain an IP address automatically
15. Hit OK twice
16. Go to What Is My IP to see if you have a new IP address



For Vista (Windows 7 is very similar)
1. Click Start
2. Click All Programs expand the Accessories menu
3. In the Accessories menu, Right Click Command Prompt and choose Run as administrator
4. Type ipconfig /release and hit enter
5. Click Start, Control Panel, and open Network and Sharing Center. Depending on your view, you may have to click Network and Internet before you see the Network and Sharing Center icon
6. From the Tasks menu on the left, choose Manage Network Connections
7. Find and Right click on the active Local Area Connection and choose Properties (If you’re hit with a UAC prompt, choose Continue)
8. Double-click on Internet Protocol Version 4 (TCP/IPv4)
9. Click on Use the following IP address
10. Enter a false IP like 123.123.123.123
11. Press Tab and the Subnet Mask section will populate with default numbers
12. Hit OK twice
13. Right click the active Local Area Connection again and choose Properties
14. Double-click on Internet Protocol Version 4 (TCP/IPv4)
15. Choose Obtain an IP address automatically
16. Hit OK twice
17. Go to What Is My IP to see if you have a new IP address

Read more: http://www.whatismyip.com