Monday, May 26, 2008

Things You Must Know About CakePHP

Original- http://www.avatarfinancial.com/pages/cake/

What's Cake?

Cake is a rapid development framework for PHP which uses commonly known design patterns like ActiveRecord, Association Data Mapping, Front Controller and MVC. CakePHP is basically the PHP equivalent of Ruby on Rails.

What should I read first?
If you are new to CakePHP, I highly recommend reading through the CakePHP manual and the 15 minute blog tutorial in addition to the items listed here. There are a ton of tutorials in the wiki, too.

Why the list?
CakePHP is very new, so documentation beyond the basics is a bit sparse in areas. I built this website entirely using CakePHP and took notes along the way to share with others. While some of these items can be found in obvious places like the manual, others required a bit of elbow grease to figure out. My name is Matt Inman and your feedback is welcome, feel free to email me with questions or comments.

Easily creating static pages
I needed to create several pages that didn't use any models and contained static data inside the default layout. My first thought was to create a controller for these pages and define an action for each static page I needed. However, this solution seemed tedious and would make it difficult to quickly add new pages. Enter the pages controller - simply create a view inside the views/pages/ folder and it'll automatically be rendered in /pages. For example, if I created /views/pages/matt.thtml it would be accessible via http://www.example.com/pages/matt

Static pages - Adjusting the page title
If you're using the pages controller and you need to change the page title, add the following to your view:
pageTitle = 'Title of your page.'; ?>

Static pages - Adjusting other data sent to the layout
If you need to send data to the layout (such as a variable indicating what section to highlight on the nav bar), add this to your view:
_viewVars['somedata'] = array('some','data'); ?>
That array should then be accessible as $somedata inside your layout.

Creating a simple admin center
If you need to create an administrative back-end for your CakePHP site and would like all the actions with administrative capabilities to exist under a specific folder, open up config/core.php and uncomment:
define('CAKE_ADMIN', 'admin');

This will then make all actions that are prefixed with "admin_" to be accessible via:
/admin/yourcontroller/youraction. For instance, if I created an action in my posts controller called "admin_add," I would access this via: www.example.com/admin/posts/add
From there I could simply password the admin folder to prohibit unwanted users from adding posts.

Viewing the SQL queries that are running behind the scenes
You can easily see the SQL queries that CakePHP is running by adjusting the DEBUG constant in config/core.php. 0 is production, 1 is development, 2 is full debug with SQL, and 3 is full debug with SQL and dump of the current object. I typically have debug set at 2, which renders a table at the bottom of the page that contains SQL debug information.

If rendering a table at the bottom of your site is constantly breaking your layout during development (especially if you're making AJAX calls and you're getting SQL inside your pages, not just the bottom), you can easily style this table to be hidden by adding this to your CSS:

#cakeSqlLog { display: none; }

This will allow you to view debug information in the HTML source code without your layout getting mangled, just don't forget to set debug back to 0 when your site goes live.

Multiple sources of documentation
Don't just rely on the manual. The wiki and the API are invaluable sources of information. The tutorials in the wiki are especially useful, and the API may be daunting at first, but you'll quickly find the information in there is crucial to building a site with CakePHP.

Using bake.php
Bake is a command line PHP script that will automagically generate a model, controller, and views based on the design of your database. I highly recommend using scaffolding to get a prototype going of a table that may change a lot in the beginning. If you're fairly certain the data is not subject to any drastic change, I recommend using bake instead. With bake all the files are generated and written to disk and you can make modifications from there. It saves a lot of time doing the repetitive tasks such as creating associations, views, and the basic CRUD controller operations.

Using bake is really easy. Once you have a table(s) in your database created, change directories to the /cake/scripts/ folder and run:
php bake.php

If you choose to bake interactively it'll walk you through the steps required to create your model, controller, and views. Once everything has been baked I usually go through all the generated code and make custom modifications as needed.

Mind permissions when moving cake around
When I changed from the development server to the live server I tarred up my entire cake directory and scp'd it to the new server. Immediately I started having an issue where any time the debug level was set to 0 (production mode), data would not be returned for certain database calls. This was a bit of a catch 22 since I needed to view debug information to troubleshoot the problem.
Someone in #cakephp kindly pointed out that permissions on the /app/tmp folder need to be writeable by apache. I changed the permissions to 777 and the issue went away.

Complex model validation
I needed to validate beyond just checking to make sure a field wasn't empty or it matched a regular expression. In particular, I needed a way to verify that the email address users registered with was unique. In the wiki I found this gem: this advanced validation tutorial, which covers some advanced methods of validation that were very useful.

Logging errors
$this->log('Something broke');
This will log your error to /tmp/logs/ (I initially made the mistake of thinking it would log it to the apache error log)

Creating a controller that uses other models
Suppose you have a controller that needs data from a bunch of different models, simply add this to the top of your controller:

class yourController extends AppController
{
var $uses = array('Post','User');
}

This controller would then have access to both the Post and the User model.

