Posting Data To PHP Using PostBackUrl - Part 2

by Saurabh 22. January 2008 20:55

Couple of years ago I did a blog post about using PostBackUrl with PHP. Although the code sample I used as illustration was a ASP.net page in it's simplest form, real world ASP.net pages aren't as simple as that. Almost any ASP.net web app that does a little more than just input some form data and flush it out would be doing so with the help of user controls and/or Master Pages. This complicates the HTML form entity names as it prefixes the user specified IDs with a number of _ (underscores) and $ signs.

So how can your PHP script read form data when element names ain't that simple anymore? Allow me to illustrate. Say we have a very basic Master page like this:

   1: <%@ Master Language="C#" AutoEventWireup="true" CodeFile="verybasic.master.cs" Inherits="Masters_verybasic" %>
   2:  
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:  
   5: <html xmlns="http://www.w3.org/1999/xhtml" >
   6: <head runat="server">
   7:     <title>Untitled Page</title>
   8: </head>
   9: <body>
  10:     <form id="form1" runat="server">
  11:     <div style="clear: both; width: 100%; text-align: center;">MASTER HEADER. <br />
  12:         <asp:CheckBox ID="CheckBox1" runat="server" Text="Master's chkBox" /></div>
  13:     <div>
  14:         <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
  15:         </asp:contentplaceholder>
  16:     </div>
  17:     </form>
  18: </body>
  19: </html>

And we have a simple webform that uses the above master:

   1: <%@ Page Language="C#" MasterPageFile="~/Masters/verybasic.master" AutoEventWireup="true" CodeFile="p2php.aspx.cs" Inherits="p2php" Title="Post To PHP" %>
   2: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
   3:     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   4:     <br />
   5:     <asp:Button ID="Button1" runat="server" Text="Submit" PostBackUrl="catchpostback.php" />
   6: </asp:Content> 

To read values of controls that are part of the Master page, the form itself or user controls, we will exploit the fact that in all such cases the form elements are "prefixed" with their containers and a bunch of underscores & dollar signs to the original developer specified control IDs. We can build a function similar to the one below:

   1: function getFormVar($var,$isPostBack = false)
   2: {
   3:     $retVal = "";
   4:     if($isPostBack == true)
   5:     {
   6:         $var = $var.'$';
   7:         foreach($_POST as $key => $r)
   8:         {
   9:             if(ereg($var,$key))
  10:                 return $_POST[$key];
  11:         }
  12:         return "";
  13:     }
  14:     else
  15:     {
  16:         if(isset($_REQUEST[$var]))
  17:         {
  18:             return $_REQUEST[$var];
  19:         }
  20:         else
  21:             return $retVal;
  22:     }
  23: }

To read the value of a control say TextBox1 you do something like this: $myvar = getFormVar("TextBox1",true);

The function getFormVar can read regular form elements as if they were from a PHP or HTML page, but when the 2nd parameter is set to true it loops through the POST variables and returns the value of the element of a ASP.net control (buried inside a user control or a master page) while you only specify the control ID you used in the ASP.net itself.

Some tidbits of this function you should know:

  • Although it gets you started, this function is not a complete solution. For example if the form element you want to read is part of a user control which has more than one instances on the page, it will fail flat out. But you can easily change the regex to enable reading in those cases.
  • I used ereg() instead of preg_match()  (comparatively fast) in my function as preg_match() might not be available on many setups.

A complete working demo can be downloaded from here.

There's one more thing that's pretty interesting IMO; ASP.net posts the entire form to the target page specified in PostBackUrl and of course __EVENTTARGET is empty!

Demo in action!

Tags: ,

Programming

A PHP4 version of PHPLiveX with ExternalJS property

by Saurabh 10. January 2008 20:51

The beauty of PHPLiveX is its astute simplicity that makes it among the best AJAX libraries for PHP. The dev team has now shifted to focus to PHP5, so ver. 2.3 is the last version for PHP4. Although a bit late, it was realized that for the sae of brevity and maintaining clean & tidy code support for outputting the javascript to a file rather than inline was made. Only a minor version too late for developers working on PHP4 code. So although folks using PHPLiveX 2.4 and above get to enjoy a more readable HTML output, the ExternalJS property is not supported by any official build for PHP4. But adding it is surprisingly easy!

