Global Variables

Rabu, 30 Maret 2011

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/
01.include('EmailAddressValidator.php');
02. 
03.$validator = new EmailAddressValidator;
04.if ($validator->check_email_address('test@example.org')) {
05.    // Email address is technically valid
06.}
07.else {
08.    // Email not valid
09.}

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
01.function generatePassword($length=9, $strength=0) {
02.    $vowels = 'aeuy';
03.    $consonants = 'bdghjmnpqrstvz';
04.    if ($strength & 1) {
05.        $consonants .= 'BDGHJLMNPQRSTVWXZ';
06.    }
07.    if ($strength & 2) {
08.        $vowels .= "AEUY";
09.    }
10.    if ($strength & 4) {
11.        $consonants .= '23456789';
12.    }
13.    if ($strength & 8) {
14.        $consonants .= '@#$%';
15.    }
16. 
17.    $password = '';
18.    $alt = time() % 2;
19.    for ($i = 0; $i < $length; $i++) {
20.        if ($alt == 1) {
21.            $password .= $consonants[(rand() % strlen($consonants))];
22.            $alt = 0;
23.        } else {
24.            $password .= $vowels[(rand() % strlen($vowels))];
25.            $alt = 1;
26.        }
27.    }
28.    return $password;
29.}

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
01.function getRealIpAddr(){
02.    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
03.        //check ip from share internet
04.        $ip = $_SERVER['HTTP_CLIENT_IP'];
05.    }
06.    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
07.        //to check ip is pass from proxy
08.        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
09.    }
10.    else{
11.        $ip = $_SERVER['REMOTE_ADDR'];
12.    }
13.    return $ip;
14.}

XSL transformation

PHP5 version
Source : http://www.tonymarston.net/php-mysql/xsl.html
01.$xp = new XsltProcessor();
02. 
03.// create a DOM document and load the XSL stylesheet
04.$xsl = new DomDocument;
05.$xsl->load('something.xsl');
06. 
07.// import the XSL styelsheet into the XSLT process
08.$xp->importStylesheet($xsl);
09. 
10.// create a DOM document and load the XML datat
11.$xml_doc = new DomDocument;
12.$xml_doc->load('something.xml');
13. 
14.// transform the XML into HTML using the XSL file
15.if ($html = $xp->transformToXML($xml_doc)) {
16.    echo $html;
17.}
18.else {
19.    trigger_error('XSL transformation failed.', E_USER_ERROR);
20.} // if
PHP4 version
01.function xml2html($xmldata, $xsl){
02.   /* $xmldata -> your XML */
03.   /* $xsl -> XSLT file */
04. 
05.   $arguments = array('/_xml' => $xmldata);
06.   $xsltproc = xslt_create();
07.   xslt_set_encoding($xsltproc, 'ISO-8859-1');
08.   $html = xslt_process($xsltproc, $xmldata, $xsl, NULL, $arguments);
09. 
10.   if (empty($html)) {
11.       die('XSLT processing error: '. xslt_error($xsltproc));
12.   }
13.   xslt_free($xsltproc);
14.   return $html;
15.}
16. 
17.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.
01.header("Content-type: application/octet-stream");
02. 
03.// displays progress bar when downloading (credits to Felix ;-))
04.header("Content-Length: " . filesize('myImage.jpg'));
05. 
06.// file name of download file
07.header('Content-Disposition: attachment; filename="myImage.jpg"');
08. 
09.// reads the file on the server
10.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/
1.include('Reform.php');
2.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/
01.include("class.phpmailer.php");
02.$mail = new PHPMailer();
03.$mail->From = 'noreply@htmlblog.net';
04.$mail->FromName = 'HTML Blog';
05.$mail->Host = 'smtp.site.com';
06.$mail->Mailer = 'smtp';
07.$mail->Subject = 'My Subject';
08.$mail->IsHTML(true);
09.$body = 'Hello<br/>How are you ?';
10.$textBody = 'Hello, how are you ?';
11.$mail->Body = $body;
12.$mail->AltBody = $textBody;
13.$mail->AddAddress('asvin [@] gmail.com');
14.if(!$mail->Send())
15.    echo 'There has been a mail error !';
Using Swift Mailer
Swift Mailer is an alternative to PHPMailer and is a fully OOP library for sending e-mails from PHP websites and applications.
Source : http://swiftmailer.org/
01.// include classes
02.require_once "lib/Swift.php";
03.require_once "lib/Swift/Connection/SMTP.php";
04. 
05.$swift =& new Swift(new Swift_Connection_SMTP("smtp.site.com", 25));
06.$message =& new Swift_Message("My Subject", "Hello<br/>How are you ?", "text/html");
07.if ($swift->send($message, "asvin [@] gmail.com", "noreply@htmlblog.net")){
08.    echo "Message sent";
09.}
10.else{
11.    echo 'There has been a mail error !';
12.}
13. 
14.//It's polite to do this when you're finished
15.$swift->disconnect();

Uploading of files

Using class.upload.php from Colin Verot
Source : http://www.verot.net/php_class_upload.htm
1.$uploadedImage = new Upload($_FILES['uploadImage']);
2. 
3.if ($uploadedImage->uploaded) {
4.    $uploadedImage->Process('myuploads');
5.    if ($uploadedImage->processed) {
6.        echo 'file has been uploaded';
7.    }
8.}

List files in directory

List all files in a directory and return an array.
Source : http://www.laughing-buddha.net/jon/php/dirlist/
01.function dirList ($directory) {
02.    // create an array to hold directory list
03.    $results = array();
04. 
05.    // create a handler for the directory
06.    $handler = opendir($directory);
07. 
08.    // keep going until all files in directory have been read
09.    while ($file = readdir($handler)) {
10. 
11.        // if $file isn't this directory or its parent,
12.        // add it to the results array
13.        if ($file != '.' && $file != '..')
14.            $results[] = $file;
15.    }
16. 
17.    // tidy up: close the handler
18.    closedir($handler);
19. 
20.    // done!
21.    return $results;
22.}

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
01.// include MDB2 class
02.include('MDB2.php');
03. 
04.// connection info
05.$db =& MDB2::factory('mysql://username:password@host/database');
06.// set fetch mode
07.$db->setFetchMode(MDB2_FETCHMODE_ASSOC);
08. 
09.// querying data
10.$query = 'SELECT id,label FROM myTable';
11.$result = $db->queryAll($query);
12. 
13.// inserting data
14.// prepare statement
15.$statement = $db->prepare('INSERT INTO mytable(id,label) VALUES(?,?)');
16.// our data
17.$sqlData = array($id, $label);
18.// execute
19.$statement->execute($sqlData);
20.$statement->free();
21. 
22.// disconnect from db
23.$db->disconnect();

0 komentar:

Posting Komentar