Creating a model for a table that doesn't actually exist in the database
I needed a way to create a model and controller without actually having an associated table in the database. I particularly wanted to make use of the $validate array so I could easily validate my fields and keep the validation logic in the model. CakePHP will throw an error if you create a model for a table that doesn't exist. Adding this to the model fixed the problem:
var $useTable = false;

You can use this to change tables names as well.
var $useTable = 'some_table';

Call exit() after redirecting
This should be no surprise to anyone who has done any serious web development in the past, but make sure you call exit() after running $this->redirect() if there's code afterward that you don't want to run. I've always done this in the past, but I made the assumption that $this->redirect() would make an exit call for me (which it didn't).

Advanced model functions
Unless you delve in to the API, there are some very useful model functions at your disposal you might not know exist. I highly recommend reading over the Model Class Reference at least once. Here's a few key functions I wasn't aware of that I found to be very useful:
· generateList() - I use this function primarily to populate select boxes with data from associated tables
· query() - Sometimes you just need to write your own SQL
· findCount() - Returns number of rows matching given SQL condition
· hasAny() - Returns true if a record that meets the given conditions exists.
Again, I highly recommend reading over the entire model class reference, you'll be surprised at what you learn.

Inserting multiple rows in succession
I had a situation where I needed to iterate through a list of items and insert new rows for each. I quickly discovered that if you insert an item and then immediately insert another, the item that is inserted next doesn't insert at all. Instead the previously inserted row was being updated. For example:

$items = array('Item 1','Item 2','Item 3');
foreach ($items as $item) {
$this->Post->save(array('Post' => array('title' => $item)));
}

This code will result in a single entry in the posts table: "item 3." CakePHP inserted "item 1", but then updates it to become "item 2," then "item 3" because $this->Post->id gets the value of the last inserted ID. Normally this functionality is very useful, but in this particular instance it was not. I found was to setting $this->Post->id = false after each insert solved the problem.

Update: Someone emailed me and apparently the proper way of doing this is to call create() to initialize the model and then set/save your new data.

Inserting logic before or after controller functions
Suppose you needed an array of colors to be available to every view rendered by your controller but you don't want to have to define this data in every action. Using the beforeRender() callback will allow you to do this:

function beforeRender() {
$this->set('colors',array('red','blue','green');
}

This would make $colors accessible in every view rendered by that controller. beforeRender() is called after the controller logic and just before a view is rendered.
There's also beforeFilter() and afterFilter(), which are called before and after every controller action. For more information, read up on callbacks in the models section of the manual.

Adding a WYSIWYG editor to CakePHP
I found this great tutorial on getting TinyMCE set up with CakePHP. Basically you just link the tiny_mce .js file to your page and then add a small bit of init code to every page that you want textareas to be converted into TinyMCE editors.

Writing your own SQL for HABTM relationships
I had an issue with trying to create a HABTM (has-and-belongs-to-many) relationship where I needed to specify my own SQL statement. According to the docs (at the time of this writing) you should set finderSql in your model, but according to the cakePHP source you should set finderQuery instead. It's just a foul-up in the docs, but I figured it'd be worth noting to save others from having to figure it out for themselves. Trac ticket here: https://trac.cakephp.org/ticket/1217

Sending email
I found two tutorials in the wiki: Sending email and Sending email with PHPMailer
I highly recommend the latter of the two, sending emails with PHPMailer is more secure and there's less of a headache because you don't have to deal with constructing the mail headers yourself.

Customizing HTML generated by the Helper
I needed to change the default generated when I called $html->selectTag() to say something like "Please Select" rather than an empty space (default). I also wanted radio buttons to have labels so the user doesn't have to click exactly on the radio button itself but can instead click anywhere on the text associated with it.

Create the file /app/config/tags.ini.php and add the following:
; Tag template for a input type='radio' tag.
radio = ""

; Tag template for an empty select option tag.
selectempty = "-- Please Select --"

You can get a full list of available tags in /cake/config/tags.ini.php. I wouldn't recommend modifying that file, however, because you could lose your changes when you upgrade CakePHP.

Creating a custom 404 error page
If you need to change the page that users see when a document is not found, create:
/app/views/errors/error404.thtml

Thursday, May 22, 2008

Copy directory to directory with all sub-directory and files using FTP

////////////////////////////////////////////////////////
// Copy directory to directory with all sub-directory and files using FTP
// By:
// Ahmed Samir
// asamir@asamir.net
// www.asamir.net
//
////////////////////////////////////////////////////////



function ftp_copyAll($conn_id, $src_dir, $dst_dir) {
if(
is_dir($dst_dir)){
return
"
Dir $dst_dir Already exists
"
;
}else{
$d = dir($src_dir);
ftp_mkdir($conn_id, $dst_dir); echo "creat dir $dst_dir
"
;
while(
$file = $d->read()) { // do this for each file in the directory
if ($file != "." && $file != "..") { // to prevent an infinite loop
if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
ftp_copyAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
} else {
$upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
echo "creat files::: ".$dst_dir."/".$file ."
"
;
}
}
ob_flush() ;
sleep(1);
}
$d->close();
}
return
"

All Copied ok "
;
}
// end fn function ftp_copyAll