I have been working to AJAXify an old PHP4 app on client insistence, this app is deployed on PHP4 and hence cannot use ExternalJS property. And I like my HTML to tidy up. So this is what I did to add ExternalJS to PHPLiveX 2.3 that was used in the project.

Start by adding a new property ExternalJS to the class. And then modify the Run method to something like this:

   1: function Run(){
   2:     $html = $this->CreateJS();
   3:     for($i=0;$i<count($this->FList);$i++){
   4:         $html .= $this->CreateFunction($this->FList[$i]);
   5:     }
   6:     if(empty($this->ExternalJS)){
   7:         echo "<script type='text/javascript' language='javascript'>" . $html . "</script>";
   8:     }
   9:     else{
  10:         if(!file_exists($this->ExternalJS)){
  11:             $fp = fopen($this->ExternalJS, "w");
  12:             if($fp != false){
  13:                 fwrite($fp, $html);
  14:                 fclose($fp);
  15:             }
  16:             else
  17:                 echo "<script type='text/javascript' language='javascript'>" . $html . "</script>";
  18:  
  19:  
  20:         }
  21:         echo "<script type='text/javascript' src='{$this->ExternalJS}'></script>";
  22:         }
  23: }

That's it! You can get rid of inline embedding of the PHPLiveX javascript. Similar to ver. 2.4 and above the call to Run() must not be inside the <script></script> tags. You can download a modded ver. 2.3 file with ExternalJS property from here.

You can further enhance this code a little more, like - Restrict the ExternalJS property to not use paths or you could restrict it to a bunch of desired paths.

Tags:

Programming

THE DARK KNIGHT TRAILER

by Saurabh 22. December 2007 14:50

If you haven't watched the trailer of THE DARK KNIGHT yet, I highly recommend you do! If you liked Christopher Nolan & Christian Bale's approach to Batman, it doesn't really take a genius to predict that you will like this summer 2008 release. The high definition trailer is available is available on the official website in QuickTime & Windows Media (as zipped files). Here's the direct link to the videos page.

Tags:

News

When The A-Team Strikes - Do It The Long Zheng Way!

by Saurabh 22. November 2007 05:48

Many technology enthusiasts like to share the cool its and bits of the UI from the latest & greatest software that has become their new favorites, among each other. And yes, many a times they do cross the legal boundaries.

So what do you do when you get a cease & desist notice?
LOLCat cease and desist
Well, if you're a tech-enthusiast and do not have affiliations with some factory-based piracy operations or much worse - a shoddy design team that's gonna rip off the very company (read Apple/Microsoft or your favorite company) that built your new favorite thing. There is not much you can do but comply. But hey, do it the Long Zheng way when the Microsoft A-Team served him a notice about this blog post.

Tags:

General

This CRYSIS Must Not Be Averted!

by Saurabh 16. November 2007 06:47

This year's biggest FPS game for the PC - CRYSIS™ (Crytek/EA Games) was released worldwide yesterday. Every FPS fan out there must get this game. I can see that the CRYSIS™ Nanosuit will gain the iconic stature shared by the HEV Hazard Suite adorned by Gordon Freeman. It's a shame though that I can't even buy the just-announced nVidia 8800GT priced at a sweet price of $250 I'll need to play it on my home desktop. Sad

The game contains -

An Epic Single Player Campaign – Players are thrust into the middle of a global conflict between the US and North Korea over a mysterious artifact that turns out to be extraterrestrial in nature. Fortunately, players are outfitted with a high tech Nanosuit that allows them to alter their strength, speed, armor and cloaking abilities and an arsenal of fully customizable weapons, helping to even the playing ground against a highly mysterious and intelligent enemy threat.

Multiplayer Reinvented – Crytek has also focused much of their development efforts in creating two unique multiplayer experiences. PowerStruggle is a new, team-based multiplayer mode where players need to work together strategically to capture resource points throughout the map to win the ultimate arms race for nuclear technology. And for those who are looking for a more action-packed experience Crysis also features Instant Action, traditional deathmatch made even more frenetic as every player is outfitted with the revolutionary Nanosuit.

