Friday, May 25, 2007

PHP-Directories filenames to database

// a sinple function to create a database connection
function db_connect() {
$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("dbname", $conn);
}
// this function will open the chosen directory and returns and array with all filenames
function select_files($dir) {
if (is_dir($dir)) {
if ($handle = opendir($dir)) {
$files = array();
while (false !== ($file = readdir($handle))) {
if (is_file($dir.$file) && $file != basename($_SERVER['PHP_SELF'])) $files[] = $file;
}
closedir($handle);
if (is_array($files)) sort($files);
return $files;
}
}
}
// this function inserts the filename and the modification date of the current file
function insert_record($name, $mod_date) {
$sql = sprintf("INSERT INTO example SET filename = '%s', lastdate = '%s'", $name, $mod_date);
if (mysql_query($sql)) {
return true;
} else {
return false;
}
}
// establish database connection
db_connect();
// enter the table structure if not exists
mysql_query("
CREATE TABLE IF NOT EXISTS example (
id bigint(20) unsigned NOT NULL auto_increment,
filename varchar(255) NOT NULL default '',
lastdate datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (id),
FULLTEXT KEY domain (filename)
) TYPE=MyISAM;");

// creating the current path
$path = dirname(__FILE__);
// the trailing slash for windows or linux
$path .= (substr($path, 0, 1) == "/") ? "/" : "\\";
// get the filenames from the directory
$file_array = select_files($path);
// creating some controle variables and arrays
$num_files = count($file_array);
$success = 0;
$error_array = array();
// if the file array is not empty the loop will start
if ($num_files > 0) {
foreach ($file_array as $val) {
$fdate = date("Y-m-d", filectime($path.$val));
if (insert_record($val, $fdate)) {
$success++;
} else {
$error_array[] = $val;
}
}
echo "Copied ".$success." van ".$num_files." files...";
if (count($error_array) > 0) echo "\n\n
\n".print_r($error_array)."\n
";
} else {
echo "No files or error while opening directory";
}
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-Daily (random) banner

mysql_connect("localhost", "user", "password");
mysql_select_db("database_name");
// create table for the banners
mysql_query("
CREATE TABLE IF NOT EXISTS `banners` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(35) NOT NULL default '',
`link` varchar(150) NOT NULL default '',
`alt_title` varchar(100) NOT NULL default '',
`image` varchar(35) NOT NULL default '',
`ins_date` date NOT NULL default '0000-00-00',
`status` enum('on','off') NOT NULL default 'on',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1");

// create the table for storing todays banner id
mysql_query("
CREATE TABLE `rand_banner` (
`id` int(11) NOT NULL auto_increment,
`date` date NOT NULL default '0000-00-00',
`todays_id` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1");

// first check if todays banner id is already stored
$check_today_sql = "SELECT todays_id FROM rand_banner WHERE date = NOW()";
$check_today_res = mysql_query($check_today_sql);
if (mysql_num_rows($check_today_res) > 0) {
$id_today = mysql_result($check_today_res, 0, "todays_id");
} else {
// if not select a random id and store the id in the table with current date
$get_ids_sql = "SELECT id FROM banners WHERE status = 'on'";
$get_ids_res = mysql_query($get_ids_sql);
$get_ids_array = array();
while ($get_ids = mysql_fetch_object($get_ids_res)) {
$get_ids_array[] = $get_ids->id;
}
$num = count($get_ids_array);
// I use the function rand() because other random functions are not "really random"
$rand_num = rand(0, $num-1);
$id_today = $get_ids_array[$rand_num];
mysql_query("INSERT INTO rand_banner (id, date, todays_id) VALUES (NULL, NOW(), $id_today)");
}
// at least select the record with the todays ID
$result = mysql_query("SELECT link AS url, alt_title, image FROM banners WHERE id = $id_today");
$obj = mysql_fetch_object($result);

// this example will show the current banner
echo "url."\">image."\" alt=\"".$obj->alt_title."\" border=\"0\">";
?>

Disclaimer: Any code or advice
given is for instructional purposes only. We will not be responsible for
any loss or damage caused by using this script.

PHP-Get TemplateMonster data

// For more information: visit http://www.templatemonster.com/webapi/
$num_records = 4;
$aff_link = "http://www.all4yourwebsite.com/";
$tm_url = "http://www.templatemonster.com/";
$tm_url .= "webapi/templates_screenshots4.php";
$param['last_added'] = "Yes"; // this value is case sensitive
$param['full_path'] = "true";
$param['order'] = "asc";
$param['sort_by'] = "date";
$param['filter'] = "1";
// add additional filters / parameters here
// building querystring from the parameters
$qs = "?";
foreach ($param as $key => $val) {
$qs .= $key."=".$val."&";
}
$qs = rtrim($qs, "&");
// now get the records from the TM webapi
$request_from = $tm_url.$qs;
$all_rows = file($request_from);
// now split the data for each row into an multi dim. array
for ($i = 0; $i < $num_records; $i++) {
$data[$i] = explode("\t", $all_rows[$i]);
}
$t_row = "
\n";
foreach ($data as $row) {
// read the information about more attr.
$id = $row[0];
$price = $row[1];
$all_images = explode(",", trim($row[15], "{}"));
$t_row .= "
\n";
$t_row .= "
\n";
foreach ($all_images as $img) {
if (preg_match("/-m.jpg$/", $img)) {
$thumb = $img;
}
}
$thumb_size = getimagesize($thumb);
$t_row .= " ";
$t_row .= "\n";
$t_row .= "
\n";
$t_row .= "
\n";
$t_row .= "

Price: $".$price."

\n";
$t_row .= "
\n";
}
$t_row .= "
";
// How to use? Just "echo $t_row" inside the documents body.
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Thursday, May 24, 2007

PHP-Text wrapper plus

function text_wrap($log_text, $limit, $divider=" ") {
$words = explode($divider, $log_text);
$word_count = count($words);
$char_counter = 0;
$block = "";
foreach ($words as $value) {
$chars = strlen($value);
$block .= $value;
$char_counter = $char_counter + $chars;
if ($char_counter >= $limit) {
$block .= " \\n ";
$char_counter = 0;
} else {
$block .= " ";
}
}
return rtrim($block);
} ?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-URL / domain name splitter

$url_parts = parse_url("http://mail.finalwebsites.co.uk");
$domain = $url_parts['']
$res = mysql_query("SELECT tld FROM domain_info ORDER BY LENGTH(tld) DESC");
// "ORDER BY LENGTH(tld)" will give first the co.uk and then the uk
while ($arr = mysql_fetch_assoc($res)) {
$tmp_tld = substr($domain, -strlen(".".$arr['tld']));
if ($tmp_tld == ".".$arr['tld']) { // You found the tld
$tld = ltrim($arr['tld'], ".");
$domainLeft = substr($domain, 0, -(strlen($tld) + 1)); // It will left the whatever, without the extension and the .
if (strpos($domainLeft, ".") === false) { // It hasn't a subdomain
$subDomain = "";
$finalDomain = $domainLeft;
} else {
$domain_parts = explode(".", $domainLeft);
$finalDomain = array_pop($domain_parts); // select the domain and remove it from the array
$subDomain = implode(".", $domain_parts); // a subdomain can more then one parts seperated with dot's
}
echo "The tld is: ".$tld."
";
echo "the domain name is :".$finalDomain."
";
echo "the subdomain is: ";
echo (!empty($subDomain)) ? $subDomain : "n/a";
echo "
";
break;
}
}
?>

Disclaimer : Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

PHP-Simple attachment mail script

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use diff. tyoes here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
echo = "mail send ... OK"; // or use booleans here
} else {
echo = "mail send ... ERROR!";
}
}
// how to use
$my_file = "somefile.zip";
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

Monday, April 2, 2007

PHP- Client URL Library Function


$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.