How To: Fixing CakePHP Broken GET Query Strings

October 9th, 2012 1 comment

After getting familiar with CakePHP 2.x for a little while, writing an application, I had a need to perform an AJAX action  using the query string of an HTTP GET request. I’ve done it countless times using straight PHP, ASP.Net, even custom constructed requests from C# desktop applications.  How difficult could it be? After all, the idea behind these PHP frameworks is to take all the heavy lifting out of writing your code, right? I set out writing the AJAX links to construct my query string using CakePHP’s JsHelper.

I started out by writing a simple query string with a single key/value and then retrieving it with some AJAX. It worked perfectly! Then I added a few more key/value pairs to the string and that’s when things went down hill. Apparently, I stumbled on to bug in the way CakePHP handles and encodes URL Query strings. Funny thing is, this bug was discovered and fixed in a previous version of the framework, but some how found it’s way into the code base again in version 2.x. Research revealed a number of work-arounds and hacks, most included editing a core file or two. I, however, did not want to have to resort to messing with core files of the framework, because they would likely be overwritten again after a version update or upgrade, leaving me back where I started. Instead I decided to “repair” the parts of the query string that CakePHP broke.

So, How did CakePHP Break the Query String Anyway?

A typical URL Query String should look something like this after it’s sent to the browser.

http://www.domain.com/?Key1=firstvalue&Key2=secondvalue&Key3=thirdvalue

The query string itself is all the text that appears AFTER the ‘?‘. In this case the query string is

Key1=firstvalue&Key2=secondvalue&Key3=thirdvalue

The string consists of three parameters and their values, each seperated by the ‘&‘ character. Where URL Query Strings are concerned, the & character is used as a delimiter to show where one key/value pair ends, and the next begins.

  1. Key1 = firstvalue
  2. Key2 = secondvalue
  3. Key3 = thirdvalue
Now we should be able to pull each of the key / value pairs with some simple code. The problem with CakePHP, however is that it encodes “special” characters in the URL string before sending it off.  So the & character is encoded and sent as &. After this happens, our Query String now looks like
Key1=firstvalue&Key=secondvalue&Key3=thirdvalue
Notice how the second and third key/value pairs have now changed.  Remember, the & character is used as the delimiter between key/value pairs, so that everything after the & character is read as part of the key/value pair up to the next & character. The result is that the key names now appear to be amp;Key2and amp;Key3
  1. Key1= firstvalue
  2. amp;Key2 = secondvalue
  3. amp;Key3= thirdvalue
Now, when we try to pull the Key2 or Key3 values in our application, they don’t exist.

Wonderful, So How Can We Fix This?

To be honest, this is more of a work-around than a “fix”, but one that I think is feasible until CakePHP developers fix the underlying problem. What we’re doing here undoing the damage the CakePHP did by taking the ‘broken’ query string and rebuilding it again with the correct delimiters and key names.

if($this->request->is(‘ajax’)){
$temparray = $this->params['url'];

foreach($this->params['url'] as $key => $value){

if(strpos($key, ‘amp;’) !== false){
$newkey = str_replace(‘amp;’,”,$key);
unset($temparray[$key]);
$temparray[$newkey] = $value;
}

}
$this->layout = ‘ajax’;
if($this->Model->save($temparray)){
echo ‘success’;
}
else{
echo “<br><strong>OOPS! something went wrong, refresh the page to reset your list</strong>”;
}
$this->autoRender = false;
exit();

else{
$this->Session->setFlash(“Not an AJAX request!”);
$this->redirect(‘/Model/View‘);
}

Break It Down

To see what’s happening here, lets step through code.

  • if($this->request->is(‘ajax’)){
    The first line checks to see if the page contains an AJAX request. If it does, then the code continues into the IF block and continues.
  • $temparray = $this->params['url'];
    If the page does contain our AJAX request, this line creates a new variable called temparray and sets it’s value to an associative array created by using CakePHP ‘params’ attribute with the URL parameter.  Basically, we’re just creating a copy of the associative array of Query String parameters. We create a copy of the original string because CakePHP will not allow us to alter the params array directly.
  • foreach($this->params['url'] as $key => $value){
    Next we start a foreach loop to iterate through all the URL parameters to access each parameter of the associative array setting the paramater name as $key and it’s value as $value.
  • if(strpos($key, ‘amp;’) !== false){
    Next, as we loop through each item in our array, we’re checking the string of each parameter name ($key) to see if it contains the encoded & string &amp; that CakePHP created.
  • $newkey = str_replace(‘amp;’,”,$key);
    If there is a match, we remove the ONLY the amp; portion of the string. We leave the leading & alone as we still need that as part of the new query string. Note here that the ” passed in the st_replace function is two single quotations and not one double. We’re replacing the amp;  found in the string with an empty string. Once we have our new string minus the amp; portion, we assign it to the $newkey variable.
  • unset($temparray[$key]);
    Now that we have the new parameter name with delimeter, we need to reconstruct the array by first removing the old array key.
  • $temparray[$newkey] = $value;
    Then, we add our newly created key $newkey and assign to it the original paired value, $value.
  • }  }
    The next two lines contain our closing brackets for the conditional IF block and next for the foreach loop.
  • $this->layout = ‘ajax’; 
    This line is just telling CakePHP to use our AJAX layout. Moving on…
  •  if($this->Model->save($temparray)){
    Now we can use our “New” array with any of CakePHP’s functions, classes etc. In this example, I’m using a conditional If statement and passing the array as part of CakePHP’s save function to update a bit of data in my database.
  • echo ‘success’;
    If the data update is successful, send the “success” string back  so that our AJAX handler can update the page.
  • }
    The next line contains the bracket that closes our conditional If statement
  • else{
    After that we have the followup to our If condition. If the data saved, do something, if not, do something else.
  • echo “<br><strong>OOPS! something went wrong, refresh the page to reset your list</strong>”;
    As part of the if / else condition, if the data update failed, then we send the error message back  so that our AJAX handler can update the page.
  • $this->autoRender = false;
    This line tells CakePHP not to render the page after we finish working our magic. Because we’re using AJAX to update the page, we don’t need CakePHP to keep reloading and rendering the page. AJAX is taking care of that for us.
  • exit();
    Next, if we got this far, there should be nothing else for us to do and we can tell CakePHP to wrap it up and quit doing anything further.
  • else{
    This else condition is the alternative to our beginning  If statement – if($this->request->is(‘ajax’)). If the page received a request, but not from our AJAX handler, then we need to do something about it.
  • $this->Session->setFlash(“Not an AJAX request!”);
    If the page received a request, but not from our AJAX handler, the we’re telling CakePHP to set a notification message to show on the page and inform the viewer that the request was “Not an AJAX request!”
  • $this->redirect(‘/Model/View‘);
    Finally, continuing with the alternative else actions, we need to tell CakePHP to redirect us back to a page (Model/View). Otherwise, because the example code used here called a Controller function using AJAX without an associated view, CakePHP would choke and complain about missing View files. IF you are calling a Controller function from AJAX that DOES have an associated CakePHP view, then you will not need this line.
  • }
    And to wrap it all up is the closing bracket bring our final else block to a close.

This sample was used as part of an existing application with specific conditions and goals. Some of the details in this How To may not apply to the specifics of your situation and this article should be used only as a guide.

That’s it. This is just one way to overcome the URL query string bug in CakePHP. There are other ways as well. I hope this at least helps in some way. Good luck and happy coding.

How To: Read Only DataGridView Control, C#

August 15th, 2012 No comments

Quick Tip:
By Default, DataGridView control columns are set as editable, but in many cases, you may not want your grid data to be edited, or you may want to set your own controls that enable when and how the data get edited. The following C# code snippet will set the DataGridView columns of your DataGridView to ReadOnly.

foreach(DataGridViewColumn dc in My_DataGridView.Columns){
dc.ReadOnly = true;
}

This snippet iterates through the  DataGridView.Columns collection and sets  the ReadOnly property for each DataGridViewColumn item referenced as dc to true (boolean).

Microsoft Security Intelligence Report Volume 8

April 29th, 2010 No comments

The Microsoft Security Intelligence Report (SIR) is a comprehensive and wide-ranging study of the evolving threat landscape, and addresses such topics as software vulnerability disclosures and exploits, malicious software (malware), and potentially unwanted software.

Volume 8 of the Security Intelligence Report (SIR v8) covers July 2009 through December 2009. It includes data derived from more than 500 million computers worldwide, each running Windows. It also draws data from some of the busiest services on the Internet, such as Windows Live Hotmail and Bing.

In this volume, the analysis is from the perspective of the three Microsoft Trustworthy Computing Security Centers in addition to several Microsoft product groups.

Microsoft has released volume 8 of their Security Intelligence Report. 248 pages of in-depth information about malware, spam, malicious Web sites, vulnerabilities, and exploits with Mitigation Strategy, advice and best practices from Microsoft’s own IT organization. Should make for some good weekend reading.

Posted via web from Ed’s Posterous

Categories: Uncategorized Tags:

Technology and IT Training on a Budget.

April 20th, 2010 No comments

Keeping your skills sharp with free online training and educational resources.

School Bus

Photo Credit: iboy_daniel

In my opinion, one of the biggest challenges faced by IT and Technology Professionals is keeping up with technology. It’s also one of the most important for any Technology Pro that plans to stay relevant and remain competitive in the field. This is something I can speak on from experience. Technology is in a constant state of change, and everything you’ve mastered today might be less relevant in 6 months or a year. It is important for Tech Pros not only to keep up on the latest technology, but also to revisit and brush up on some of the standard technologies as well.

Add this constant rate of change to the state of the economy, reduced or even no training budgets, or worse, an unemployed IT worker that needs to pick up a new skill set to compete in a scarce job market and you may start to feel a little overwhelmed.

Working for a company that has so far provided no formal training assistance, I have relied on other methods and resources to educate myself and stay focused on tech. The web is full of training, course materials, ebooks and other self-study and educational resources, all available for free. I thought I’d share a few of my favorite ones with you here.

HP Learning Center

The HP Learning Center is full of resources and instruction for a range of IT levels and functions from Business and Business Process, to PC Maintenance and Security, to courses specifically targeting the IT Professional.

MIT Open Courseware

MITOpenCourseware is provided by Massachusetts Institute of Technology and is loaded with free courses and materials. In addition to Technology and computer Sciences, you can find courses and materials  covering other subjects including Architecture, Biology, Engineering, Economics, Physics, and much more.

Some of the courses date back a few years, but over all the information and materials are still relevant.

Linux Online

http://www.linux.org/lessons/

Linux Online provides free online Linux training courses broken down into Beginner, Intermediate and Advanced courses.

You will also find a couple additional areas with more focused Tips and How-To’s to satisfy your quick fix.

Academic Earth

Academic Earth is a lot like MIT Open Courseware in terms of providing access to a range of educational topics. In addition to Computer Science, you can catch up on subjects including Mathmatics, Physics, Philosophy, Chemistry and more. One main difference is that Acacemic Earth has connected with select instructors at several Universities including MIT, Stanford, Harvard, and Berkely to provide free access to online learning materials and video “class lectures”.

Microsoft Learning

Microsoft Learning provides both Free and paid training courses and materials. I included it here because it does have a lot of free training available if you want to browse through the learning catalog. Courses and resources here cover Office, Server Technologies, Dynamics, Windows OS (servers and desktops) and a few other areas.

Runner-up

Open University has a number of general computer and IT related learning courses

This is a shortlist of some of the more “formal” resources. Let’s not forget all the incredible smart people who share with us what they have learned in countless blogs, online communities and personal web sites. If you know of any other great free online learning resources for technology professionals, share them in the comments.

Tech Humor: Password Policy

March 9th, 2010 No comments

Found this in an IT blog comment about Network Password Policies.

During a company’s recent password audit, it was found that a blonde employee was using the following password:

MickeyMinniePlutoHueyLouieDeweyDonaldGoofySacramento

When asked why she had such a long password, she said she was told that it had to be at least 8 characters long and include at least one capital.

 

Posted via web from Ed’s Posterous

Categories: Personal Tags: ,

FTW – Netflix takes a proactive approach, steps up and owns it.

February 11th, 2010 No comments
I signed up for a Netflix account recently after purchasing a new Blu-ray player that supports Netflix movie streaming. I figured "Wow, this is great. I can watch movies when I want from my netflix queue." My only worry was, would my current internet connection be able to sustain a quality viewing experience. I still have Verizion DSL. My town does not have FiOS available (and no plans to), and my location has an effect on overall DSL speeds. I've learned to live with it.

So when I had some intermittent problems accessing and watching movies via netflix, I assumed it was due to my connection. That is, until I received an email from Netflix that stated:

"Recently, you may have had trouble instantly watching movies or TV episodes via your Netflix Ready Device due to technical issues.

We are sorry for the inconvenience this may have caused. This is not a great way to begin your Netflix membership. So that you can properly experience Netflix, we would like to extend your free trial.."

I did not complain about the service, and in fact attributed it to my sometimes questionable DSL connection. But Netflix was right there to voluntarily step up, take the initiative and say oops, we goofed. It's refreshing to see a company take responsibility for their service without being prompted.

There is the argument that I am still on a trial membership basis, and they are just trying to initiate some damage control to keep me on as a paying user when the trial expires. Maybe, but it's good to know they are keeping tabs on the service and own it when something goes wrong.

Posted via email from Ed’s Posterous

Categories: Uncategorized Tags:

WordPress: Use Custom Fields To Add Keyword Metadata to Your Posts

February 4th, 2010 11 comments
Keywords at edwardstafford.com

Keywords for edwardstafford.com

One of the short-comings with using WordPress is that it does not provide an easy, built-in way to include metadata for your web page descriptions and keywords (and rightfully so). Why Not? The reason is simply that WordPress cannot read your mind. I know it’s hard to believe when you consider what you can do with wordpress, but it’s true. The issue with Description and Keyword page metadata is that, to be truely effective, it should be created to  describe the content found on each individual page. It’s how search engines like google determine how to categorize and index each page. Now, there are some SEO “experts” who will argue that this information is not very relevant anymore, and I do agree with that for the most part, but there are still SEO benefits to including this metadata vs. not including it at all.

I’ve been giving this some thought lately and developed a couple ideas of how to add these features into a wordpress site without too much difficulty. A bulb went off in a moment clarity when I started to think about using the Custom Fields to store page specific metadata. I was even naive enough to think I was on to something new (should have known better) but as I started researching some ideas, I realized there were others already doing similar things. Oh well, a minor detail. I took my own approach to the idea anyway, if for no other reason than a learning exercise. Ultimately, this could be added as a premium feature to any custom theme using a couple hooks and some custom theme options magic.

Read more…

What are your credentials worth?

February 3rd, 2010 No comments

Security Watch posted an interesting article today discussing the value of personal login credentials, or username and password combinations used to access online services. I often get asked question about why people hack into computers, or write and spread viruses and malware. My answer has always been that it’s less about damaging computers or systems anymore, and more about being stealthy and collecting valuable information that can be used for monetary gain. This article paints a general picture and help to explain of how much our information is worth, answering the question – Why do they do it?.

Twitter credentials worth $1,000 to cybercriminals
Gmail account worth $80.00 +

According to the article, the actual value of account credentials is based mainly on popularity of the application, and the `popularity’ of the account, but I’d also include type of application, authority of the account holder, and the probability of an account granting access to additional valuable data as determining overall value of the credentials.

Read the full Article here.

Posted via web from Ed’s Posterous

Beer O’Clock Friday Selections! Now On Posterous

January 20th, 2010 2 comments

As some of you may already know, I like Beer!! And if you didn’t, well, you do now! Not just any beer, but good quality microbrews, craft beers, and foreign treats. You’ll never find Budweiser mentioned here – well… except for that, but it won’t happen again.

A little more than a year ago, I decided to start a weekly Beer O’Clock ritual by selecting a different brew each Friday to feature and share thoughts about it with friends online. Let me state from the start that I am in no way a beer snob, expert, aficionado or anything else along those lines. I just like beer and want to experience as many different kinds as I can and try to learn a little more about the different types of brew along the way. I’ve even tried adding my incredibly amateur opinions / reviews with selections when I can.

Up till now, I used flickr, twitter and facebook to post weekly selections. But now it’s time to graduate to something a little more permanent, so I have set up a posterous page to post weekly selections to. The good thing about posterous is that the Flickr, Twitter, and Facebook updates will still continue.

So, if you like beer and want to check out what’s being featured each week and share your own thought and opinions about them, head over to http://beeroclock.posterous.com

Posted via web from Friday Beer O’clock Selections

Categories: Uncategorized Tags:

Cheap & Easy Social Media Management? Really?

December 15th, 2009 No comments

Saw an email today soliciting “Cheap & Easy Social Media Management”

For the most part I don’t pay too much attention to these claims, but this one hit a nerve. Below is a the excerpt that sums it up.

… Most of you are too busy to do it all yourself and don¹t want the hassle of fussing with the technology. Some of you have thrown up your hands in despair.

So here’s the good news: We’re going to do it for you, and it’s not expensive. For a limited time, you can start for as little as $XXX.xx [edit] a month. Our new business, [removed] , will review and setup all the components of your social media infrastructure. We’ll even extract and write your blogs, or edit your original blog posts. We’ll twitter for you and maintain your connections. Without breaking a sweat, you’ll be a master of the new social media.

The Bold parts are what I have a problem with. The Red Bold part is what put it over the edge for me. Really? I can be a Social Media Master by letting someone else pretend to be me and do all the work? Who knew it was that easy?

I was always under the impression that this Social Media thing was about being a real person, with a real voice, with real ideas and opinions. Conversing, interacting, engaging with and getting to know other real people. Is it possible that I had this all wrong the whole time?

Is this sort of thing now common practice? I would think there are a great number of risks involved if your exposed, or when the service agreement ends. What happens then? The more I think on this, the more questions I have about it.

I don’t claim to be a Social Media expert or even a “Master” and I know there are legitimate business out there that help other businesses and brands build and create Social Media profiles and identities, but their claims just seem wrong regarding Social Media.

Posted via web from Ed Stafford – Mobile Mutterings

Categories: Uncategorized Tags: