Friday, December 26, 2008

Auto-Grow Textarea - doing it the easy way in Javascript

Just earlier on, I was working on a project for a friend of mine. The project was a php website that includes shopping cart, and some other modules. Well, lately i'm very into facebook and I was fascinated by their auto-growing text boxes. So i googled and found some javascript code snippets too.

However, these scripts either require jQuery javascript framework or use time intervals (window.setInterval) to check for the height. These techniques made it look very ugly: and high resource usage too.

Here, by combining String Object match method and textarea's onkeydown event, I can do it neatly in one line.

<textarea onkeypress="var m = this.value.match(/\n/g); if(m!=null) {this.rows = (m.length+1);}else{this.rows = 2;}"></textarea>

Upon each key press, the javascript code will check for the number of newline characters in the text area value. If there's no match, it will set to the default.

See, it's better than installing jQuery framework just to do this auto-grow textarea! and you can do it selectively too!

Edit:
To apply this to all textarea DOM object, you can use jQuery to do so.
<script type="text/javascript">/* <![CDATA[ */ $(document).ready(function(){$("textarea").keypress(function(e){var m = this.value.match(/\n/g); if(m!=null) {this.rows = (m.length+1);}else{this.rows = 2;}});});/* ]]> */</script>

The code will work no matter where you place in the body, because the applying of keypress binding will only start when the whole document is loaded. Hope the new code helps!

Friday, November 28, 2008

PHP Loop Benchmarking - WHILE vs FOR

I was very bored today, when I suddenly realised that I should do some benchmarking for PHP myself. I created a script (can be found at thephpcode pastebin: http://thephpcode.pastebin.com/f80e53fe) and run it on my xampp localhost.

In the php benchmarking script, i am comparing 3 loops: FOR, WHILE and FOREACH. Amazingly, but not surprising, WHILE loop is the fastest compared to FOR and FOREACH, and as expected FOREACH is the slowest.

This is my output:
0.000854015350342 seconds
// for the FOR loop with 10000 times
0.000696897506714 seconds
// for the WHILE loop with 10000 times
10000 elements
// the number of elements in the array
0.00111794471741 seconds
// for the FOREACH loop with 10000 times


I read about the WHILE loop on Javascript that WHILE is faster than FOR, but I didn't know that the same thing applies in PHP too. Well, here's a learning point for all of us.

Note that the timings taken are an average of 5 runs spreaded across 5 mins (i.e. 1 run per minute) for the most accurate timings. Please note that the timings may differ from computer to computer. I am using Intel QuadCore 2.4GHz, 4GB RAM, Windows XP SP3, XAMPP 1.7.1, PHP 5.2.9.

Sunday, November 23, 2008

Multiple Pages with one PHP file

OMG.. i am so sorry for the delay. i was seriously slow and lazy as promised. well, today i am going to talk about having multiple pages with only one php files.

many PHP noobs, they create one small module with tons and tons of pages. that's really bad because you duplicate loads and loads of the same thing! This is made possible using the system-defined variable $_GET, which returns all $_GET variable .. eg index.php?a=b to get the value 'b' you can use $_GET['a'].

what you can do is to combine these pages into one php files. this makes things easy as you are able to backup less files: instead of hundreds of files.

Previously you can have:
+ index.php
+ postback.php
+ about.php
+ process.php

now you can have:
+ index.php
+ index.php?p=pb
+ index.php?p=a
+ index.php?p=prc

Simply in index.php you just have to use IF ELSE statements, or use any other conditional statements.

index.php:
<?php

if($_GET['p']=='pb'){
// display page for postback
}elseif($_GET['p']=='a'){
// for about page
}elseif($_GET['p']=='prc'){
// for processing
}else{
// displaying main page...
}

?>


This is simple and easy. If you have common template for all the pages, you can combine and put them before or after the IF conditions. Most client browsers identify different GET headers as different pages, so it doesn't affect much of your application.

Wednesday, October 15, 2008

Taking a Break...

Hello all php geeks C=

i am taking a 4 week break, for my national exams are going on.
During this period of time i won't be posting any updates on PHP.

However, you still can comment on my blog or ask me questions on php.
<?php
while($thephpcode == true){
if($need_break){
break;
}
}
?>

Cheers
Sam Yong
thephpdeveloper

Wednesday, September 17, 2008

$_REQUEST Security Problem

hello all! it has been quite some time. i have been studying for my national examinations. oh well, today i am going to talk about security issues in PHP regarding the $_REQUEST variable.

The $_REQUEST variable is a combination of key and values of $_POST, $_GET and $_COOKIE variables. This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script.

The problem with this variable, is that when you are using it, you never know where the value came from. It might come from a cookie, it might come from a GET header request, or even a POST data.

This often allows hijacking of sessions to occur.
1) Hackers gets the Session ID of the user, visitor, or worse of all: Administrators.
2) They inject into the cookies to get into the session of the user/administrator.
3) this allows the server to show the hijacker what the real user sees.
4) and the hijacker is also able to access whatever the user is able to access.

