Saturday, October 22, 2011

Simple PHP demo for file uploading

Uploading of files can be very useful from time to time. This time round, I am going to show you how to upload a file into the server using PHP.

This demo will start from a simple html file.
<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

And a simple PHP file that will handle all the uploading...
<?php

//Maximum filesize that can be uploaded through this file
$filesize = 1000;
//The folder that all the uploads will be place in
$folderName = "uploads/";

// detect slash/backslash nomenclature dirname
$path = dirname( __FILE__ );
$slash = '/'; strpos( $path, $slash ) ? '' : $slash = '\\';
define( 'BASE_DIR', $path . "/" );
$dirPath = BASE_DIR . $folderName;   // folder path
//If the filesize of the file is smaller than the maximum filesize
if ($_FILES["file"]["size"] < $filesize)
{
 //If there is an error
 if ($_FILES["file"]["error"] > 0)
 {
  echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
 }else{
  //Display more info about the uploaded file
  echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  echo "Type: " . $_FILES["file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
  //If the folder hasn't been created yet, create it now
  if(!is_dir($dirPath))
   mkdir($dirPath,0777);
  //If the file already exist
  if (file_exists($dirPath . $_FILES["file"]["name"]))
  {
   echo $_FILES["file"]["name"]." file exist". "<br />";
  }else{
   //Copy the uploaded file into the specified folder
   move_uploaded_file($_FILES["file"]["tmp_name"],
   $dirPath . $_FILES["file"]["name"]);
   echo "Stored in: " . $dirPath . $_FILES["file"]["name"]. "<br />";
  }
  echo "The URL of the file would be:<a href='";
  echo removeFileName(). $folderName . $_FILES["file"]["name"]."'>here</a>";
 }
}else{
 echo "Invalid file";
}

//Function to get the url of the current page
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":";
  $pageURL .= $_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

//Function to get the url of the current page and remove the filename of this page
function removeFileName(){
 $pageURL = curPageURL();
 $pieces = explode("/", $pageURL);
 $piecesLength = count($pieces);
 $pageURL = "";
 for ( $counter = 0; $counter < ($piecesLength - 1); $counter ++) {
  $pageURL = $pageURL. $pieces[$counter]."/";
 }
 return $pageURL;
}
?>
... okay the file isn't so easy after all...

Some additional Notes:
  • Remember to set the write permission into the folder that you have placed the php files
  • My example currently only allows files that are lesser than 1000 bytes, but you can change the maximum file size by increasing it in the php file.


* Click here to view the demo of this example:
^ Click here for the source files of this demo.

Saturday, October 15, 2011

A paradise for Geeks?

Sim Lim Square would probably be the best place to source for all the computer parts and accessories that a Geek would need. Besides for all the computer related products, they also have 3 levels of shops selling all sorts of electronic products ranging from tv to music/video players to cameras, you can find all these electronics products in one building. Isn't that convenient?

Pictures of Sim Lim Square.


Some info:
  • Try to ask around for the price of the same product first before making an purchase
  • Try not to go there as an individual (Chances that you get con can be pretty high, unless you know the shop owners pretty well)
  • Sometimes, Cash payment can help you to get more discounts

* Click here for the website of 'Sim Lim Square'.
^ Click here for the location of 'Sim Lim Square'.

Friday, October 14, 2011

Playing with LinkList (2)

I had introduced the use of LinkList in my previous post. So what can you do with a LinkList? And how can it help you?

Let us take a look at a simple example.
If you are staying in a house with many rooms and each room have a few cupboards or shelves fully occupied with books, you probably will have a list like the following.
Click here for the list.

I have created a simple flex application to sort all the data in a orderly manner.
Buy let us take a look at some parts of the codes first.

On top of the CustomLinkList class that I had introduced in the previous post, I had build a room class on top of the CustomLinkList class.
package List
{
 public class RoomsList extends CustomLinkList
 {
  public function RoomsList()
  {
   super();
  }
  
  //Override the add Value function in the CustomLinkList class
  override public function addValue(tempValue:*):void{
   var newNode:Node = new RoomNode(tempValue);
   var baseNode:Node = head;
   var tempNode:Node;
   if(baseNode == null){
    head = newNode;
   }else{
    var hasCheck:Boolean = false;
    while(hasCheck == false){
     //While moving from one node to the next,
     //do a comparison between the nodes
     //and find the best place to place the new node
     if(compareRoomName(baseNode, newNode)){
      hasCheck = true;
      if(baseNode.prev == null){
       head = newNode;
      }
      tempNode = baseNode.prev;
      if(tempNode != null){
       tempNode.next = newNode;
      }
      newNode.prev = baseNode.prev;
      newNode.next = baseNode;
      baseNode.prev = newNode;
     }else{
      if(baseNode.next == null){
       baseNode.next = newNode;
       newNode.prev = baseNode;
       hasCheck = true;
      }else{
       baseNode = baseNode.next;
      }
     }
    }
   }
   count ++;
  }
  
  //Function to compare 2 node and if the new node that was pass into
  //this function had a smaller value, it will return true, else false 
  //We are going to sort the room by their room_name value
  public function compareRoomName(tempNode1:Node, tempNode2:Node):Boolean{
   var name1:String = String(tempNode1.value.room_name).toLowerCase();
   var name2:String = String(tempNode2.value.room_name).toLowerCase();
   var tempArray:Array = new Array();
   tempArray.push(name1);
   tempArray.push(name2);
   tempArray.sort();
   if(name2 == tempArray[0]){
    return true;
   }else{
    return false;
   }
   return false;
  }
 }
}

And a RoomNode class that builds on top of the Node class.
package List
{
 public class RoomNode extends Node
 {
  private var shelvesList:ShelvesList = new ShelvesList();
  //After passing in the value of this node for room,
  //Pass in all the relevant data for creating the 
  //respective shelves
  public function RoomNode(tempValue:*):void {
   // constructor code
   super(tempValue);
   for(var i:int = 0; i < this.value.shelfs.shelf.length(); i ++){
    shelvesList.addValue(this.value.shelfs.shelf[i]);
   }
  }
  
  public function get roomContents():ShelvesList{
   return shelvesList;
  }
 }
}
And this would be my main application class.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute"
    width="100%"
    height="100%"
     creationComplete="creationCompleteHandler(event)">
 <mx:Style>
  VBox{
   paddingTop:5;
   paddingBottom:5;
   paddingLeft:5;
   paddingRight:5;
  }
 </mx:Style>
 <mx:Script>
  <![CDATA[
   import List.*;
   
   import mx.events.FlexEvent;
   
   //Embed a xml file that contents data
   [Embed(source="xml/booksData.xml")]
   private var dataXml:Class;
   
   //Create a list for rooms
   private var tempRoomList:RoomsList = new RoomsList();
   
   protected function creationCompleteHandler(event:FlexEvent):void{
    var strOutput:String = "";
    var tempDataXML:XML = dataXml.data as XML;
    //Pass all the data into the list for rooms
    for(var i:int = 0; i < tempDataXML.room.length(); i ++){
     tempRoomList.addValue(tempDataXML.room[i]);
    }
    var roomObject:RoomNode;
    var shelfObject:ShelfNode;
    //Display all the contents in the list for rooms
    for(i = 0; i < tempRoomList.length(); i ++){
     roomObject = tempRoomList.getNodeAt(i);
     strOutput += "Room Name = " + 
      String(roomObject.value.room_name);
     strOutput += "\n";
     for(var j:int = 0; j < roomObject.roomContents.length(); j ++){
      shelfObject = roomObject.roomContents.getNodeAt(j);
      strOutput += "-> Shelf Name = " + 
       String(shelfObject.value.shelf_name);
      strOutput += "\n";
      for(var k:int = 0; k < shelfObject.shelfContents.length(); k ++){
       strOutput += "   -> Book Title = " + 
        String(shelfObject.shelfContents.getNodeAt(k).value.book_title);
       strOutput += ", Written By " + 
        String(shelfObject.shelfContents.getNodeAt(k).value.author);
       strOutput += "\n";
      }
     }
    }
    txtMessage.text = strOutput;
   }
   
  ]]>
 </mx:Script>
 <mx:VBox width="100%" height="100%">
  <mx:TextArea id="txtMessage" width="100%" height="100%"/>
 </mx:VBox> 
</mx:Application>
* Click here to view the demo in this post.
^ Click here for the source files of the demo
` Click here to follow the other post on LinkList.

Sunday, October 9, 2011

Playing with LinkList

In most of the older Programming language that I had used before or played before requires the developer to enter a value for the number of items that you are going to store in a Array. This can be quite a nuisance sometimes, but luckily there is something known as a Link List in the programming world. :D With the help of a Link List, it had definitely solved a lot of length issues in various Programming Language.

This is a simple example that I had created for Flex but the classes were also usable in Flash Professional Projects.
This is the source file for the main Application - LinkList.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" width="100%" height="100%"
    creationComplete="creationCompleteHandler(event)">
 <mx:Style>
  VBox{
   paddingTop:5;
   paddingBottom:5;
   paddingLeft:5;
   paddingRight:5;
  }
 </mx:Style>
 <mx:Script>
  <![CDATA[
   import List.*;
   
   import mx.events.FlexEvent;
   
   private var tempObject:Object = {x:100,y:100};
   private var dataArray:Array = new Array("Data",12345,3.14,tempObject);
   
   private var tempList:CustomLinkList = new CustomLinkList();
   
   protected function creationCompleteHandler(event:FlexEvent):void
   {
    var strOutput:String = "";
    //Adding values to the List
    for(var i:int = 0; i < dataArray.length; i ++)
    {
     tempList.addValue(dataArray[i]);
    }
    strOutput = "Show Contents of List";
    strOutput += "\nList has " + tempList.length() + " items.";
    strOutput += "\n";
    //Display the objects in the List
    for(i = 0; i < tempList.length(); i ++)
    {
     strOutput += String(tempList.getValueAt(i)) + " ";
    }
    strOutput += "\nRemove Item number 3";
    //Method to remove an object of a particular position
    strOutput += "\n" + String(tempList.removeValueAt(2)) +
     " have been removed.";
    strOutput += "\nShow Contents of List Again";
    strOutput += "\nList has " + tempList.length() + " items.";
    strOutput += "\n";
    //Display the objects in the List
    for(i = 0; i < tempList.length(); i ++)
    {
     strOutput += String(tempList.getValueAt(i)) + " ";
    }
    strOutput += "\nRemove All Items";
    while(tempList.length() != 0)
    {
     strOutput += "\n" + String(tempList.removeValueAt(0)) +
      " have been removed.";
    }
    strOutput += "\nShow Contents of List Again";
    strOutput += "\nList has " + tempList.length() + " items.";
    strOutput += "\n";
    for(i = 0; i < tempList.length(); i ++)
    {
     strOutput += String(tempList.getValueAt(i)) + " ";
    }
    txtMessage.text = strOutput;
   }
   
  ]]>
 </mx:Script>
 <mx:VBox width="100%" height="100%">
  <mx:TextArea id="txtMessage" width="100%" height="100%"/>
 </mx:VBox> 
</mx:Application>

This is a basic Link List class that I had written
package List{
 public class CustomLinkList {
  private var _head:Node;
  private var _count:int;
  public function CustomLinkList() {
   // constructor code
   head = null;
   count = 0;
  }
  
  //count = number of items Getters and Setters
  protected function get count():int
  {
   return _count;
  }

  protected function set count(value:int):void
  {
   _count = value;
  }

  //Start of the Node
  protected function get head():Node
  {
   return _head;
  }

  protected function set head(value:Node):void
  {
   _head = value;
  }

  //Creating and adding a new Node
  //And connect the 2 way Link List properly
  public function addValue(tempValue:*):void{
   var newNode:Node = new Node(tempValue);
   var currNode:Node = head;
   if(currNode == null){
    head = newNode;
   }else{
    while(currNode.next != null){
     currNode = currNode.next;
    }
    currNode.next = newNode;
    newNode.prev = currNode;
   }
   count ++;
  }
  
  //Removing a node and returning 
  //the value of the Node at the same time
  //And connect the 2 way Link List properly
  public function removeValueAt(tempInt:int):*
  {
   var i:int = 0;
   var currNode:Node = head;
   if(tempInt < count)
   {
    var nextNode:Node;
    var prevNode:Node;
    while(i != tempInt){
     currNode = currNode.next;
     i ++;
    }
    if(currNode)
    {
     nextNode = currNode.next;
     prevNode = currNode.prev;
     if(nextNode)
      nextNode.prev = prevNode;
     if(prevNode)
      prevNode.next = nextNode;
     if(currNode == head)
     {
      head = nextNode;
     }
    }
    if(count > 0)
     count --;
    return currNode.value;
   }else{
    return null;
   }
  }
  
  //Get the value of a Node of a particular position
  public function getValueAt(tempInt:int):*{
   var i:int = 0;
   var currNode:Node = head;
   if(tempInt < count)
   {
    while(i != tempInt){
     currNode = currNode.next;
     i ++;
    }
    return currNode.value;
   }else{
    return null;
   }
  }
  
  //Returns the length of the LinkList
  public function length():int{
   return count;
  }
 }
}
This is a simple Node class
package List{
 public class Node {
  protected var _value:* = null;
  protected var _next:Node;
  protected var _prev:Node;
  public function Node(tempValue:*) {
   // constructor code
   _value = tempValue;
   _next = null;
   _prev = null;
  }
  
  //Previous Node Getters and Setters
  public function get prev():Node
  {
   return _prev;
  }

  public function set prev(value:Node):void
  {
   _prev = value;
  }
  
  //Next Node Getters and Setters
  public function get next():Node
  {
   return _next;
  }

  public function set next(value:Node):void
  {
   _next = value;
  }
  
  //Previous Content of the Node
  public function set value(tempValue:*):void{
   _value = tempValue;
  }
  
  public function get value():*{
   return _value;
  }
 }
}
* Click here to view the demo in this post. ^ Click here for the source files of the demo

Sunday, October 2, 2011

One of Windows OS missing component - Partitioning Your Hard Disk

Being a Windows user for more than 10 years, I have encounter numerous situations where I have bought a PC or Laptop from a Vendor and there was only one partition in the System. As I have been using Windows XP since a few years ago, I would use 'Partition Magic' to solve all these partition issues. Especially when the default Windows Disk Management Utility was pretty slow and step intensive. (Especially, when a user was required to sit in front of the monitor to wait for the completion of one step before he can move on and select the next step...) As for Partition Magic, an user can create a series of task and let them run at one go. Isn't it useful?


But with the discontinuation of supplying the number of updates to 'Partition Magic' and the uprising of Windows Vista and Windows 7, an user cannot use 'Partition Magic' any more, which is kinda sad. :(

Although, its pretty sad that we cannot use 'Partition Magic' any more, there seems to be some other potential alternatives to 'Partition Magic'.
For Example:

Image taken from Arconis Website
Click the above image or here to access the website of Acronis Disk Manager.


Image taken from Aomei Website
Click the above image or here to access the website of Aomei Partition Assistant.

* Click here to find out more about 'Partition Magic'

Sunday, September 25, 2011

Flash/Flex: Changing the colors of the hyperlinks of a body text

I had figured out a simple solution for changing the colors of your hyperlinks in a body text a few weeks ago. Hence I decided to share it in the post. On top of that, the demos that I had shown in this post also demonstrate the use of the TextEvent.LINK Event which can be very useful also. :D

Here's a simple AS3 Actionscript Class file that contains a simple Stylesheet for setting the properties of the default and the hover state of the hyperlinks. I have created this file so that I can reuse it in Flex and Flash.

package
{
 import flash.text.StyleSheet;

 public class SimpleStylingClass
 {
  private var _ss:StyleSheet = new StyleSheet();
  
  public function get ss():StyleSheet
  {
   return _ss;
  }
  
  public function set ss(value:StyleSheet):void
  {
   _ss = value;
  }
  
  public function SimpleStylingClass()
  {
   var aHover:Object = new Object();
   aHover.color = '#FF0000';
   aHover.fontWeight = 'bold';
   aHover.textDecoration = 'none';
   
   var aNorm:Object = new Object();
   aNorm.color = '#0000FF';
   aNorm.textDecoration = 'underline';
   
   ss.setStyle("a", aNorm);
   ss.setStyle("a:hover", aHover);
  }

 }
}

The following would be the source file for the flex file.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" width="100%" height="100%" >
 <mx:Style>
  HBox{
   paddingLeft: 10;
   paddingRight:10;
   paddingTop:10;
   paddingBottom:10;
  }
 </mx:Style>
 <mx:Script>
  <![CDATA[
   import mx.events.FlexEvent;
   import mx.controls.Alert;
   
   //Bindable String to be used by the text area below.
   [Bindable]
   private var _bodyText:String = "I have some body text here. It " +
    "contains a few clickable URLs. For example: <a href='" +
    "event:http://www.google.com' target='_blank'>Google.com" +
    "</a>, <a href='event:http://www.msn.com' " +
    "target='_blank'>msn.com</a> and <a target='_blank' " +
    "href='http://nekyouto-tech.blogspot.com'>My Tech Blog</a>.";
   
   /*
    When the user clicks on such a link (href='event:...', 
    I will show a Alert box indicating the URL that the 
    user have click and a simple message.
   */
   protected function txtAreaBody_linkHandler(event:TextEvent):void
   {
    // TODO Auto-generated method stub
    Alert.show(event.text + " have been block by this site"
     , "Alert",Alert.OK);
   }
   
  ]]>
 </mx:Script>
 <mx:HBox width="100%" height="100%">
  <!-- 
   I have pointed the htmlText value to the Bindable String in the 
   above.I have also added the Stylesheet for the text area and 
   also theListener for hyperlinks in the body text. It will keep 
   a lookout for href='event:..... pattern in a hyperlink text. 
  -->
  <mx:TextArea id="txtAreaBody" width="100%" height="100%" 
      htmlText="{_bodyText}" link="txtAreaBody_linkHandler(event)"
      styleSheet="{new SimpleStylingClass().ss}" fontSize="24" />
 </mx:HBox>
</mx:Application>


And the following would be the main class for the Flash file
package
{
 import flash.display.Sprite;
 import flash.events.TextEvent;
 import flash.text.TextField;
 import flash.external.ExternalInterface;
 
 public class StylingHyperlinksMainClass extends Sprite
 {
  //Text to be displayed in the textfield
  private var _bodyText:String = "I have some body text here. It " +
   "contains a few clickable URLs. For example: Google.com" +
   ", " +
   "msn.com and My Tech Blog.";
  private var _txtBodyText:TextField;
  
  public function StylingHyperlinksMainClass()
  {
   super();
   _txtBodyText = this.getChildByName("txtBodyText") as TextField;
   _txtBodyText.htmlText = _bodyText;
   //Setting the stylesheet of the Textfield
   _txtBodyText.styleSheet = new SimpleStylingClass().ss;
   //Adding the listener for href that starts with event:...
   _txtBodyText.addEventListener(TextEvent.LINK, textLinkEvent);
  }
  
  /*
  Shows a Javascript Alert box when the user clicks on the
  URL that starts with event:...
  */
  private function textLinkEvent(event:TextEvent):void
  {
   ExternalInterface.call("alert", event.text + " have been block" +
    " by this site.");
  }
 }
}

* Click here to view the Flex demo.
# Click here to view the Flash demo.
^ Click here to download the source file of the above demos.

Sunday, September 18, 2011

A work around for the Blogger Images Overlay and your Lightbox Overlay

As I have just started creating my Blogs a few months ago and I was putting a lot of effort creating and updating it... Something crazy had happened suddenly...


Image shows a mixture of Blogger Image Overlay and Spicebox Overlay...

In order to stop the above from happening any further, I have done the following steps:
  1. In your Blogger dashboard click Design > Edit Html
  2. Find the keyword Spicebox and replace it with something else in the code of your blogs and you are done.

But I do hope that Blogger will provide an option so that I can turn the current black overlay for images and have my Overlay effect back again.

* Click here for the Spicebox overlay effect for Blogger.