As artists think alike…

June 7, 2009

8 PHP functions I won’t ever miss

Category: Programming » Web

I’m always at most careful and concerned about security and especially idiot-proofing whenever I’m into developing some usual stuffs. PHP specifically, does not only provide it’s "FREEness", but also the handiest functions I always do not miss to consider. Here are my Top 8.

1-2. addslashes() and mysql_real_escape_string()

These two functions are a bit related, in a sense that these provide security especially in handling things with your database queries. As their name suggest, the first function adds slashes (escapes) to these characters in a string: ‘, ", \, while mysql_real_escape_string() escapes \x00, \n, \r, \, ‘, " and \x1a. In a more complicated security issue, most programmers prefer mysql_real_escape_string() since it prevents certain loop holes like escaping quotes (characters) which later lead to SQL injection.

3. stripslashes()

If slashes may be added to strings, then at some point, you would also need to strip them out. This is when stripslashes() comes in. Though I don’t really often use this function, but it becomes handy when you need to print an HTML code through a JavaScript code all from a PHP source. Just don’t forget this function, surely you will have to remember it as soon as you would need its purpose.

4-5. urlencode() and urldecode()

Printing anchors, source urls, url outputs, form validation using GET or POST method, urlencode() musn’t be missed out for use. Usually, the absence of this function especially when handling anchors result to broken links (which of course would be pretty inconvenient for your visitors). There are certain characters like %, &, ?, spaces, and other more special characters which are read differently on URLs which should be encoded first before passing it. While of course, urldecode() does the opposite. It decodes encoded URLs and reads them back on how they should be read.

6. trim()

Though this one’s not as important as the other mentioned functions, but this would definitely help in idiot-proofing. You know, some users may be too idiot to follow certain instructions that leading and tailing spaces are not accepted but still they submit their inputs with these. It would rather lead to flaws and unexpected results, so better trim out those spaces first before validating strings.

7. strip_tags()

Most web programmers just take this function for granted, but by the time their website layouts would act strange and get mixed up, they’ll start investigating and end up never knowing HOW. It’s because without strip_tags() just means your website will definitely become very very prone to hacks. A simple example would be the insertion of a <strong style="font-size:100px;"> string.

8. htmlentities()

My favorite of ‘em all. Nearly most of my PHP echoes come along with this (unless especially not needed). This encodes special characters into HTML readable characters like < (less than) to &gt; and " (quote) to &quot; This is very important when printing values for HTML tag attributes, since you would no longer need to bother for misprinting strings.

These are just pieces of advises and functions I recommend you mustn’t miss to consider. Mark them "strictly for security purposes", and everything will run as smoothly as a web should be. emoticon

-->

April 24, 2009

AJAX - Encoding special characters

Category: Programming » Web

The data that needs to be passed when using the POST method in AJAX must be properly encoded, especially if it contains special characters which are out of the standard ASCII range. Javascript provides 3 encoding functions which may be used for this case: escape(); encodeURI(); and encodeURIComponent(); But these functions have certain limitations, and these limitations are discussed here: Comparing escape(), encodeURI(), and encodeURIComponent()