Worse still, if you want to double check the session via a POST and GET, and you use the $_REQUEST variable to check, the hacker can simply put it into cookie and he passes through.

It also allows bots to POST data easily using cookies if you use $_REQUEST. Especially if you have forms using $_REQUEST, the bot can keep bypassing your form using cookies or get headers.

You should use a more specific variable to further secure your application. Well, that's all i have. Goodnights!

Wednesday, September 10, 2008

Script Bundle

I have recently started building a php scripts bundle for sales. The bundle includes

  • Password and String Encryption Class - pcrypt
    A class that helps you to encode a string with a password and a random salt. The same password is required to decode the encrypted string. useful for storing data that requires password encryption. it offers common hashing methods: SHA1, MD5 and CRC32.

  • Hypertext Markup Language PHP Builder Class - htmlbuilder
    Using this class, you can build XHTML and HTML valid web pages with php codes. it uses object-based codes and you can nest objects in objects with class parent-children relations.

  • Javascript in HTML Optimizer Control Class - scriptcontrol
    Puts all the codes in javascripts tags into a file and call from there. this allow optimized loading and thus decreasing server load.

  • Script and File Pre-Processor - sp
    Pre-process your xml, javascript and css files with this processor. it is not a class, instead, you can call it directly. Also, instead of calling individual files, you can combine many files into one: eg sp.php?f=file1.css;file2.css;file4.css

  • Alternative Logging - altlog
    a great logging tool that allows error logging to be managed easy via a class. commonly used by the rest of the scripts for error logging.

  • PHP Cache Control - cachec
    Allows you to cache variables, data so as to speed up page loading. it saves cache into files in a directory and will load it later for faster loading.



Would you want to buy it? Comment your thoughts.

Saturday, August 30, 2008

Pastebin Integration

Hello all!

i am proud to announce that in future, a copy of code examples will also be on Pastebin at http://thephpcode.pastebin.com/. This will allow all to post your source codes up there and discuss it here on thephpcode.blogspot.com.

This also means that, you can see the codes clearly and find help directly when you click from the functions in the source code. and with the added usefulness of line numbers, you can look at the code clearly.

hope it helps all.

cheers
sam

Tuesday, August 12, 2008

Getting a recursive file list in PHP: Code Example

Ever wonder how you can get an array of files in a directory. ALL the files, including those in the subfolders? Sure you can do that! an example is shown below! The function below returns an array tree of files. It recursively get files in a folder, then calls itself again for all the sub folders.

function dirfiles($dirname = '.', $relative = false) {
if($dirname == ''){$dirname = '.';}
if (!is_dir($dirname) || !is_readable($dirname)) {
// check whether the directory is valid.
return false;
}

$a = array();

$handle = opendir($dirname);
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_readable($dirname . DIRECTORY_SEPARATOR . $file)) {
if (is_dir($dirname . DIRECTORY_SEPARATOR . $file)) {
$a[($relative ? $file : $dirname . DIRECTORY_SEPARATOR . $file)] = dirfiles($dirname . DIRECTORY_SEPARATOR . $file, $relative);
}else{
$a[] = ($relative ? $file : $dirname . DIRECTORY_SEPARATOR . $file);
}
}
}
closedir($handle);

return $a;
}


You can specify whether to return each array in an relative manner or not.

$relative = true:
Array
(
[data] => Array
(
[0] => dataone.inc.php
[1] => user.inc.php
[2] => forum.inc.php
)

[0] => constants.inc.php
[1] => functions.inc.php
[2] => header.inc.php
)


$relative = false:

Array
(
[dat/inc/data] => Array
(
[0] => dat/inc/datadataone.inc.php
[1] => dat/inc/datauser.inc.php
[2] => dat/inc/dataforum.inc.php
)

[0] => dat/inc/constants.inc.php
[1] => dat/inc/functions.inc.php
[2] => dat/inc/header.inc.php
)

