PHP & CakePHP Articles

RSS Feed - PHP & CakePHP

Emailing through Google Apps / Gmail on CakePHP

Tags: Email, PHP, CakePHP | Written on Jun 07, 2009

When launching new websites and web applications, it is difficult to get on trusted email lists of Hotmail, Yahoo and Etc. Aside from having proper SPF records, a great way to avoid this sysadmin problem is to use Gmail / Google Apps to offload your domain's email to their servers. By doing this, your domain gets an instant trust factor with receiving mail servers that a new server simply cannot do in a short period of time.

To email with Google Apps / Gmail with CakePHP, I've had recent success using the SwiftMailer CakePHP component. It is easy to use and leverages the PHP SwiftMailer library.

Configuring SwiftMailer CakePHP Component with Gmail

This is pulled off the component article's example, but I posted it here as well for your reference.

PHP:
  1. $this->SwiftMailer->smtpType = 'tls';
  2. $this->SwiftMailer->smtpHost = 'smtp.gmail.com';
  3. $this->SwiftMailer->smtpPort = 465;
  4. $this->SwiftMailer->smtpUsername = 'name@domain.com';
  5. $this->SwiftMailer->smtpPassword = 'your_password';
  6.  
  7. $this->SwiftMailer->sendAs = 'both';
  8. $this->SwiftMailer->from = 'name@domain.com';
  9. $this->SwiftMailer->fromName = 'Full Name';
  10. $this->SwiftMailer->to = 'to_name@domain.com';
  11. $this->SwiftMailer->template = 'your_action';
  12. $this->SwiftMailer->subject = 'your_subject'

I added two custom attributes here, template and subject because I find I like to set that as a variable instead of putting it in the send function (in the next step).

Emailing with SwiftMailer CakePHP Component

The send function has 3 parameters, but we are only concerned with the first two since we've already configured our settings in the step above. The first is the template found in /views/elements/email, the second is the subject.

PHP:
  1. try {
  2.     if(!$this->SwiftMailer->send($this->SwiftMailer->template, $this->SwiftMailer->subject)){
  3.         $this->log("Error sending email");
  4.     }
  5. } catch(Exception $e) {
  6.     $this->log("Failed to send email: ".$e->getMessage());
  7. }

You will also notice here that we are wrapping the send function in a try/catch block. This allows us to output whatever caused the function to fail through an exception (and fail silently), rather having the component either kill the client to output the message, or simply return false with no explanation like a lot of things in CakePHP-land. Try/catch blocks work great in non-mission critical things like sending an email, conturary to the core library which should simply fail and exit the application.

I had one error on my local computer with TLS not being installed into PHP. So I added the following line to my PHP compile to add TLS support:

Bash:
  1. --with-openssl

My entire PHP compile looks like this...

Bash:
  1. sudo make clean && sudo ./configure --prefix=/usr/local/php5  --with-pear --enable-sockets --with-iodbc=/usr --with-curl=/usr --with-mysql=/usr/local/mysql --without-iconv --with-apxs2=/opt/local/apache2/bin/apxs --with-zlib-dir=../zlib-1.2.3/ --with-jpeg-dir=../jpeg-6b --with-openssl --with-gd --with-freetype2=/Developer/SDKs/MacOSX10.5.sdk/usr/X11/include/freetype2/freetype && sudo make && sudo make install

As an alternative to SwiftMailer, I was pointed to joshua's solution on the mailing list to use the built-in CakePHP email component with Gmail. Apparently he got it to work, but I couldn't for whatever reason.

Enjoy having mail go through to your users without fail!

Yahoo! Search BOSS Integration with CakePHP

Tags: CakePHP, Yahoo, API | Written on Jul 17, 2008

CakePHP Logo Yahoo Search Boss Description

Note on March 21st, 2008: Neil Crookes made a nice Yahoo! Boss CakePHP Plugin that I would recommend over my code. Neil's fits much better into the CakePHP environment.

Tutorial - CakePHP Ajax "Quick Save" with jQuery

Tags: CakePHP, jQuery | Written on Jul 15, 2008

When you are in an administration panel, sometimes you want a "quick save" feature that allows you to save without leaving the page.  Here is how to accomplish this with CakePHP and jQuery.

To start, download jQuery and the jQuery Form Plugin JavaScript.  Include them in your view with the JavaScript helper:

PHP:
  1. $javascript->link(array('jquery', 'form'), false);

Include the RequestHandler in your controller detect an Ajax save attempt.  Also include the JavaScript helper if you haven't already.

PHP:
  1. var $helpers = array('Javascript');
  2. var $components = array('RequestHandler');

Next we want to override our save function with the ajax quick save.  Put this right before your $this->Model->save($this->data) in your save action.

PHP:
  1. if ($this->RequestHandler->isAjax()) {
  2.     if ($this->Article->save($this->data)) {
  3.         echo 'success';
  4.     }
  5.     Configure::write('debug', 0);
  6.     $this->autoRender = false;
  7.     exit();
  8. }

This detects if the request is ajax, then saves the data.  Then it sends back a simple, "success" message to let you know things went fine.  It also writes debug to 0 and doesn't render anything, then exits.

Lastly, lets create and include a JavaScript file that performs the quick save.

JavaScript:
  1. jQuery(function($){
  2.     $('<input type="button" value="Quick Save" />')
  3.         .click(function(){
  4.             $(this).parents("form:first").ajaxSubmit({
  5.                 success: function(responseText, responseCode) {
  6.                     $('#ajax-save-message').hide().html(responseText).fadeIn();
  7.                     setTimeout(function(){
  8.                         $('#ajax-save-message').fadeOut();
  9.                     }, 5000);
  10.                 }
  11.             });
  12.             return false;
  13.         })
  14.         .appendTo('form div.submit');
  15. });

This adds a button called, "Quick Save" to each form on the page where a div with class="submit" exists (you may want to switch this to the id of the form you want to add quick save to). Then It also attaches a click event to the button that submits the form via the jQuery Form Plugin.

In a few simple steps, we've created a quick save feature that saves your data whenever you want without leaving the page.

CakePHP Email Encoding

Tags: CakePHP | Written on Feb 12, 2008

My email was not getting sent using the email component in CakePHP. I debugged inside the core and found out that my subject was getting changed to something like, "=?UTF-8?B?V2VsY29tZ...".

In talking to Larry (core CakePHP team), he educated me that this allows for characters other than the English language to be sent via email (UTF-8 encoding). Even though it apparently was correct, it was still not being received at my personal email or a Yahoo account. Gmail got it, the others didn't.

The Alternate Email Encoding (English only)

Larry showed me the alternative way to encode that works just fine for English characters. If you are having trouble with receiving these UTF-8 encoded emails, try sending with iso-8859-15 (only English characters). You can try the English encoding using this line of code:

PHP:
  1. $this->Email->charset = 'iso-8859-15';

This works for English-only applications, but if anyone can offer up a solution as to why Yahoo and Media Temple email accounts are not getting the UTF-8 emails please let me know. It is strange to me that gmail gets it just fine. Until then, I am only planning on sending English emails anyway so there is no issue until I build a multi-lingual application.

CakePHP Asset Mapper

Tags: CakePHP, PHP | Written on Dec 26, 2007

Released my CakePHP Asset Mapper. I've always wanted an easier way to control my JavaScript and CSS includes and this is the solution I came up with. Controls the entire web application's includes in one file!

Here is an example of a mapping rule:

PHP:
  1. $this->AssetRule->create();
  2. $this->AssetRule->compact->css = array('site','global');
  3. $this->AssetRule->compact->scripts = array('jquery', 'ui.datepicker');
  4. $this->AssetRule->runRule();

Accross the entire site, this would compact the site.css and global.css files together and run them through CSS Tidy. jQuery.js and ui.datepicker.js would be compacted together and then ran through JSMin.

Great, this simplifies a complex process of compacting and minimizing - while still giving you the freedom to include scripts normally. Compacting lowers the amount of http requests you website makes, increasing website performance. JSMin and CSS Tidy strip comments and whitespace leaving your files much smaller in size.

You can create a rule to include files in a specific controller and/or action with AssetRule->map and AssetRule->controller:

PHP:
  1. $this->AssetRule->create();
  2. $this->AssetRule->map->controller = 'posts';
  3. $this->AssetRule->map->action = 'admin_add';
  4. $this->AssetRule->compact->css = array('user');
  5. $this->AssetRule->runRule();

This would only include your 'user.css' file in the, 'posts' controller - with the action, 'admin_add'. The css file would be compacted with the others.

Some scripts like TinyMCE, include other files (so it can't be compacted with the others) and requires a codeblock to be initialized. This configuration satisfies TinyMCE:

PHP:
  1. $this->AssetRule->create();
  2. $this->AssetRule->map->action = 'admin_edit';
  3. $this->AssetRule->scripts = array('tiny_mce/tiny_mce');
  4. $this->AssetRule->codeblock = 'tinyMCE.init({
  5.    mode : "textareas",
  6.    theme : "advanced",
  7.    plugins : "media",
  8.    media_external_list_url : "media/list.js",
  9.    theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,outdent,indent,redo,link,unlink",
  10.    theme_advanced_buttons2 : "",
  11.    theme_advanced_buttons3 : "",
  12.    theme_advanced_resizing : true,
  13.    theme_advanced_toolbar_location : "top",
  14.    theme_advanced_toolbar_align : "left",
  15.    theme_advanced_statusbar_location : "bottom",
  16.    extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
  17. });';
  18. $this->AssetRule->runRule();

Coming from a heavy UI developer background, I can afford to be incredibly anal when managing my CSS and JavaScript files. I hope this saves you time, frustration and makes your developer-life better.

PHP Development in Eclipse

Tags: Free Tools, PHP | Written before Dec, 2007

Eclipse IDE Auto Complete

I have been writing a CakePHP application and quickly realized I need something better for PHP development then Dreamweaver. I found PDT (Eclipse with PHP Plugins) and I am amazed at the helper tools they have for PHP developers. It has auto complete, tree view to browse functions and syntax highlighting. I probably haven't scratched the surface for its features.

I was blown away with PDT I am going to use it from now on for PHP development. I had to do one setup for PDT to recognize CakePHP's thtml files:

  • Window->Preferences
  • General->Content Types->PHP Content Type
  • Add in *.thml

Thats it! I'm looking forward to better application development with Eclipse.

Edit CakePHP's THML / CTP files with Dreamweaver

Tags: CakePHP | Written before Dec, 2007

Note on July 15th, 2008: I haven't used dreamweaver for a long time, this article was written back in cake 1.1 days.  I suggest Text Mate for Mac OS X, and E Text Editor for Windows.

Dreamweaver Add THTML

I needed Dreamweaver to recognize a new file extension called, "thtml" for CakePHP. Here is how I got Dreamweaver to recognize new code extensions and highlight them correctly:

  1. Edit your Extensions.txt file: C:\\Documents and Settings\\User\\Application Data\\Macromedia\\Dreamweaver 8\\Configuration
  2. Add in the new file extension into its type: HTM,HTML,HTA,HTC,XHTML,THTML:HTML Documents
  3. Now Dreamweaver recognizes the new file types but to get code highlighting you need to edit your MMDocumentTypes.xml file: C:\\Program Files\\Macromedia\\Dreamweaver 8\\Configuration\\DocumentTypes
  4. Add in the new file extension to HTML winfileextension.

Here is the full article by Adobe: Adobe: Changing and adding file extensions recognized by Dreamweaver

5 PHP Book Purchases

Tags: Books, PHP | Written before Dec, 2007

I purchased 5 PHP books from Bookpool this morning. I am really excited to learn PHP security and check out the cookbook PHP examples. A friend suggested the SAMS book and Programming PHP, 2nd Edition was the #1 best selling book on bookpool. I will let you know what I think of them when I get a chance to dig through them.

  • Essential PHP Security - $18.50
  • PHP and MySQL Web Development, 3rd Edition - $31.95
  • PHP Cookbook, 2nd Edition - $28.50
  • PHP Solutions: Dynamic Web Design Made Easy - $21.95
  • Programming PHP, 2nd Edition - $24.95

Essential PHP SecurityPHP and MySQL Web DevelopmentPHP CookbookPHP SolutionsProgramming PHP

Create a Blog from Scratch

Tags: PHP, MySQL | Written before Dec, 2007

Note on June 23, 2008: The post you are reading is years old, but shows the trail of the beginnings of MarcGrabanski.com. Thank you for reading!

Without much prior PHP knowledge, I managed to program this blog in less than a week. Here is how I did it. Note: This is an overview and not actual code examples.

  1. First, I went through Code Grrl's Build a Blog Tutorials

    Sure, I could have stopped there but I really didn't like how the blog was programmed. I like this tutorial though because I dug through the code and learned basic PHP, but I wanted much more functionality.

  2. I wanted clean URLs so I found Making "clean" URLs with Apache

    I customized the url so I can add keywords inside it if I want. I love these clean URLs. Apache also has documentation on mod_rewrite.

  3. Then I added user authentication

    This was the most basic, yet effective login script I found. Of course I modded it to make it a little more secure.

  4. I rewrote the code to use Object Oriented PHP

    My blog was basically built but I didn't like how the code looked. I thought PHP looked horrible until I ran into some object oriented code. Makes things look much nicer.

  5. Created Tag Cloud Navigation

    I started with ByteMyCode's Tag Cloud code and then moved to selecting from the database with the "LIKE" MySQL commmand.

    Mysql:
    1. $sql = "SELECT * FROM php_blog WHERE tags LIKE '%$tag%' ORDER BY timestamp DESC";

    I also had to count the tags so I used the array_count_values PHP function.

    PHP:
    1. $tags = array_count_values($DBtags); // a very useful function to count the tags!

    Wow gotta love those tags!

  6. Added More Features

    I added an image uploader to my admin page, RSS 2.0 and many minor tweaks until I had my very own customized blog built from scratch!

Some functions I found very useful on php.net:

PHP:
  1. list()
  2. split()
  3. htmlspecialchars()
  4. str_replace()
  5. explode()
  6. include(dirname(__FILE__)

I now have my own custom blog! You can too! I heavily modified each example and made them my own. It feels so nice to have a custom blog!

Other Categories