I often use AJAX in most of my web projects and because of a certain need that I have to allow special characters to be passed, I found a suitable function which will effectively encode most characters:

  function urlencode(url){
      var SAFECHARS = "0123456789" + // Numeric
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
      "abcdefghijklmnopqrstuvwxyz" +
      "-_.!~*’()";                   // RFC2396 Mark characters
      var HEX = "0123456789ABCDEF";
        var spec = new Array();
   
        spec["8364"] = 132; spec["8218"] = 133; spec["402"] = 134; spec["8222"] = 135;
        spec["8230"] = 136; spec["8224"] = 137; spec["8225"] = 138; spec["710"] = 139;
        spec["8240"] = 140; spec["352"] = 141; spec["8249"] = 142; spec["338"] = 143;
        spec["381"] = 144; spec["8216"] = 145; spec["8217"] = 146; spec["8220"] = 147;
        spec["8221"] = 148; spec["8226"] = 149; spec["8211"] = 150; spec["8212"] = 151;
        spec["732"] = 152; spec["8482"] = 153; spec["353"] = 154; spec["8250"] = 155;
        spec["339"] = 156; spec["382"] = 157; spec["376"] = 158;
   
      var plaintext = url;
      var encoded = "";
      for (var i = 0; i < plaintext.length; i++ ) {
      var ch = plaintext.charAt(i);
      if (ch == " ") {
          encoded += "+"; // x-www-urlencoded, rather than %20
      } else if (SAFECHARS.indexOf(ch) != -1) {
          encoded += ch;
      } else {
          var charCode = ch.charCodeAt(0);
          if (charCode > 255) {
              encoded += "%";
              encoded += HEX.charAt((spec[charCode.toString()] >> 4) & 0xF);
              encoded += HEX.charAt(spec[charCode.toString()] & 0xF);
          } else {
              encoded += "%";
              encoded += HEX.charAt((charCode >> 4) & 0xF);
              encoded += HEX.charAt(charCode & 0xF);
              }
          }
      }
      return encoded;
  }

I got this function from Mabaloo.com but I’ve improved a bit of it just for it to support some characters out of the standard ASCII range.

-->

October 22, 2008

Why I’m using AJAX

Category: Programming

AJAX or Asynchronous JavaScript and XML simply provide these cool benefits:

  1. No-Refresh dynamic web page. This resembles a desktop application wherein you don’t have to wait for page loads when you need to retrieve some data or even files. Basically, this saves time especially when users aren’t that patient enough.
  2. Saves bandwidth for websites. Since AJAX can request a response (usually a text response) from a server using the xmlHTTPRequest Object, it may be specially designed to retrieve only a small amount of data, and this very much lessens the size it needs to burn some bandwidth. The retrieved text may be used to dynamically modify any HTML tag or in any way you’d want it to behave with the help of lots of JavaScript capabilities.
  3. We’re already in the 21st Century. We have to say bye bye from the old static web pages and make use of this new technology before it’ll be overridden with much more awesome web features.
  4. Finally, we can make use of this for any website, as long as browsers used in the client side support JavaScript and xmlHTTPRequest. Just like this example below: Check it out!

-->

September 10, 2008

Google’s favorite word

Category: Web

Speed is probably Google’s most favorite word. As I noticed, their applications, websites, mail provider, and even their newest browser, the Google Chrome, carefully takes consideration on how fast the performance of each. One simple proof is their most popular search engine homepage: www.Google.com. Try to check out this page and take a look of its source code by right clicking on it and select "View Page Source" or the like. You’ll notice that the code for that certain page and even the pages for the search results are not written and formatted line by line in a readable manner. I believe that this has nothing to do with enhancing security but most probably, this is designed intentionally to optimize speed.

How then does writing it that way improves speed? There’s just one simple explanation: white spaces (which includes spaces, tabs, and line breaks; except for string constants and separators for keywords and tags) are ignored by internet browsers upon reading HTML codes, but still consume memory spaces with 1 byte per character. Remember that HTML codes are sent from web servers byte per byte to client applications such as internet browsers. So, even those unnecessary white spaces consume time upon transfer. Simply, they still burn some bandwidth, and in order to take care of these, they just have to be removed.

Fact: Line breaks have 2 characters each: the character with ASCII value of 10; and with ASCII value of 13. This means, per line break consumes 2 bytes. Imagine if you have a well formatted HTML page with 100 lines of code, even excluding those tabs and spaces, then it has just unnecessarily consumed 200 bytes of memory. If there are about 1 million users requesting for the same page in one second, then that website has just wasted 200 million bytes of memory using up bandwidth. That is more than 190 Mb per instance.

Now you won’t wonder why Google tops among all of the current search engines. emoticon

-->

May 15, 2008