For ($relative = true), the presentation would be nicer, however in ($relative = false), the array would be more useful for argument of another file access function.

hope it is useful ^^

Link to code example on pastebin: http://thephpcode.pastebin.com/f495b59a1

Sunday, August 3, 2008

Why JSON over XML in AJAX?

Many web applications nowadays use AJAX to help them in decreasing server load and of course speed up the website. AJAX have been part of the web 2.0 technologies and is used widely in many websites.

AJAX have this idea of calling back the server from the client side to accomplish some task, such as posting back data to the server or getting new information from the server. it can been seen as form submitter, tips of the day ticker, tabbed boxes and more.

However, developers have the choice of language of the message that is responded from the server after the postback or request have been made by AJAX from client side. It can either be in the form of Javascript Object Notation (JSON) or Extensible Markup Language (XML).

JSON generally have advantages over XML - firstly because JSON is much lightweight compared to XML. As JSON only contains one character notations, it saves more bandwidth and load time compared to XML which uses tags.

Secondly, the multiple-dimension JSON is also attractive to developers, as JSON's parsing on PHP is easy, with only 2 functions, whereas XML uses multiple functions to parse - which may be confusing.

Thirdly, JSON is directly readable on client side using Javascript, thus you save time parsing it on server AND client side. For XML, you will need to parse the data again in order to use it.

To use JSON directly in Javascript: var myObject = eval('(' + myJSONtext + ')');

For course, the X in AJAX originally refers to XML - asynchronous JavaScript and XML - but as time goes by, developers will find satisfying format for their needs of communication between server and client. Even in ASP.net, AJAX messages in Updatepanels and other controls are split using "|".

Thursday, July 31, 2008

Setting read-only variables of PHP classes

Many would ask, how can I make variables of PHP classes read only? There's nothing similar to other programming languages such as C# to use the readonly keyword.

Oh well, there is a work around instead. For example, in the class pClass, there is this variable named $read i want to make read-only. So i will have to do this:


<?php

class pClass{

private $read = '';

public function __get($name){ // this will be called when a variable is read.
return $this->$name; // returns the variable
// without this function, PHP will return an error.
}

}

?>


Note that by setting this function, all private variables in your class are readable. However, you still can filter them in the __get function before returning the result..

Note that the function have 2 underscores, not one.

Adding class instances to Array()

I was coding a script halfway, when i ran into this case that i had never encounter before: adding class instances into arrays. I asked myself, was that possible? Well, the answer will reveal below.

<?php

class pClass{

public $_array = array();

public function display(){
print_r($this->_array);
}

}

$p = new pClass();
$second = new pClass();
$p->_array[] = $second;
// IT IS POSSIBLE! xD
$p->display(); // outputs: Array ( [0] => pClass Object ( [_array] => Array ( ) ) )
// how cool.

?>


Fortunately, i tested and it works. I added a class instance to the array of another class. On top of that, the both can be instances of the same class. Well, this allows parent-children relationships of classes.

In addition, this will allow recursive addition of class, since it is a class in a class. Well, why not?

Adding class instances to array would mean that multiple instances can also be added to one class, via this method too!

Sunday, July 20, 2008

MySQL Query from PHP

i was coordinating with my external project's Facebook App programmer, when i realised that i haven't write an article on how to query using MySQL from PHP. it's simple. so let's get the steps right.

First of all, you will need to connect to your MySQL server first before you can query. this is to verify that the user you are querying with have authorisation to access certain features of MySQL, such as limited table/database privileges.

$link = @mysql_connect(%server%,%user%,%password%);
- $link contains the information of the connection that you have made and might be required by other mysql_* functions. it becomes false when the mysql_connect returns error as false.
- %server% is the server address, and most probably local MySQL server should be "localhost"
- %user% is the user name of the account used to access MySQL on %server%
- %password% confirms the identity.

Only when connected, MySQL then can be accessed using the other functions, such as mysql_select_db(), mysql_query(), mysql_fetch_array(). Now, you will need to select a specific database to work in.

