"Swift Mailer integrates into any web app written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features."
Download Documentation
[sourcecode language="php"]
<!--?php require_once 'swiftmailer/lib/swift_required.php'; // Create the Transport //SMTP /*$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25) --->setUsername('your username')
->setPassword('your password')
;
*/
// Sendmail
//$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Mail
$transport = Swift_MailTransport::newInstance();
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john@doe.com' => 'John Doe'))
->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
?>
[/sourcecode]
Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts
Saturday, August 31, 2013
Tuesday, September 4, 2012
Browser Detection Class - PHP
Demo
[sourcecode language="php"]
class Browser
{
private $u_agent;
private $bname;
private $platform;
private $version;
public function __construct()
{
$this->u_agent = $_SERVER['HTTP_USER_AGENT'];
$this->bname = 'Unknown';
$this->platform = 'Unknown';
$this->version= "";
}
public function getBrowser()
{
//First get the platform?
if (preg_match('/linux/i', $this->u_agent)) {
$this->platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $this->u_agent)) {
$this->platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $this->u_agent)) {
$this->platform = 'windows';
}
// Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$this->u_agent) && !preg_match('/Opera/i',$this->u_agent))
{
$this->bname = 'Internet Explorer';
$this->ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$this->u_agent))
{
$this->bname = 'Mozilla Firefox';
$this->ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$this->u_agent))
{
$this->bname = 'Google Chrome';
$this->ub = "Chrome";
}
elseif(preg_match('/Safari/i',$this->u_agent))
{
$this->bname = 'Apple Safari';
$this->ub = "Safari";
}
elseif(preg_match('/Opera/i',$this->u_agent))
{
$this->bname = 'Opera';
$this->ub = "Opera";
}
elseif(preg_match('/Netscape/i',$this->u_agent))
{
$this->bname = 'Netscape';
$this->ub = "Netscape";
}
// finally get the correct version number
$known = array('Version', $this->ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $this->u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($this->u_agent,"Version") < strripos($this->u_agent,$this->ub)){
$this->version= $matches['version'][0];
}
else {
$this->version= $matches['version'][1];
}
}
else {
$this->version= $matches['version'][0];
}
// check if we have a number
if ($version==null || $version=="") {
$version="?";
}
return array(
'userAgent' => $this->u_agent,
'name' => $this->bname,
'version' => $this->version,
'platform' => $this->platform,
'pattern' => $this->pattern
);
}
}
[/sourcecode]
Usage
[sourcecode language="php"]
$obj= new Browser();
$ua = $obj->getBrowser();
echo $ua['name']."<br>";
echo $ua['version']."<br>";
echo $ua['platform']."<br>";
echo $ua['userAgent']."<br>";
[/sourcecode]
[sourcecode language="php"]
class Browser
{
private $u_agent;
private $bname;
private $platform;
private $version;
public function __construct()
{
$this->u_agent = $_SERVER['HTTP_USER_AGENT'];
$this->bname = 'Unknown';
$this->platform = 'Unknown';
$this->version= "";
}
public function getBrowser()
{
//First get the platform?
if (preg_match('/linux/i', $this->u_agent)) {
$this->platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $this->u_agent)) {
$this->platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $this->u_agent)) {
$this->platform = 'windows';
}
// Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$this->u_agent) && !preg_match('/Opera/i',$this->u_agent))
{
$this->bname = 'Internet Explorer';
$this->ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$this->u_agent))
{
$this->bname = 'Mozilla Firefox';
$this->ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$this->u_agent))
{
$this->bname = 'Google Chrome';
$this->ub = "Chrome";
}
elseif(preg_match('/Safari/i',$this->u_agent))
{
$this->bname = 'Apple Safari';
$this->ub = "Safari";
}
elseif(preg_match('/Opera/i',$this->u_agent))
{
$this->bname = 'Opera';
$this->ub = "Opera";
}
elseif(preg_match('/Netscape/i',$this->u_agent))
{
$this->bname = 'Netscape';
$this->ub = "Netscape";
}
// finally get the correct version number
$known = array('Version', $this->ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $this->u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($this->u_agent,"Version") < strripos($this->u_agent,$this->ub)){
$this->version= $matches['version'][0];
}
else {
$this->version= $matches['version'][1];
}
}
else {
$this->version= $matches['version'][0];
}
// check if we have a number
if ($version==null || $version=="") {
$version="?";
}
return array(
'userAgent' => $this->u_agent,
'name' => $this->bname,
'version' => $this->version,
'platform' => $this->platform,
'pattern' => $this->pattern
);
}
}
[/sourcecode]
Usage
[sourcecode language="php"]
$obj= new Browser();
$ua = $obj->getBrowser();
echo $ua['name']."<br>";
echo $ua['version']."<br>";
echo $ua['platform']."<br>";
echo $ua['userAgent']."<br>";
[/sourcecode]
Wednesday, June 6, 2012
PHP File Upload Class
uploader.php
[sourcecode language="php"]
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $maxSize;
private $uploadName;
private $seqnence;
private $renamedState = 0;
public function setDir($path)
{
$this->destinationPath = $path;
}
public function setMaxSize($sizeMB)
{
$this->maxSize = $sizeMB * (1024*1024);
}
public function setExtensions($options)
{
$this->extensions = $options;
}
public function getExtension($string)
{
$ext = "";
try
{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}
catch(Exception $c)
{
$ext = "";
}
return $ext;
}
public function setMessage($message)
{
$this->errorMessage = $message;
}
public function getMessage()
{
return $this->errorMessage;
}
public function getUploadName()
{
return $this->uploadName;
}
public function setSequence($seq)
{
$this->imageSeq = $seq;
}
public function getRandom()
{
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
public function getRenamedState()
{
return $this->renamedState;
}
public function renameFile($state,$newName)
{
$this->renamedState = $state;
$this->uploadName = $newName;
}
public function deleteUploaded()
{
unlink($this->destinationPath.$this->uploadName);
}
public function uploadFile($fileBrowse)
{
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath))
{
$this->setMessage("Destination folder is not a directory ");
}
else if(!is_writable($this->destinationPath))
{
$this->setMessage("Destination is not writable !");
}
else if(empty($name))
{
$this->setMessage("File not selected ");
}
else if($size>$this->maxSize)
{
$this->setMessage("Too large file !");
}
else if(in_array($ext,$this->extensions))
{
switch ($this->getRenamedState())
{
case 0: //Keep original file name
$this->uploadName= $name;
break;
case 1: //Rename file with randomly-generated name
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
break;
case 2: //Rename file with given name when calling renameFile() function
$this->uploadName.= ".".$ext;
break;
default:
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName))
{
$result = true;
}
else
{
$this->setMessage("Upload failed");
}
}
else
{
$this->setMessage("Invalid file format!");
}
return $result;
}
}
[/sourcecode]
How to use this uploader class
[sourcecode language="php"]
<?php
if(isset($_POST['btnSub']))
{
require_once('uploader.php');
$uploader = new Uploader();
$uploader->setDir('public/img');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list
$uploader->setMaxSize(.5); //set max file size to be allowed in MB
//Select one of the following alternatives
//$uploader->renameFile(0,""); //Keep original file name
//$uploader->renameFile(1,""); //Rename file with randomly-generated name
//$uploader->renameFile(2,"sample"); // Rename file with 'sample'
if($uploader->uploadFile('txtFile'))//specify file field
{
$image = $uploader->getUploadName(); //get uploaded file name
}
else
{
echo $uploader->getMessage(); //get upload error message
}
}
?>
<!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>File Upload Example</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input name="txtFile" type="file" />
<input name="btnSub" type="submit" />
</form>
</body>
</html>
[/sourcecode]
[sourcecode language="php"]
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $maxSize;
private $uploadName;
private $seqnence;
private $renamedState = 0;
public function setDir($path)
{
$this->destinationPath = $path;
}
public function setMaxSize($sizeMB)
{
$this->maxSize = $sizeMB * (1024*1024);
}
public function setExtensions($options)
{
$this->extensions = $options;
}
public function getExtension($string)
{
$ext = "";
try
{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}
catch(Exception $c)
{
$ext = "";
}
return $ext;
}
public function setMessage($message)
{
$this->errorMessage = $message;
}
public function getMessage()
{
return $this->errorMessage;
}
public function getUploadName()
{
return $this->uploadName;
}
public function setSequence($seq)
{
$this->imageSeq = $seq;
}
public function getRandom()
{
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
public function getRenamedState()
{
return $this->renamedState;
}
public function renameFile($state,$newName)
{
$this->renamedState = $state;
$this->uploadName = $newName;
}
public function deleteUploaded()
{
unlink($this->destinationPath.$this->uploadName);
}
public function uploadFile($fileBrowse)
{
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath))
{
$this->setMessage("Destination folder is not a directory ");
}
else if(!is_writable($this->destinationPath))
{
$this->setMessage("Destination is not writable !");
}
else if(empty($name))
{
$this->setMessage("File not selected ");
}
else if($size>$this->maxSize)
{
$this->setMessage("Too large file !");
}
else if(in_array($ext,$this->extensions))
{
switch ($this->getRenamedState())
{
case 0: //Keep original file name
$this->uploadName= $name;
break;
case 1: //Rename file with randomly-generated name
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
break;
case 2: //Rename file with given name when calling renameFile() function
$this->uploadName.= ".".$ext;
break;
default:
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName))
{
$result = true;
}
else
{
$this->setMessage("Upload failed");
}
}
else
{
$this->setMessage("Invalid file format!");
}
return $result;
}
}
[/sourcecode]
How to use this uploader class
[sourcecode language="php"]
<?php
if(isset($_POST['btnSub']))
{
require_once('uploader.php');
$uploader = new Uploader();
$uploader->setDir('public/img');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list
$uploader->setMaxSize(.5); //set max file size to be allowed in MB
//Select one of the following alternatives
//$uploader->renameFile(0,""); //Keep original file name
//$uploader->renameFile(1,""); //Rename file with randomly-generated name
//$uploader->renameFile(2,"sample"); // Rename file with 'sample'
if($uploader->uploadFile('txtFile'))//specify file field
{
$image = $uploader->getUploadName(); //get uploaded file name
}
else
{
echo $uploader->getMessage(); //get upload error message
}
}
?>
<!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>File Upload Example</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input name="txtFile" type="file" />
<input name="btnSub" type="submit" />
</form>
</body>
</html>
[/sourcecode]
Sunday, March 18, 2012
PHP User Class
[sourcecode language="php"]
<?php
class User
{
private $user_id;
private $username;
private $password;
private $email;
protected static $table_name="lbs_user";
public function __construct($username="",$password="",$email="")
{
$this->username = $username;
$this->password = $password;
$this->email = $email;
}
/* Add a new user.
* Returns true on success, false on error */
public function getUserId()
{
return $this->user_id;
}
public function create()
{
global $gdbObj;
$username = $gdbObj->escape_value($this->username);
$password = $gdbObj->escape_value($this->password);
$email = $gdbObj->escape_value($this->email);
$sql = "INSERT INTO ".self::$table_name." (username,password,email) values('$username','$password','$email')";
if($gdbObj->query($sql))
{
$this->user_id = $gdbObj->insert_id();
return true;
}
else
{
return false;
}
}
/* Update user profile.
* Returns true on success, false on error */
public function update()
{
}
/* Remove an user.
* Returns true on success, false on error */
public function delete()
{
}
}
$guserObj = new User();
?>
[/sourcecode]
<?php
class User
{
private $user_id;
private $username;
private $password;
private $email;
protected static $table_name="lbs_user";
public function __construct($username="",$password="",$email="")
{
$this->username = $username;
$this->password = $password;
$this->email = $email;
}
/* Add a new user.
* Returns true on success, false on error */
public function getUserId()
{
return $this->user_id;
}
public function create()
{
global $gdbObj;
$username = $gdbObj->escape_value($this->username);
$password = $gdbObj->escape_value($this->password);
$email = $gdbObj->escape_value($this->email);
$sql = "INSERT INTO ".self::$table_name." (username,password,email) values('$username','$password','$email')";
if($gdbObj->query($sql))
{
$this->user_id = $gdbObj->insert_id();
return true;
}
else
{
return false;
}
}
/* Update user profile.
* Returns true on success, false on error */
public function update()
{
}
/* Remove an user.
* Returns true on success, false on error */
public function delete()
{
}
}
$guserObj = new User();
?>
[/sourcecode]
PHP/MySQL Sample Database Class
[sourcecode language="php"]
<?php
class MySqlDatabase
{
private $_connection;
public $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
public function __construct()
{
$this->open_connection();
/* Returns the current configuration setting of magic_quotes_gpc.
Returns 0 if magic_quotes_gpc is off, 1 otherwise. */
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
}
public function open_connection()
{
$this->_connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if(!$this->_connection)
{
die('Database connection failed'.mysql_error());
}
else
{
$db_select = mysql_select_db(DB_NAME,$this->_connection);
if(!$db_select)
{
die('Database selection failed'.mysql_error());
}
}
}
public function close_connection()
{
if(isset($this->_connection))
{
mysql_close($this->_connection);
unset($this->_connection);
}
}
/* For SELECT returns resultset on success, false on error.
* For INSERT, UPDATE, DELETE etc returns true on success, false on error */
public function query($sql)
{
$this->last_query = $sql;
$result = mysql_query($sql,$this->_connection);
$this->confirm_query($result);
return $result;
}
/* Make sure query executed successfully.
* Only for debugging purposes. */
private function confirm_query($result)
{
if(!$result)
{
$output = "Databse query failed".mysql_error()."<br>";
$output .= "Last query ".$this->last_query;
die($output);
}
}
/* Escape special characters in the string before sending to the database
* Consider PHP Version*/
public function escape_value($value)
{
if($this->real_escape_string_exists)// PHP version 4.3.0 or higher
{
if($this->magic_quotes_active)
{
/* Automatically add back slashes when magic quotes are active in php.ini
* First remove them. */
$value = stripslashes($value);
}
//Escapes special characters in a string
$value = mysql_real_escape_string($value);
}
else //before PHP version 4.3.0
{
if(!$this->magic_quotes_active)
{
// Add slashes manually
$value = addslashes($value);
}
}
return $value;
}
/* Returns an array of strings that corresponds to the fetched row.
* Returns FALSE if there are no more rows.*/
public function fetch_array($result_set)
{
return mysql_fetch_array($result_set);
}
/* Retrives the number of rows from the result set.
* Returns FALSE on failure. */
public function num_rows($result_set)
{
return mysql_num_rows($result_set);
}
/* Get the ID generated in the last query
* 0 if the previous query does not generate an AUTO_INCREMENT value.
* FALSE if no MySQL connection was established. */
public function insert_id()
{
return mysql_insert_id($this->_connection);
}
/* Get number of affected rows in previous MySQL operation.
* Return -1 if the last query failed. */
public function affected_rows()
{
return mysql_affected_rows($this->_connection);
}
}
//Creates an object from MySQLDatabase class
$gdbObj = new MySqlDatabase();
?>
[/sourcecode]
<?php
class MySqlDatabase
{
private $_connection;
public $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
public function __construct()
{
$this->open_connection();
/* Returns the current configuration setting of magic_quotes_gpc.
Returns 0 if magic_quotes_gpc is off, 1 otherwise. */
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
}
public function open_connection()
{
$this->_connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if(!$this->_connection)
{
die('Database connection failed'.mysql_error());
}
else
{
$db_select = mysql_select_db(DB_NAME,$this->_connection);
if(!$db_select)
{
die('Database selection failed'.mysql_error());
}
}
}
public function close_connection()
{
if(isset($this->_connection))
{
mysql_close($this->_connection);
unset($this->_connection);
}
}
/* For SELECT returns resultset on success, false on error.
* For INSERT, UPDATE, DELETE etc returns true on success, false on error */
public function query($sql)
{
$this->last_query = $sql;
$result = mysql_query($sql,$this->_connection);
$this->confirm_query($result);
return $result;
}
/* Make sure query executed successfully.
* Only for debugging purposes. */
private function confirm_query($result)
{
if(!$result)
{
$output = "Databse query failed".mysql_error()."<br>";
$output .= "Last query ".$this->last_query;
die($output);
}
}
/* Escape special characters in the string before sending to the database
* Consider PHP Version*/
public function escape_value($value)
{
if($this->real_escape_string_exists)// PHP version 4.3.0 or higher
{
if($this->magic_quotes_active)
{
/* Automatically add back slashes when magic quotes are active in php.ini
* First remove them. */
$value = stripslashes($value);
}
//Escapes special characters in a string
$value = mysql_real_escape_string($value);
}
else //before PHP version 4.3.0
{
if(!$this->magic_quotes_active)
{
// Add slashes manually
$value = addslashes($value);
}
}
return $value;
}
/* Returns an array of strings that corresponds to the fetched row.
* Returns FALSE if there are no more rows.*/
public function fetch_array($result_set)
{
return mysql_fetch_array($result_set);
}
/* Retrives the number of rows from the result set.
* Returns FALSE on failure. */
public function num_rows($result_set)
{
return mysql_num_rows($result_set);
}
/* Get the ID generated in the last query
* 0 if the previous query does not generate an AUTO_INCREMENT value.
* FALSE if no MySQL connection was established. */
public function insert_id()
{
return mysql_insert_id($this->_connection);
}
/* Get number of affected rows in previous MySQL operation.
* Return -1 if the last query failed. */
public function affected_rows()
{
return mysql_affected_rows($this->_connection);
}
}
//Creates an object from MySQLDatabase class
$gdbObj = new MySqlDatabase();
?>
[/sourcecode]
Subscribe to:
Posts (Atom)
How to enable CORS in Laravel 5
https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...
-
I have already written several posts regarding Android database applications. This post might be similar to those tuts. However this is more...
-
< Requirements Java Development Kit (JDK) NetBeans IDE Apache Axis 2 Apache Tomcat Server Main Topics Setup Development Environ...