Secret ascii codes

Category: Programming

I have a cool trick to send out secret codes using ASCII characters. It just popped out my mind when I thought of making myself a VB application to quickly encode text to ASCII codes, and decode ASCII codes to text. Download this application here, and use it to extract the code below:

80 108 101 97 115 101 32 108 101 97 118 101 32 115 111 109 101 32 99 111 109 109 101 110 116 115 46 46 32 58 68

So, what did you find out?

By the way, here’s a screen shot of the program.

Ascii Encoder 

82 101 103 97 114 100 115 44
82 111 110 97 108 100 32 66 111 114 108 97

-->

February 24, 2008

The Magic Square

Category: Programming

On a perfect square number grid, when all the numbers are summed up vertically, horizontally and diagonally, wherein each sum are of the same value, then it is said to be a "Magic Square". For instance, on a 3 x 3 number grid, an example of a Magic Square would be:

8 1 6
3 5 7
4 9 2

In this case, when you add numbers vertically (8 + 3 + 4), the sum is 15. Same as when you add other vertical numbers (1 + 5 + 9) is still 15. Also when you add numbers horizontally (8 + 1 + 6) is 15. The same answer would be when you add them diagonally (4 + 5 + 6).

A magic square can be solved with the requirement: The number of squared grids must be an odd number. Though there was an amazing magic square having a 4 x 4 grid, but common magic squares have grids with odd numbers. In this article, I have included a C++ algorithm to solve for the Magic Square of a certain odd number. Here’s how:


#include <iostream>
#include <conio.h>

using namespace std;

int coor[99][99];

int callFunc(int sides, int toPrint)
{
    int x, y, sum = 0;
    for (y = 1; y <= sides; y++)
    {
        if (toPrint){ cout<<endl; }
        for (x = 1; x <= sides; x++)
        {
            if (toPrint){
                cout<<coor[x][y]<<"\t"; }
            else {
                coor[x][y] = 0; }
        }
        sum += coor[1][y];
    }
    return sum;
}

void MagicSquare(int sides, int xIndex, int yIndex, int val)
{
    if (val > sides * sides){ return; }
    if (xIndex == 0 && yIndex == 0)
    { xIndex = sides / 2 + 1; yIndex = 1; }
    if (xIndex > sides){ xIndex = 1; }
    if (yIndex <= 0){ yIndex = sides; }
    if (coor[xIndex][yIndex] != 0)
    { xIndex–; yIndex += 2; }
    if (coor[xIndex][yIndex] == 0)
    { coor[xIndex][yIndex] = val; }
    if (xIndex == sides && yIndex == 1)
    { yIndex++; coor[xIndex][yIndex] = ++val; }
    MagicSquare(sides, xIndex + 1, yIndex - 1, val + 1);
}

main()
{
    int n, sum = 0;
    system("cls");
    cout<<"Enter grid size : ";
    cin>>n;
    if (n > 99 || n < 1){ return main(); }
    if (n % 2 == 0){
        cout<<endl<<"Invalid! Number must be odd!"; }
    else {
        int loc[n][n];
        callFunc(n, 0);
        MagicSquare(n, 0, 0, 1);
        sum = callFunc(n, 1); }
    cout<<endl<<endl<<n<<" x "<<n<<" Magic Square"<<endl<<"Sum Value = "<<sum;
    cout<<endl<<endl<<"Press ‘Esc’ to exit…";
    if (getch() != 27){ return main(); }
}


 

Magic Square

This is just a simple Magic Square solution following a simple rule. If you wish to find out what rules to follow to solve for this, understand the algorithm on your own. I made it specially for you to understand it much easier. Clue: By looking at the grids at varied number of squared grids, you may notice a pattern of the order of numbers. Happy solving! emoticon

-->

January 24, 2008

List all Prime Factors

Category: Programming

Here’s my recursive solution in VB for listing all prime factors of a certain number in sorted manner.