$return = @mysql_select_db(%database%);
- $return returns the value true or false. False on failure.
- %database% is the name of the database without ` warp.

If both functions are a success, then you are able to use mysql_query() to query and get results from the database specified in mysql_select_db().

$result = @mysql_query(%query%);
- $result is the data that is returned from %query% [WARNING: $result is not an array, it just contains data for other functions to process]. it returns false on error.
- %query% is the fully query string. See MySQL query syntax at http://dev.mysql.com/doc/

Since the $result of the mysql_query function is not an array or object, or anything that PHP can read properly into variables, you will need to use functions like mysql_fetch_array() or mysql_ fetch_ assoc().

To read off all the rows of the result, do a while loop.

$table = array();
while($array = @mysql_fetch_array($result)){
$table[] = $array;
}


when mysql_fetch_array() reaches no more result, it will return a false, and thus breaking the loop. $table will be an array of rows of the result returned, where $result is the variable returned by mysql_query().

After you have gotten the results in an array, you can free the $result variable as it might occupy the system memory. To free the result, use mysql_free_result().

@mysql_free_result($result);
- $result is the variable that is returned by mysql_query. function does nothing if variable is false.

When you are done with everything on MySQL, you can use mysql_close() to close the connection. Connection is automatically closed when the script terminates.

@mysql_close([$link]);
- where $link is the connection information returned by mysql_connect(). function closes last opened connection if $link is not specified.

Saturday, June 28, 2008

PHP Session functions and notes

like any other web server-side scripts, PHP has its Session functions and methods. Every time a user opens your website, you consider it a session and when the user is inactive for sometime, the session is gone.

Also, when you want to pass parameters from one page to another, you might notice normal variables will not stay when loaded another page. However, you can declare (array)$_SESSION variables to keep the variables in the session and you can use it on any other page.

The only condition is that, you must start the session using function void session_start(void) at the start of PHP scripts that you want to use Session.

When your domain (eg http://www.johnsmith.com/) uses subdomain (eg http://sub.johnsmith.com/), using the normal session_start() is not enough. The session from your domain will be different from your sub domain.

So, you can add the following in front of session_start() to configure this: session_set_cookie_params(t, '/',dn,false,true); - where t represents the timeout before the session expires, '/' represents that the session can be used from the whole domain, and dn should be a .<yourdomainname>.com where you add a . in front of your domain name without the "www"

Also, during my own testing experience, i noticed that if you put localhost in the "dn", the session will not work on any browsers and PHP will keep renewing the session, which may result in undesirable returns.

Tuesday, June 17, 2008

PHP script include() function

One of the things I regard best as a developer, is the include() function of PHP.

include() is something like the MasterPages and ContentPages in ASP.NET. You can use it for defining site-wide variables and constants, defining functions and classes, or even putting site-wide processes and functions into it and call it from anywhere else.

For example, i need to display "hello world" on both "a.php" and "b.php" pages. I can use the include() function to do this. first, i put
<?php echo "hello world"; ?>
into "head.php", then i put
<?php include('head.php'); ?>
into both pages "a.php" and "b.php". Then, both pages "a.php" and "b.php" will show up "hello world".

both pages will run "head.php" at the line where include() function is. However, there are some unexpected results of using include().

For example, i put "head.php" into a folder call "folder", and i have this script "call.php" which have the following
<?php include('folder/head.php'); ?>
The current directory for "head.php" is no longer 'folder/', but it is now '/', since it is called by "call.php". Included scripts will always use the current directory of the parent script. (See more: Directory Functions and chdir() function)

The return statement can be used in the main scope of included scripts to return the control back to the parent script immediately. example:
<?php return; $I++; ?>
variable $I will not be incremented. but if you run this code as parent main scope, return will not work.

Wednesday, June 4, 2008

Upgrading MySQL - with xampp installed first

Hello all!

We have noted that the internet requires an article on how to upgrade your MySQL server with xampp installed first. MySQL server on your computer are be shared among many HTTP servers - Apache or IIS - on the same operating system. Thus, there are possibilities you might want to upgrade or downgrade your MySQL server.

xampp by Apache Friends is a package that includes the Apache server, PHP and MySQL together with many other wonderful functions for local web development(localhost). However, the MySQL server included is never up to date. So below is how you upgrade your MySQL server.

1) Download MySQL server from http://dev.mysql.com/downloads/
2) When you set up MySQL server, one of the steps of the installer should show an "Advanced" button, click on it.
3) Following you should see where the server is about to install to. Change it to %your_xampp_installation_path%\mysql\ (e.g. C:\xampp\mysql\)
4) After installation, your MySQL is upgraded.

Note that if you do not change the installation directory of MySQL server, the server will not be upgraded as the default server is still in your xampp folder. After upgrading, you can use MySQL Administrator (GUI Tools) or MyPHPAdmin to check the server version.

Note that you are advised to back up your database information before performing such upgrade or maintenance work. I will not be held responsible for any problems caused directly or indirectly by my articles or whatsoever.

Directory Size Calculations with Code Examples

Calculating files are easy. Using the php filesize() function, you can easily find out the file size. However, have you encountered a case whereby you need to calculate the whole directory, including sub folders and the files in them?

In this article, we are going to talk about how to recursively calculate the total folder size of a directory. You can add thousands of folders and millions of files into a single folder, and this customized php function is able to calculate out the size of the directory. You can also use it for calculating your disk space too!

function dirsize($dirname) {
if (!is_dir($dirname) || !is_readable($dirname)) {
// check whether the directory is valid.
return false;
}

$dirname_stack[] = $dirname;
$size = 0;

do {
$dirname = array_shift($dirname_stack);
$handle = opendir($dirname);
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_readable($dirname . DIRECTORY_SEPARATOR . $file)) {
if (is_dir($dirname . DIRECTORY_SEPARATOR . $file)) {
$dirname_stack[] = $dirname . DIRECTORY_SEPARATOR . $file;
}
$size += filesize($dirname . DIRECTORY_SEPARATOR . $file);
}
}
closedir($handle);
} while (count($dirname_stack) > 0);

return $size;
}


Hope this helps you in building it in as a useful function in your administration panel of your website.

Link to code example on pastebin: http://thephpcode.pastebin.com/f24c2ec13
http://thephpcode.pastebin.com/f24c2ec13

Friday, May 23, 2008

PHP IDE choosing guide

There are plenty of Integrated Development Environment (IDE) - softwares or hardwares that form up the environment for the development of softwares or other hardwares - created for the programming of PHP codes.

Some of them include Dev-PHP, Aptana Studio, Adobe Dreamweaver and more.. But what is the best for you, since PHP is such a dynamic and complex language?

There are a few pointers you should consider before using that IDE of your choice.
1) Patches and security fixes to the software - are they kept up to date with the latest version of PHP?
2) Does it allow you to integrate PHP with other platforms such as AJAX and XML?
3) Are the code correctly colored?
4) Are the tools available with the packages useful?
5) Are the tools available easy to use?
6) Is it free for use/production?

Those pointers are just some guide to choosing your default IDE. Of course, you can combine them and use multiple IDE on one single project. It's good that you experiment out the available IDEs and find the one that suits you best.

Cheers
Sam Yong

NEXT UP: Directory Size Calculations

Friday, May 9, 2008

Setting up XAMPP - local php environment

Hello to all!

Today we are going to talk about how to set up a local PHP testing environment on your own computer using the server localhost or 127.0.0.1. It is understood that PHP is installed on a server in order to parse PHP files and output into the browser, but how are you going to do that on your own computer where you have so many things running about?

Well, we'll use xampp, by Apache Friends, which is an apache package with MySQL community version, PHP, FTP support, and more. It supports many platforms: Windows, Mac, Linux, Solaris and more!

What's more? xampp is free!

Installing xampp will take awhile after you have selected the appropriate download for your platform. After installing, you will be able to access the server using http://localhost/, or add the port number if you use it, on your browser.

You will need to remember that other people that can connect to you can access your apache server using your IP address. You will need to set some of the security options available on the server mainpage.

To edit the files on the server, either you can use the ftp protocol, or you can access it via your local hard drive (for example on Windows, htdocs folder inside where xampp is installed).

And if you want to upgrade MySQL, just the version of MySQL from the official website, and install into where xampp is installed.

Well, signing off.
Sam Yong

NEXT UP: PHP IDE choosing guide

Tuesday, May 6, 2008

thephpcode - opening

hello all.

i am sam yong, thephpdeveloper blogger, and i am 15 this year, yes going 16. i currently live in singapore, and i have 2 years, maybe a little more, of PHP and programming logic experience. I have opened and work in quite a number of companies, but now i am here to share my experience with you.

here in this blog, i am sharing php codes and functions together with its explanations. you might find them useful, find bugs in them or you might just love the way i do the codes. but i am willing to learn PHP with you.

if you are a beginner in PHP, i suggest that you read my next post, on how to set up a PHP server environment on your own computer and you can learn PHP without the use of purchased servers.

also, i hand-code all my codes, and they are not going to be formatted. you can format them in your own IDE (Integrated Development Environment) so that you can read them.

Cheers
Sam Yong

NEXT UP: Setting up XAMPP - local php environment