//$ftp_user_name = 'asamirftp@phpeg.net';
//$ftp_user_pass = 'asamirftp123';
//$ftp_server = 'phpeg.net';

// connect to FTP server
$ftp_user_name = 'FTP_User_name';
$ftp_user_pass = 'FTP_Password';
$ftp_server = 'FTP_Server';


$conn_id = @ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

// login into FTP server
if (@ftp_login($conn_id, $ftp_user_name, $ftp_user_pass)) {
//echo "Connected as $ftp_user_name@$ftp_server\n";
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 1000); // Set the network timeout to 10 seconds

$copy_result = ftp_copyAll($conn_id, 'Folder', 'FolderCopy');

echo
$copy_result;

}else{
echo
"Couldn't connect as $ftp_user\n";
}

@
ftp_close($conn_id); // colse of ftp_connect
// @ftp_quit($conn_id);

?>

Thursday, May 15, 2008

PHP & MySQL Web Development

php & MySQL Web development video, interview with Luke Welling and Laura Thomson

Thursday, May 8, 2008

Adobe Flash Professional CS3 Portable

Adobe® Flash® CS3 Professional software is the most advanced authoring environment for creating rich interactive content including websites, online advertisements, instructional media, presentations, games, and mobile device content.

Flash CS3 Professional offers nearly limitless opportunities to student designers and developers who are interested in building careers using interactive design technology. Flash CS3 is a common denominator that integrates with and supports a broad spectrum of emerging technologies, including Ajax, 3D animation, online video, and open source development.
Flash CS3 Professional is now part of the Adobe Creative Suite® family. Learn more about Creative Suite 3 and education.

Download from Rapidshare
http://rapidshare.com/files/111747207/Adobe-Flash-Professional-CS3-Portable.part1.rar
http://rapidshare.com/files/111747209/Adobe-Flash-Professional-CS3-Portable.part2.rar
http://rapidshare.com/files/111747211/Adobe-Flash-Professional-CS3-Portable.part3.rar
http://rapidshare.com/files/111747212/Adobe-Flash-Professional-CS3-Portable.part4.rar

Download from Easy-Share
http://w15.easy-share.com/1700290706.html
http://w15.easy-share.com/1700290705.html
http://w15.easy-share.com/1700290704.html
http://w15.easy-share.com/1700290703.html

Monday, May 5, 2008

Build A Customizable RSS Feed Aggregator In PHP

Although there are several commercially available feed aggregators, it's easy to develop your own feed aggregator, which you can integrate with your Web applications. You'll appreciate this article's fully functional PHP code snippets, demonstrating the use of PHP-based server-side functions to develop a customizable RSS feed aggregator.

Read More :-
http://www.ibm.com/developerworks/library/wa-aj-rssphp/index.html?S_TACT=105AGX44&S_CMP=EDU

Friday, May 2, 2008

Php And Mysql Programming Security

Choosing php and mysql as programming language for a website is not enough. With open source coding being one of the inherent properties of php mysql development, securing your codes becomes essential. So when one allows the users to upload files on the website, then security is definitely at stake.

PHP Programming Protection

While it is not entirely possible to protect your site, yet there are few precautions that you can incorporate for better protection of PHP programming. Some of these are:
  • You should check the referrer, for being sure that the information sent is from your website and not an outside source. Since, there are maximum chances of the information being fake.
  • Restriction of the type of extension files being uploaded on the website is yet another method of security check.
  • Renaming files is another way in which the program can be secured. This procedure involves the checking of double-barreld extensions like yourfile.php.gif.
  • Changing the permission command for the upload folder so that files within it are not executable.
  • All the alterations created by the user should be allowed only when they ‘Login’ into the database. On the other hand the owner of the site should always keep a close watch on all files being uploaded and then make them live.
Mysql Programming Security

Another aspect in php and mysql web development is the protection of the mysql libraries. Therefore, the most important aspect involved in protecting the mysql program is the security of the entire server host.

Securing MySQL is very essential for the smooth running of the website. This is based on Access Control Lists and SSL-encrypted connections, for protecting the php mysql web development program from random users visiting the website.

Some of the vital things to be considered for online site protection are:
  • Accessing of the mysql database should not be allowed for any and everyone.
  • Privileges to the users should always be accompanied with some restriction. If one can easily connect to the server without any ‘login’ then the security level code of the MySQL server should be rechecked.
  • The MySQL database should be void of plain-text passwords. Use programs like MD5 (), SHA1(), or some hashing function for complete protection.
  • Do not choose passwords from dictionaries, since they can be hacked easily. Use programs that break the passwords.
Therefore, the successful development of a website through php and mysql web development is complete only when the site owner consults a professional programmer. They expertise in the optimization of the MySql hosting database. This program is dynamic in nature and is an effective tool in the creation of browser-based applications.