Private Function ListPrimeFactors(nNum As Long, _
                                  Optional cSep As String = " ", _
                                  Optional cFact As Long = 2, _
                                  Optional mStr As String) As String
Dim mBound As Long
If cFact < nNum Then
    If nNum Mod cFact = 0 And Not (cFact = 1) Then
        mStr = mStr & CStr(cFact) & cSep
        ListPrimeFactors = ListPrimeFactors(nNum / cFact, cSep, cFact, mStr)
    Else
       
        ListPrimeFactors = ListPrimeFactors(nNum, cSep, cFact + 1, mStr)
    End If
Else
    If nNum Mod cFact = 0 Then
        mStr = mStr & CStr(cFact) & cSep
    End If
    ListPrimeFactors = Left$(mStr, Len(mStr) - Len(cSep))
End If
End Function


The function will return the listed prime factors in a string. The first parameter input is the number to base the prime factors, second parameter is the string to separate the listed prime factors. The third and fourth parameters are not necessary.

Example of use:


MsgBox ListPrimeFactors(InputBox("Enter number"), "x")


With this statement, an input box will appear and asks for a number to base the list of its prime factors. After entering the number, a message box will show to you the result or the list of prime factors.

Feel free to make use! (^^,) Just give me some credits though.

-->

January 12, 2008

Trellian Webpage

Category: Programming

"Wonderful! This is the Ultimate Webpage Editor I would ever need!" emoticon

I was searching for a WYSIWYG webpage editor in the internet when I saw Trellian Webpage meeting my standards for high quality softwares. If you want to create webpages with full designs just in minutes, then trust me, this is the best Webpage Editor you’d ever want to use. Why? Simply because:

  1. It’s completely got the What-You-See-Is-What-You-Get (WYSIWYG) features.
  2. Easy to understand text editor, with almost all the functionalities of an HTML page.
  3. Quick inserting of different objects such as Image, Links and even Javascript Form Objects (Buttons, Radio Buttons, Check Boxes, Text Field, Dropdown Boxes, and etc.) plus Javascript Applets, Embedded Plugins and Active-X Controls.
  4. Quick access to Editor’s tab, Source, and Page Preview.
  5. Comes up with a built-in GIF Animator / Editor plus Image Editor.
  6. Lots of available useful tools.
  7. Contains Search Engine Optimizer (SEO) easy application tools.
  8. Gives you access about references for CSS.
  9. Has HTML syntax checking tools.
  10. Easy website publishing.
  11. A webpage grabber / importer from an address specified in the internet.
  12. Installer’s just 7.76 Mb in size.
  13. Most of all, it’s completely FREE!!!

Mind you, this is the best I’ve ever seen! You’ve got to try this out! If you wish to download this software right away, just click on this link, http://www.trellian.com/webpage/download.htm, follow the proper procedures and begin to create webpages. emoticon

-->

January 8, 2008

Understanding Recursion

Category: Programming

A recursive function is a loop-like block of code in a program wherein this certain function calls on itself to perform a specific task and is rather harder to understand than those of an iterative function. As an introduction to recursion, the example below shows the simplest form of a recursive algorithm.

Using C++… (Bloodshed’s Dev-Cpp)


int num = 0;

main()
{
    cout<<num<<" ";
    num++;
    getch();
    return main();
}


As you notice, in the above code, the main() function calls on itself in the later part right before the end bracket of the function. Try to code this in C++, don’t forget to include iostream and conio.h, this would result into a never-ending running application wherein this program will print an ascending number starting from 0, increment the value of num, waits for a user key input, prints the new number, increment the value of num, wait for another user key input and so on, and so forth.

Well of course, this example already explains recursion, but, take note that it is not the usual application of a useful recursive algorithm. If you think just by understanding the example above, you’ve already understood the whole idea of recursion, then think again. Have you heard of the "quick sort algorithm", or "binary search tree algorithm", or perhaps, "towers of hanoi"? These problems are made out of recursion. But take note of this, as a programmer, I strongly believe that for every recursive function, there is always an iterative equivalent and is much faster but harder and longer to write. In the programming world, one would always face the dilemma between speed and maintainability of codes. I’d like to stress, for complex algorithms, recursion is often much more maintainable but slower in performance, while iteration produces faster performance but much more difficult to maintain. Simply because, recursion may already result into a desired function but would only be written in only a small amount of lines of codes, while an iterative equivalent would most likely should be written in fewer lines. So, if ever you’d like to decide to write a recursive function than an iteration, you should be able to understand first how recursion works.

Programmers have been explaining, for every recursive function call (the part or the line where the function calls on itself), whatever the result of that certain call is independent from the current procedure itself. Which means, there just came a chance wherein a function which produces a specific task is also in need of the result of the very same function itself.

For example, a function has a specific task, wherein it splits a string into an array of string. Somewhere inside the function, by chance, it would also need a function which performs splitting of a string into an array of string. So, rather than calling another foreign function to do the job, it would just necessarily call itself instead since the purpose of this function is to split a string into an array of string. Got the idea?

Before, I had a hard time understanding recursion, not until I learned Binary Tree, specifically the Binary Search Tree (BST). Since I can explain BST better for recursion, then let’s understand BST first.

BST is the special technique used by programmers to quickly search for a certain item inside a list of data. Of course, for manageability purposes, a list of data inside a Binary Tree must be arranged in a sorted manner. So later, it won’t be hard to search for an item. Here’s where a BST comes in. Suppose we have a list of 1 million items, considering the data are already sorted, would you search for a certain item by starting from the very beginning or from the end? Suppose you’d start from the first item, what if the actual location of the searched item is just 5 items from the end list? Or if you’d start from the end, and the actual location is at the 6th Rank? Mind you, it would take the program to iterate almost a million times just to search for that certain data, which would rather result into a very slow performance.

To eliminate this undesirable result, programmers created a faster way to search using a recursive algorithm most commonly known as the "divide and conquer algorithm". Introducing, Binary Search Tree: BST starts it’s search from the midpoint of a list of items. The midpoint can be calculated by adding the value of the starting index to the value of the ending index divided by 2 [ in the form ((LowerBound + UpperBound) / 2) ]. For example we are searching number 40 in the list below…

1 3 4 5 8 9 13 14 18 19 20 26 35 36 40 41 45

In the list of numbers above, we assume that the LowerBound index is 0, and the UpperBound index is 16. So we find the midpoint by adding 0 and 16, since there are 17 items in the list, divide by 2. The midpoint is 8, which is the item "18" (Take note that the list starts at index 0, so index 8 should be at the 9th item). Then following the BST rule, we would check if the midpoint is the number we are searching for. If it is the right number then return the number, if not, then we continue the searching process.

Now what do we do after we found out that the midpoint is not yet the number we are looking for? We will now divide the task. Since we know that the list is sorted, have you noticed that all numbers to left of the midpoint are actually numbers less than this midpoint. And all numbers to its right are greater. We would then again want to search for the right number by taking all the numbers to the left as a new list of numbers, and the numbers to the right as another list of numbers. Find each midpoint, divide again the list into two until the midpoint is exactly the number we are looking for. This is where the recursive function is used. Since our function’s purpose is to check whether the midpoint of the list is the number we are searching for, and we came to a point wherein we need a certain function to search for the midpoint of a list and check whether this is the number we are searching for, we will then call the function itself.

1 3 4 5 8 9 13 14 18 19 20 26 35 36 40 41 45

Notice above, the numbers in red becomes the new list of numbers wherein we’d search again for the midpoint and check whether this midpoint is the number we are looking for, and same for those new list in blue. And the current midpoint, which is "18", won’t be used anymore as part in the new list to be searched. Therefore, the new list would be…

1 3 4 5 8 9 13 14 … We find the midpoint using the same formula as mentioned above…

and…

19 20 26 35 36 40 41 45 … Find also the midpoint and check if it’s the number we are looking for…

If the midpoint for each list is once again found, and it showed that the midpoint is not the number we are looking for, repeat the process of dividing the list into 2 until we find the number we are searching for.

Have you tried to visualize what the output would be? I hope this is a better way of explaining recursion. Just remember, upon handling recursive functions, you must consider 3 things: First, how would you begin the recursion. Second, what are the contents of the function. Lastly, what could trigger for the function to end. Search for different examples of recursion. You would notice a starting statement on an "If… If Else" Learn why it should appear. But just a clue, this "If statement" handles the recursion on when it should end its process.

I have written a function in Visual Basic which draws a "Crack-Like Image" on a Picture Box, rather useful as a tool for an Image Editor Application. If you are a VB Programmer, try to download my submission on PSCode right in this link… Paint Tool - Using Recursive Algorithm.

-->

Hand Tools Set (Demo)

Category: Programming

I’m working on an interesting VB Program. It may be categorized as Entertainment plus Educational, and Personal. Anyway, here’s a screenshot of this Demo…

 Hand Tools (Demo)

The actual application has a "Close Application" option. Click on this label then you it will be properly closed. Please do not close by ending the process through the task manager. The mouse cursor might disappear, thus you would need to restart your PC. Please use with extra care… LOL.

This is purely Visual Basic. Comments and suggestions are accepted… (^^,) 

Download the (.zip) file in this link… Hand Tools (Demo) 

Unzip the file and Run "Hand Tools (Demo).exe" to open Demo application.

In case there are errors about missing components,  download the OCX’s here… RegOCX. Then unzip the file, and run "Setup.bat".

P.S.: Don’t ask who’s hand is being used… emoticon Thanks!!

Special thanks to LaVolpe, contributor to the PSCode community.

-->

December 6, 2007

The “Bool Fool” arithmetic

Category: Programming

Bool fool arithmetic
The above equation is puzzling… And it tries to imply, that this equation is true. But of course, it does not follow the usual decimal system. It is through the application of a Boolean arithmetic. That instead of a series of numbers given, from 0 to 9, it uses only binary digits, which means, possible numbers could only be either 1 (true) or 0 (false).

Boolean logic is one of the most important factors in Programming. It follows the same idea as with a circuit of an electrical device. Most usually, it serves as a condition for a lot of programming statements. It can be combined with another condition through a set of operators, and, or, xor, and the inverter, not. (inverter yields an opposite value of a number being inverted. E.g.: not true yields a value of false, since false is the invert or opposite of true)

Suppose, the statement in the image: "study physics" has a value of true, "fail" has a value of false, while "no" is the inverter not. Let’s show it in a much more precise manner, why the heck it becomes so confusing…

true = not false

not true = false

true + not true = not false + false

…then combining like terms

true ( not + 1 ) = false ( not + 1 )

…since "not + 1" appears on both side of the equation, it is possible to eliminate it by dividing both sides of the equation by "not + 1".

( true ( not + 1 ) ) / ( not + 1 ) = ( false ( not + 1 ) ) / ( not + 1 )

…when "not + 1" has been eliminated,  what remains is…

true = false

Anyway, if you think it’s a pain in the neck, then don’t think about it anymore. emoticon But, I tell you, if you’d try to absorb this equation, you might… fail.

-->

November 27, 2007

A Complete Programming Source

Category: Programming

There are already a number of websites available when in terms of programming source code needs… But among of the few, what I can say, "It stands out" is PSCode.com.

For about 10 different programming languages, programmers from different places all around the world share their ideas about programming in a single website… Name them all: from the hardest-to-understand source codes down to the beginner-level programs are posted in this site…

If you are a programmer, who might be in need of ideas about programming, or rather, skilled enough to share your knowledge, register now at PSCode and be one of us… And you’ll find out what more you can do in the world of programming. emoticon

-->





















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham