chandrasekhar.co.uk
Independant Software Consultant & Business Owner
  HOME
  EXPERIENCE SUMMARY
King's College, London
Framestore CFC
Alt N Solutions
Bits Infotech
B2B Software
Singapore Computers
  EXPERTISE SUMMARY
  EDUCATION SUMMARY
  CODE BASE
PHP Code Base
Java Code Base
.NET code Base
Database Code Base
Linux/Windows Code Base
  CONTACT DETAILS
 

Valid HTML 4.01 Transitional

Valid CSS!

View Chandrasekhar Yeddanapudi's profile on LinkedIn

PHP Code Base
Some cool stuff which I find useful
PHP HTTP authentication example

Let us look at some sample code for a page that may only be viewed if the user enters username 'myuser' and password 'mypass':
if ($PHP_AUTH_USER != 'mysuser' 
or $PHP_AUTH_PW != 'mypass'): 
// Bad or no username/password. 
// Send HTTP 401 error to make the 
// browser prompt the user. 
header("WWW-Authenticate: " . 
"Basic realm=\'Protected Page: " . 
"Enter your username and password " . 
"for access.\''); 
header('HTTP/1.0 401 Unauthorized'); 
// Display message if user cancels dialog 

<H1>Authorization Failed</H1> 
<P>Without a valid username and password, 
access to this page cannot be granted. 
Please click 'reload' and enter a 
username and password when prompted. 
</P> 
else:
...page contents here...

Javascript blocking keypresses for certain characters
http://javascript.internet.com/forms/block-press-script.html

(not sure if the numbers bit works on Safari)
Putting quote marks or apostrophes in input boxes or javascript
Firstly, make sure the string with the quotes or apostrophes is enclosed in double-quotes, not apostrophes. Not sure why this should make a difference but it does. This applies whether the string is going into a javascript variable or the value attribute of an input element. The quotes and apostrophes should then be replaced by their html codes (ampersand followed by by a code). The php function htmlentities does this nicely.
PHP console output codes
Clear the screen:

print("x0C")

Clear the current line:

print("x0D");

Backspace:

print("x08");

More codes here:

http://thalia.spec.gmu.edu/~pparis/classes/notes_101/node24.html
PHP POST through proxy
function post_through_proxy($url, $payload, $proxyhost="proxy.admin.local", $proxyport=8001) {

          $errno="";
          $errstr="";
          $file = fsockopen($proxyhost, $proxyport, &$errno, &$errstr, 30);

          if(!$file) {

               // Failed to open connection to proxy - exit:
               return false;

          } else {

               // Define the max number of bytes to fread at once:
               $fread_max = 4096;

               // Successfully opened connection to proxy, attempt to post data:
               $headers = "POST $url HTTP/1.1\r\n";
               $headers .= "Content-type: application/x-www-form-urlencoded\r\n";
               $headers .= "Content-Length: ".strlen($payload)."\r\n\r\n";
               $headers .= $payload;
               fputs($file, $headers);

               // Get small chunks of reponse until we know the content length:
               $response = "";
               whi
le(!stristr($response, "Content-Length:")) $response .= fread($file, 20);
               $response .= fread($file, 20);

               // Look for Content-length:
               $content_length = substr($response, strpos($response, "Content-Length: ")+16);
               $content_length = substr($content_length, 0, strpos($content_length, "\n"));
               $content_length = (double)$content_length;

               // Get small chunks of response until we get to the content:
               while(!stristr($response, "\r\n\r\n")) $response .= fread($file, 1);

               // Get the content:
               $content = "";
               for($i=0; $i
Javascript form.submit() method doesn't work
If you have a form with a submit button called 'submit', any calls to the form's submit() function will not work (you will get the error message "this object does not support this property or method". So just make sure never to call a submit button 'submit'.
JavaScript atoi / string to integer
Use eval():

var number_five = eval("5");
XSLT xsl:for-each and xsl:if
Link:
http://www.zvon.org/xxl/XSLTutorial/Books/Output/example20_ch7.html

The XSLT stylesheet uses the 'xsl:for-each' loop to go through each service. Within each service, the 'selected' field is checked to see if it equals 1 using the 'xsl:if'.

Source XML:

<services>
     <service>
          <contact_ref>43885</contact_ref>
          <service_ref>6</service_ref>
          <uber_group_ref>35</uber_group_ref>
          <entity />
          <elevel>0</elevel>
          <selected>0</selected>
          <description>AdSearch Client Administrator</description>
          <service>AdSearch Client Administrator</service>
     </service>
     <service>
          <contact_ref>43885</contact_ref>
          <service_ref>13</service_ref>
          <uber_group_ref>35</u
ber_group_ref>
          <entity />
          <elevel>0</elevel>
          <selected>1</selected>
          <description>AdSearch Free High Quality Previews</description>
          <service>AdSearch Free High Quality Previews</service>
     </service>
</services>

XLST stylesheet:

<xsl:template match="services">
     <service_list>
          <xsl:for-each select="service">
               <xsl:if test="selected = 1">
                    <service_ref>
                         <xsl:value-of select="service_ref" />
                    </service_ref>
               </xsl:if>
          </xsl:for-each>
     </service_list>
</xsl:template>

Output:

<services>
     <service_ref>13</service_ref>      
</services>
JavaScript variable scope
Variables declared outside any function are global.

Variable declared inside a function but without the 'var' keyword, are also global! So be particularly aware of variables such as loop counters etc - they must be declared in advance using 'var' otherwise you will get into a mess.

Javascript functions always take arguments passed by value, EXCEPT arrays and objects, which are always passed by reference.
Regular expressions:
From: http://www.phpbuilder.com/columns/dario19990616.php3

     First of all, let's take a look at two special symbols: '^' and '$'. What they do is                     indicate the start and the end of a string, respectively, like this:

     "^The": matches any string that starts with "The";
     "of despair$": matches a string that ends in the substring "of despair";
     "^abc$": a string that starts and ends with "abc" -- that could only be "abc" itself!
     "notice": a string that has the text "notice" in it.

     There are also the symbols '*', '+', and '?', which denote the number of times a character
     or a sequence of characters may occur. What they mean is: "zero or more", "one or more",
     and "zero or one." Here are some examples:

     "ab*": matches a string that has an a followed by zero or more b's ("a", "ab", "abbb", etc.);
     
"ab+": same, but there's at least one b ("ab", "abbb", etc.);
     "ab?": there might be a b or not;
     "a?b+$": a possible a followed by one or more b's ending a string.

     You can also use bounds, which come inside braces and indicate ranges in the number of occurences:

"ab{2}": matches a string that has an a followed by exactly two b's ("abb");
"ab{2,}": there are at least two b's ("abb", "abbbb", etc.);
"ab{3,5}": from three to five b's ("abbb", "abbbb", or "abbbbb").
Note that you must always specify the first number of a range (i.e, "{0,2}", not "{,2}"). Also, as you might have noticed, the symbols '*', '+', and '?' have the same effect as using the bounds "{0,}", "{1,}", and "{0,1}", respectively.

Now, to quantify a sequence of characters, put them inside parentheses:

"a(bc)*": matches a string that has an a followed by zero or more copies of the sequence "bc";
"a(bc){
1,5}": one through five copies of "bc."
There's also the '|' symbol, which works as an OR operator:

"hi|hello": matches a string that has either "hi" or "hello" in it;
"(b|cd)ef": a string that has either "bef" or "cdef";
"(a|b)*c": a string that has a sequence of alternating a's and b's ending in a c;
A period ('.') stands for any single character:

"a.[0-9]": matches a string that has an a followed by one character and a digit;
"^.{3}$": a string with exactly 3 characters.
Bracket expressions specify which characters are allowed in a single position of a string:

"[ab]": matches a string that has either an a or a b (that's the same as "a|b");
"[a-d]": a string that has lowercase letters 'a' through 'd' (that's equal to "a|b|c|d" and even "[abcd]");
"^[a-zA-Z]": a string that starts with a letter;
"[0-9]%": a string that has a single digit before a percent sign;
",
[a-zA-Z0-9]$": a string that ends in a comma followed by an alphanumeric character.
You can also list which characters you DON'T want -- just use a '^' as the first symbol in a bracket expression (i.e., "%[^a-zA-Z]%" matches a string with a character that is not a letter between two percent signs).

In order to be taken literally, you must escape the characters "^.[$()|*+?{" with a backslash (''), as they have special meaning. On top of that, you must escape the backslash character itself in PHP3 strings, so, for instance, the regular expression "($|¥)[0-9]+" would have the function call: ereg("(\$|¥)[0-9]+", $str) (what string does that validate?)

Just don't forget that bracket expressions are an exception to that rule--inside them, all special characters, including the backslash (''), lose their special powers (i.e., "[*+?{}.]" matches exactly any of the characters inside the brackets). And, as the regex man pages tell us:
"To include a literal ']' in the list, make it the first character (following a possible '^'). To include a literal '-', make it the first or last character, or the second endpoint of a range."

For completeness, I should mention that there are also collating sequences, character classes, and equivalence classes. I won't be getting into details on those, as they won't be necessary for what we'll need further down this article. You should refer to the regex man pages for more information.
PHP/HTTP prevent caching:
Used this to stop the images in the StoryBoards flash anim from being cached:

     header("Expires: Sat, 1 Jan 2000 00:00:00 GMT");
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Cache-Control: no-store, no-cache, must-revalidate");
     header("Cache-Control: post-check=0, pre-check=0", false);
     header("Pragma: no-cache");

The Cache-Contol command is used with HTTP/1.1, and the Pragma command is used for HTTP/1.0.
PHP & Cookies
Althouth the docs say that most of the parameters to setcookie are optional, I have only got
     it to work by using all the parametes, like this:

          setcookie("name_of_cookie","value",time()+(60*60*24*30),"/","",0)

     To delete cookies, set them in exactly the same way (even the time), but set the value to "":

          setcookie("name_of_cookie","",time()+(60*60*24*30),"/","",0)

     Also, remember that there can be newline characters within the tags before header
     operations (such as cookie operations), but there can be no newlines (or any output) outside of
     the php tags, cos such output is then part of the hmtl, and therefore sent to the browser as
     soon as the server comes across it.
XHTML html, body and table height control:
Note that the tag's 'height' attribute has been depreciated, so we now have to use:

html, body, .content { height: 100%; }
This text appears in the middle
Apache, nslookup
Apache by default does not look up the remote host name, because this requires an nslookup to be performed, and this will slow things down a lot if a lot of requests are being made to the server. The lookup can be turned on in the httpd.conf file by setting
     HostnameLookups On
This will result in the CGI HTTP_REMOTE_HOST variable being set.
In PHP you can get the host name from the IP address with gethostfromaddr() and vice versa with gethostfromname().
PHP outputting JPEGs
When JPEGS (maybe other image files) are outputted using PHP to send the raw data in HTTP headers, sometimes when you save the .jpg it wont be a completely valid .jpg file, but it can still be read by ACDSee. Photoshop wouldn't open the invalid files and niether would Flash. ACDsee can be used to do a batch conversion to quickly make all the files valid jpegs.
Last Updated Jul 2010