CryENGINE 2TM Sandbox Editor – Also included with Crysis is the complete version of Crytek’s Sandbox Editor. Extremely powerful with a simple user interface, the editor will give the community full access to one of the most powerful design tools in the industry.

Tags:

News

Visually Differentiate Command Prompt Window in Normal Mode From Administrator Elevated Mode

by Saurabh 10. November 2007 14:44

If you need to run the command prompt with elevated privileges on a regular basis if not as often as the standard command prompt. You probably would have have probably created a shortcut in the start menu programs folder or your desktop for easy access.

But how do can you visually differentiate between a normal command prompt window from an elevated command prompt window. Of course, the title of elevated CMD.exe is prefixed by "Administrator: " followed by <Your Shortcut Name> e.g. I always name my shortcut "ELEVATED CMD" so the title says "Administrator: ELEVATED CMD". But there's another way, you can set the colors of the command prompt windows to be visually different. I bet its easier for you to see which command prompt window below is running with elevated privileges.


Normal vs. Elevated Command Prompt

So all you gotta do is change the colors of the command prompt once inside Admin. Elevated mode and again for the normal command window (that you usually invoke via typing "CMD" in Start Menu's Run Command). You might receive a prompt to save the settings for the current Window or the shortcut that launched this window, choose the latter option. I prefer to work with white background so I have set it to Green text for Normal and Maroon for ELEVATED CMD whereas the color for popup text in both cases is gray.

Tags: ,

Windows

How To Export/Backup Firefox Search Engines

by Saurabh 17. October 2007 18:40

Sometimes it becomes hard to find things that otherwise seem blatantly obvious. I was searching on Google to backup the search engines my Firefox and realized that this information isn't easily reachable. Of course hardcore Firefox users would tell you this even when they're half asleep, but me; I don't fall in that category.

Updated!
The information below has been updated for Firefox 3.6.

So here is what needs to be done. Get to your profile folder of Firefox, if you don't know how to get there, you need to know how to reach Firefox's profile folder.

Inside the Firefox folder, there is a folder called searchplugins which contains all the engines, one XML file per engine. Use your discretion to backup the engines, you may want to backup the entire folder or you may want to export/backup engines selectively.

Firefox 3.5 and above: Besides backing up the searchplugins folder, you also need to backup search.json & search.sqlite (if exists).

For details on the various files and folders in the profile folder, read the KB article on mozillazine.

Tags:

General

IE 7 sans WGA - Lose Big or Lose Small For Microsoft

by Saurabh 6. October 2007 08:39

Yesterday, Microsoft released a refreshed build of Internet Explorer 7 for Windows xp that no longer requires WGA check. If you're wondering why Microsoft decided to do it or why now? Mary Jo Foley has pretty much nailed it.

It's obvious that it's in Microsoft's best interests to let pirates install IE 7 more easily (not that it was impossible) to improve its market share rather than let Firefox gain over it due restrictions enforced by Microsoft itself.

So all you pirates out there, if you weren't able to download IE7 for obvious reasons. Get it now!

Tags: ,

News

Installing AnkhSVN on Vista

by Saurabh 25. September 2007 07:36

I wouldn't have to make this post if I could post a comment on Jesse Johnston's entry which would most probably solves the problem for anybody. It's just that there's a small explanation missing. Since you will be running Visual Studio as the administrator not pseudo admin that you may probably be, and since that's a different account than yours, remember to install AnkhSVN for "All Users" instead of "Just Me".

Tags: ,

Windows | Programming

How To Export/Backup IE 7 Search Providers

by Saurabh 19. September 2007 20:35

I thought this would be so easy to find, a simple search for "Backup IE 7 Search Providers"  on Google would fetch me the answer. But no sir, I found no such thing! I even did a search on Microsoft and even the Knowledge Base but didn't find what I was looking for. The one page that did help me find the solution has an altogether different title.

Well the good news is that; it is really easy!

Simply backup the following registry key and you're done.
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\SearchScopes

Tags:

Windows