26 Eylül 2007 Çarşamba

PHP SMTP Authentication: send an email through an authenticated SMTP server

Author: Matthew R. Miller, http://www.bytemycode.com/snippets/snippet/223/


<?php
function mymail($to,$subject,$message,$headers)
{
// set as global variable
global $GLOBAL;
// get From address
if ( preg_match("/From:.*?[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+.*/", $headers, $froms) ) {
preg_match("/[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+/", $froms[0], $fromarr);
$from = $fromarr[0];
}
// Open an SMTP connection
$cp = fsockopen ($GLOBAL["SMTP_SERVER"], $GLOBAL["SMTP_PORT"], &$errno, &$errstr, 1);
if (!$cp)
return "Failed to even make a connection";
$res=fgets($cp,256);
if(substr($res,0,3) != "220") return "Failed to connect";
// Say hello...
fputs($cp, "HELO ".$GLOBAL["SMTP_SERVER"]."\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "Failed to Introduce";
// perform authentication
fputs($cp, "auth login\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "334") return "Failed to Initiate Authentication";
fputs($cp, base64_encode($GLOBAL["SMTP_USERNAME"])."\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "334") return "Failed to Provide Username for Authentication";
fputs($cp, base64_encode($GLOBAL["SMTP_PASSWORD"])."\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "235") return "Failed to Authenticate";
// Mail from...
fputs($cp, "MAIL FROM: <$from>\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "MAIL FROM failed";
// Rcpt to...
fputs($cp, "RCPT TO: <$to>\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "RCPT TO failed";
// Data...
fputs($cp, "DATA\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "354") return "DATA failed";
// Send To:, From:, Subject:, other headers, blank line, message, and finish
// with a period on its own line (for end of message)
fputs($cp, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "250") return "Message Body Failed";
// ...And time to quit...
fputs($cp,"QUIT\r\n");
$res=fgets($cp,256);
if(substr($res,0,3) != "221") return "QUIT failed";
return true;
}
?>


Extracts all email adresses from a given string, and returns them as array

Author: Jonas John, http://codedump.jonasjohn.de/

<?php
/*
** Function: extract_emails (PHP)
** Desc: This function extracts all E-Mail adresses from a given string, and returns them as array.
** Author: Jonas John
*/

function extract_emails($str)
{
// This regular expression extracts all emails from
// a string:
$regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
preg_match_all($regexp, $str, $m);
return isset($m[0]) ? $m[0] : array();
}
?>


Email address validator

Author: Tobias Ratschiller & izzy, http://www.zend.com/tips/tips.php?id=224&single=1

<?php

/*
Original script by Tobias Ratschiller.
* top level domain must have at least 2 chars
* there can be more than one dot in the address
*/

function is_email($address) {
$rc1 = (ereg('^[-!#$%&'*+./0-9=?A-Z^_`a-z{}~]+'.
'@'.
'[-!#$%&'*+\/0-9=?A-Z^_`a-z{}~]+.'.
'[-!#$%&'*+\./0-9=?A-Z^_`a-z{}~]+$',
$address));
$rc2 = (preg_match('/.+.ww+$/',$address));
return ($rc1 && $rc2);
}
?>


Emailer Class

author: edolecki, http://www.bigbold.com/snippets/tag/php/6

<?php
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class Emailer {
// required for EventDispatcher:
public var addEventListener:Function;
public var removeEventListener:Function;
private var dispatchEvent:Function;

// use to communicate with php script
private var _lv:LoadVars;
// holds address of sender
private var _sentFrom:String;
// constructor
public function Emailer() {
EventDispatcher.initialize(this);
_lv = new LoadVars();
}
//
private function dataReceived(dataxfer_ok:Boolean):Void {
// if some problem with loadVars transfer, pass back error=2
if (!dataxfer_ok) dispatchEvent({target:this, type:'mailSent', errorFlag:2});
// otherwise pass back error code returned from script
else dispatchEvent({target:this, type:'mailSent', errorFlag:Number(_lv["faultCode"])});
}
// Use loadvars object to send data (set to call dataReceived when script returns data)
public function sendEmail(sub:String, fn:String, fe:String, msg:String, rep:String):Void {
// if user already sent from this address, show error msg
if (_sentFrom == fe) dataReceived(false);
// otherwise set up and send
else {
_sentFrom = fe;
// specify function to handle results, make scope = Emailer
_lv.onLoad = Delegate.create(this, dataReceived);
// set up properties of lv to items to be POSTed
_lv.subject = sub;
_lv.name = fn;
_lv.email = fe;
_lv.message = msg;
_lv.reply = rep;
// call script
_lv.sendAndLoad("sendemail.php", _lv, "POST");
}
}
}
?>


6 Eylül 2007 Perşembe

Php maker

* Advanced Security
* User registration system
* Export to CSV/HTML/Excel/Word/XML
* File uploading to database or folder
* Master/Detail
* Custom View
* Report
* Customizable template
* Database re-synchronization

Demo


26 Ağustos 2007 Pazar

phpDesigner 2007 Professional 5.5.1















Syntax Highlighters


•Intelligent Highlighter that automatically switch between PHP, HTML, CSS, and JavaScript depending on your position!
•PHP (both version 4 and 5 are supported)
•SQL (MySQL, MSSQL 2000, MSSQL 7, Ingres, Interbase 6, Oracle, Sybase)
•HTML/XHTML
•CSS (both version 1 and 2.1 are supported)
•JavaScript
•VBScript
•Java
•C#
•Perl
•Python
•Ruby

Intelligent and Advanced Editing

•PHP code explorer shows all classes, extended classes, interfaces, properties, functions, constants and variables
•Intelligent code suggestions for PHP with full support for PHP 5.2, nested objects and object-oriented programming!
•Intelligent code suggestions for HTML/XHTML
•Intelligent code suggestions for CSS (both version 1 and 2.1 are supported)
•Intelligent code tip are displayed as you type, it shows you description, arguments and returning values for typed PHP functions including what version its available in!
•Highlight (un)matching brackets/tags
•Select or jump to matching brackets/tags
•Automatic indent or close brackets
•Jump to any declaration with filtering by classes, interfaces, functions, variables or constants
•Auto completions and corrections
•Bookmarks (1-9)
•Search and replace in multiple files with support for highlighting search results and regular expression
•Drag-n-drop text and files are supported
•Advanced printing options

Project and File Management

•PHP Code explorer shows all classes, extends, interfaces, properties, functions, constants and variables in the project
•Jump to any declaration in project files with filtering by classes, interfaces, functions, variables or constants
•Framework support
•Integration with 3rd party tools like Tortoise SVN or Tortoise CVS in the file and project browser

PHP

•Support for both PHP 4 and PHP 5
•Work with any PHP frameworks!
•Support for PHP heredoc
•Enclose strings with single- or double quotes, linefeed, carriage return or tabs
•PHP server variables
•PHP statement templates (if, else, then, while…)
•PHP code beautifier with many configurations
•phpDocumentor wizard
•Add phpDocumentor documentation to functions and classes with one click!
•phpDocumentor tags
•Smarty tags
•Comment or uncomment with one click!

Debug/Run & Preview

•Live syntax check for PHP, HTML and CSS
•Debug/Run PHP using the PHP Interpreter
•Syntax check PHP using the PHP Interpreter
•Localhost Preview
•Preview with Internet Explorer, Firefox, Netscape, Opera and Safari

HTML/XHTML

•Support for HTML 4.01 strict/transitional/frameset
•Support for XHTML 1.0 strict/transitional/frameset
•Link-, image-, table-, list-, meta-, flash, forms-, font and color dialog
•Formatting tools
•Color picker
•HTML Tidy (code beutifier for HTML/XHTML)

Integrated Help

•Contextual help for PHP (detailed information about more than 3000 native PHP functions on the fly using the PHP manual)
•Contextual search (search engines)

Code Libraries

•PHP
•phpDocumentor
•Smarty
•SQL (MySQL, MSSQL 2000, MSSQL 7, Ingres, Interbase 6, Oracle, Sybase)
•HTML
•XML
•CSS
•JavaScript
•VBScript
•Java
•C#
•Perl
•Python
•Ruby

Tools

•Application Manager
•Code Snippets
•Code templates allow you to type whole code fragments with one single click!
•Remote FTP editing
•Todo & Bug manager (embedded and external)
•Database connection manager
•Database browser (using phpMyAdmin)
•Date/Time Manager
•SSI
•TortoiseSVN integration
•Export to HTML, RTF and LaTeX

File Encoding

•ANSI (iso/windows)
•UTF-8 (with and without BOM)
•UTF 16 LE/BE (with and without BOM)

User Interface

•Fully customizable workspace with drag- and floatable toolbars/panels
•Theme support
•Save/load desktop layout

Free trial download


22 Ağustos 2007 Çarşamba

How to Find the Current URL with PHP

source: http://discomoose.org/2005/11/02/how-to-find-the-current-url-with-php/

<?php
// find out the domain:
$domain = $_SERVER['HTTP_HOST'];

// find out the path to the current file:
$path = $_SERVER['SCRIPT_NAME'];

// find out the QueryString:
$queryString = $_SERVER['QUERY_STRING'];

// put it all together:
$url = "http://" . $domain . $path . "?" . $queryString;
echo "The current URL is: " . $url . "<br />";

// An alternative way is to use REQUEST_URI instead of both
// SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
$url2 = "http://" . $domain . $_SERVER['REQUEST_URI'];
echo "The alternative way: " . $url2;
?>


11 Ağustos 2007 Cumartesi

The Essential Guide to Dreamweaver CS3 with CSS, Ajax, and PHP (Paperback)


With over 3 million users worldwide, Adobe's Dreamweaver is the most popular web development software in the world, and it just took another step forward with CS3, the new version released in 2007. Having come a long way from it's humble beginnings as a as a simple web design tool, CS3 allows you to rapidly put together standards compliant web sites and dynamic web sites with server -side languages and Ajax, and much more.

What youll learn:
* How to set up your ideal development environment, using Mac OSX/Windows, Apache (and IIS on Windows,) Apache, MySQL, and phpMyAdmin
* Creating standards compliant web sites using CS3's XHTML and CSS features
* Creating dynamic web applications using CS3's PHP and Spry Ajax server behaviors
* Building several real world web site functions, such as form validation, random quote generator, search function, user management/login pages, dynamic Ajax gallery, and much more.
* Creating an interface design in Fireworks CS3 and importing it into Dreamweaver CS3.
* How use Dreamweaver CS3's XML functionality, to consume RSS feeds, and create Spry data sets
* Using includes, templates and master detail pages.
* How to publish your site after you've created it


1 Temmuz 2007 Pazar

Strip HTML code & make data safe!

function make_safe($variable)
{
$variable = htmlentities($variable, ENT_QUOTES);

if (get_magic_quotes_gpc())
{
$variable = stripslashes($variable);
}

$variable = mysql_real_escape_string(trim($variable));
$variable = strip_tags($variable);
$variable = str_replace("\r\n", "", $variable);

return $variable;
}


Reading a TAB Delimited File

$filename = "Book1.txt";
$fd = fopen($filename,"r");
$contents = fread ($fd,filesize ($filename));
fclose($fd);

$splitcontents = explode(" ", $contents);
$counter = 0;

foreach($splitcontents as $data)
{
echo $counter++;
echo ": " . $data;
}


Read an write tab seperated files (like CSV files, etc).

function write_tabbed_file($filepath, $array, $save_keys=false)
{
$content = '';

reset($array);
while(list($key, $val) = each($array)){

// replace tabs in keys and values to [space]
$key = str_replace("\t", " ", $key);
$val = str_replace("\t", " ", $val);

if ($save_keys){ $content .= $key."\t"; }

// create line:
$content .= (is_array($val)) ? implode("\t", $val) : $val;
$content .= "\n";
}

if (file_exists($filepath) && !is_writeable($filepath)){
return false;
}
if ($fp = fopen($filepath, 'w+')){
fwrite($fp, $content);
fclose($fp);
}
else { return false; }
return true;
}

//
// load a tab seperated text file as array
//
function load_tabbed_file($filepath, $load_keys=false)
{
$array = array();

if (!file_exists($filepath)){ return $array; }
$content = file($filepath);

for ($x=0; $x < count($content); $x++){
if (trim($content[$x]) != ''){
$line = explode("\t", trim($content[$x]));
if ($load_keys){
$key = array_shift($line);
$array[$key] = $line;
}
else { $array[] = $line; }
}
}
return $array;
}

/*
** Example usage:
*/

$array = array(
'line1' => array('data-1-1', 'data-1-2', 'data-1-3'),
'line2' => array('data-2-1', 'data-2-2', 'data-2-3'),
'line3' => array('data-3-1', 'data-3-2', 'data-3-3'),
'line4' => 'foobar',
'line5' => 'hello world'
);

// save the array to the data.txt file:
write_tabbed_file('data.txt', $array, true);

/* the data.txt content looks like this:
line1 data-1-1 data-1-2 data-1-3
line2 data-2-1 data-2-2 data-2-3
line3 data-3-1 data-3-2 data-3-3
line4 foobar
line5 hello world
*/

// load the saved array:
$reloaded_array = load_tabbed_file('data.txt',true);

print_r($reloaded_array);
// returns the array from above


Retrieve the size of all files in an directory

function dir_size($path)
{

// use a normalize_path function here
// to make sure $path contains an
// ending slash
// (-> http://codedump.jonasjohn.de/snippets/normalize_path.htm)

// to display a good lucking size you can use a readable_filesize
// function, get it here:
// (-> http://codedump.jonasjohn.de/snippets/readable_filesize.htm)

$size = 0;

$dir = opendir($path);
if (!$dir){return 0;}

while (($file = readdir($dir)) !== false) {

if ($file[0] == '.'){ continue; }

if (is_dir($path.$file)){
// recursive:
$size += dir_size($path.$file.DIRECTORY_SEPARATOR);
}
else {
$size += filesize($path.$file);
}
}

closedir($dir);
return $size;
}


How to strip file extension

function strip_ext($name)
{
$ext = strrchr($name, '.');

if($ext !== false)
{
$name = substr($name, 0, -strlen($ext));
}

return $name;
}

// demonstration
$filename = 'file_name.txt';
echo strip_ext($filename)."n";

// to get the file extension, do
echo end(explode('.',$filename))."n";


Checks whether a file or directory exists

$filename = '/path/to/foo.txt';

if (file_exists($filename))
{
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}


Get a List of Folders and/or Files

function listFolder($folder, $types = 0)
{
$functions = array(
1 => 'is_dir',
2 => 'is_file'
);

$folderList = array();

foreach( glob( "$folder/*" ) as $currentItem )
{
if( $types == 1 or $types == 2 )
{
if( $functions[$types]($currentItem) )
$folderList[] = basename($currentItem);
}
else $folderList[] = basename($currentItem);
}

return $folderList;
}


Format File Size

function GetFileSize($nBytes)
{
if ($nBytes >= pow(2,40))
{
$strReturn = round($nBytes / pow(1024,4), 2);
$strSuffix = "TB";
}
elseif ($nBytes >= pow(2,30))
{
$strReturn = round($nBytes / pow(1024,3), 2);
$strSuffix = "GB";
}
elseif ($nBytes >= pow(2,20))
{
$strReturn = round($nBytes / pow(1024,2), 2);
$strSuffix = "MB";
}
elseif ($nBytes >= pow(2,10))
{
$strReturn = round($nBytes / pow(1024,1), 2);
$strSuffix = "KB";
}
else
{
$strReturn = $nBytes;
$strSuffix = "Byte";
}

if ($strReturn == 1)
{
$strReturn .= " " . $strSuffix;
}
else
{
$strReturn .= " " . $strSuffix . "s";
}

return $strReturn;
}


Read directory contents

function dir_list($path){

$files = array();

if (is_dir($path)){
$handle = opendir($path);
while ($file = readdir($handle)) {
if ($file[0] == '.'){ continue; }

if (is_file($path.$file)){
$files[] = $file;
}
}
closedir($handle);
sort($files);
}

return $files;

}


Get a filename without knowing it's correct case

/*
I often pull info from files on NT shares into my Linux/PHP-powered web pages.
The problem I've run in to is that the cases of the files I need aren't constant.
Here is a function that will take a path and a filename. It will search that path for a
file matching that name, regardless of case, and return the name of the file in the
correct case, or null if it doesn't find it. Also included is another function which
this one uses, which gets a list of files for the given directory.

Works with PHP3 and PHP4.
*/

// Source Code

#============================================================
# Give it a path (defaults to .) and a filename. It will return
# null (if the file doesn't exist) or the filename as it appears
# in that path, in the correct case.
function getCasedFilename( $fname, $path="." )
{
$flist = getFileList( $path);

while( list($ndx,$f) = each( $flist ) )
{
if ( eregi( "$fname", $f ) ) {
return $f;
}
}

return null;
}

#============================================================
# Returns a list of all files in the given dir, excluding . and ..
# If no dir is passed, it uses the current dir.
# Returns null if it can't open the dir.
function getFileList( $dirname="." ) {
$flist = array();
$dir = opendir( $dirname );

if ( ! $dir ) { return null; }

while( $file = readdir( $dir ) )
{
if ( ereg( "^.$", $file ) || ereg( "^..$", $file ) ) continue;
$files[] = $file;
}
return $files;
}


Copy non-empty directory

// Path to this file by server directory structure.
$cfg_['localftpdir'] = join('/',array_splice(split("/",ereg_replace('\\',
'/', $PATH_TRANSLATED)), 0, count(split('/',ereg_replace('\\', '/',
$PATH_TRANSLATED)))-1));

// REMEMBER - No end backslash.
$startDir = $cfg_['localftpdir'].'/dir1';
$startDir = str_replace('//','/',$startDir); // for win systems
$endDir = $cfg_['localftpdir'].'/dir2';
$endDir = str_replace('//','/',$endDir); // for win systems

// Make base directory in end directory.
$arrCD = explode('/',$startDir);
mkdir($endDir.$arrCD[count($arrCD)-1],0700);
$endDir = $endDir.$arrCD[count($arrCD)-1];

function paste($param) {
$workDir = $param[0]; // Assign values to variables.
$endDir = $param[1]; // It's only for our comfort.
$var = $param[2]; //
$end = $param[3]; //

if ($dir = opendir($workDir.$var)) { // Open work directory.
$dirCount = 0; // Assume - there is no other directory in work directory.
while (($file = readdir($dir)) !== false) { // List all elements.
// If there is directory and it's not '.' and '..' that not exists in end directory.
// Choose first meet directory, select name and create it in end directory.
if ((is_dir($workDir.$var.'/'.$file) && (($file != '.') && ($file != '..')))
&& is_dir($endDir.$var.'/'.$file) == false) {
$dirCount++; break; // Break while - work directory is not empty.
}
if (is_file($workDir.$var.'/'.$file) && is_file($endDir.$var.'/'.$file) ==
false) {
copy($workDir.$var.'/'.$file,$endDir.$var.'/'.$file);
}
}
if ($dirCount==0) { // If there was no other directories.
if ($var == '' || $var == '/') { $end=true; } // And if we are in start directory this means we must finish copying.
else { // Else...
$var = str_replace('//','/',$var);
$arrVar = split('/',$var);
$arrVar = array_slice($arrVar, 0, count($arrVar)-1);
$var = join('/',$arrVar); // cut $var path one element from end.
}
}
else {
mkdir($endDir.$var.'/'.$file,0700); // Make chosen directory in end directory.
if ($var=='') { $var = '/'.$var.$file; } // Increase $var path.
else { $var = '/'.$var.'/'.$file; }
$var = str_replace('//','/',$var);
}
} closedir($dir); // Close work dir.

$param[0] = $workDir; // Assign values to array, ...
$param[1] = $endDir; //
$param[2] = $var; //
$param[3] = $end; //

return $param; // return array as a function result.
}

if ($dir = opendir($startDir)) { // Copy all files from main copied directory to end directory.
while (($file = readdir($dir)) !== false) {
if (is_file($startDir.'/'.$file) && is_file($endDir.'/'.$file) == false) {
copy($startDir.'/'.$file,$endDir.'/'.$file);
}
}
} closedir($dir);

// Assign starting values...
$end = false;
$param[0] = $startDir;
$param[1] = $endDir;
$param[2] = '';
$param[3] = $end;

// Copy directory.
while ($end !== true) {
$param = paste($param);
$workDir = $param[0];
$endDir = $param[1];
$var = $param[2];
$end = $param[3];
}

echo 'Done !';


Removes a folder, including its subfolders and files in a efficient way without recursion

function removeFolder($dir)
{
if(!is_dir($dir))
return false;
for($s = DIRECTORY_SEPARATOR, $stack = array($dir), $emptyDirs = array($dir); $dir = array_pop($stack);)
{
if(!($handle = @dir($dir)))
continue;
while(false !== $item = $handle->read())
$item != '.' && $item != '..' && (is_dir($path = $handle->path . $s . $item) ?
array_push($stack, $path) && array_push($emptyDirs, $path) : unlink($path));
$handle->close();
}
for($i = count($emptyDirs); $i--; rmdir($emptyDirs[$i]));
}