Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, April 25, 2014

HTML: Post your data into a popup window

Rather than posting the data to a new page, you might need have to post the data to a popup. Therefore, this would help you to get a rough idea on how to do that. (Things get pretty interesting when you learn new stuff everyday. :D)

Source code of the main html file - index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Form</title>
<script language="javascript" type="text/javascript">
  function submitForm(formName){
 var popupWin = window.open("",formName,"status,height=540,width=500,resizable=yes,scrollbars=yes");
 popupWin.focus();
  }
</script>
</head>
<body>
<form action="formResults.php" method="post" name="myForm" target="popupWin" onsubmit="javascript:submitForm(this.target);">
Name:<br /><input name="name" type="text" size="50" maxlength="50" /><br />
Address:<br /><input name="address" type="text" size="50"/><br />
<input name="submit" type="submit" value="Submit the form data to a popup"/>
</form>
</body>
</html>

Here's the simple form that I would be posting the data to - formResults.php
Your name is: 
<br />
<?php
  echo $_REQUEST["name"]
?>
<br />
<br />
Your address is: 
<br />
<?php
  echo $_REQUEST["address"]
?>
* Click here for the demo shown in this post.

Sunday, October 14, 2012

Playing with open source web stuff

Probably around 8 or 9 years ago, ever since I knew about the existence of an open source server side scripting language (PHP), I would spend a bit of time playing with it whenever I'm free. But I still remember how annoying it was if you are trying to setup a web server environment on your local machine. You need to find separate installers for Apache, PHP, mySQL, etc... Just by finding all these installers and downloading all of them can be pretty annoying. Luckily...

We have such tools that will help us to reduce all the crazy installation issues. Introducing...

'WampServer'
Taken from the website, 'WampServer' is a Windows web development environment.
It allows you to create web applications with Apache2, PHP and a MySQL database.
Alongside, PhpMyAdmin allows you to manage easily your database.
Congratulations, upon a successful installation of 'WampServer', you can skip
the step of downloading and installing the individual applications. Isn't that great?


'MAMP'
As for 'MAMP', which is pretty much similar to 'WampServer' except for the fact
that it is meant for 'Mac' Users only. I was using this application when I was
using a 'Mac' computer in the office back then. The performance of this app
is pretty good and it's pretty useful too.

While browsing through the web, it seems that Linux have it's own set of applications that can accomplish the task of installing and configuring an open source web development environment for Apache, MySQL and PHP too. But you probably need to spend some time searching. (I have never used Linux before therefore...)

* Click here to find out more about 'WampServer'.
^ Click here to find out more about 'MAMP'

Thursday, June 28, 2012

PHP: Playing with a simple form

I was trying to come up with a solution to minimise the number of php files needed to manipulate and submit the form data and this is the solution that I have come up with. :D (Though it can be done using 3 php files but too many files lah...)

form.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<?
 $hasPostData = "false";
 $name = "";
 $address = "";
 $info = "";
 //Check if this php file has receive any form data
 //through POST method.
 if(isset($_POST["form_name"]))
 {
  $hasPostData = "true";
  $name = $_POST["form_name"];
  $address = $_POST["form_address"];
  $info = $name.$address;
 }
?>
</head>
<body>
<form action="" method="post" name="loginForm">
Name: <input type="text" name="form_name" size="32"/><br />
Address: <input type="text" name="form_address" size="32"/><br />
<input type="submit"/>
</form>
<?
 //If you have submitted some data thru the form, 
 //we need to send the data to the next php file.
 if($hasPostData === "true")
 {
  echo "<form action='nextPage.php' method='post' name='mainLoginForm'>";
  echo "<input type='hidden' name='name' value='". $name ."'/>";
  echo "<input type='hidden' name='address' value='". $address ."'/>";
  echo "<input type='hidden' name='info' value='". $info ."'/>";
  echo "</form>";
  echo "<script type='text/javascript'>";
  echo "function sendFormData(){document.mainLoginForm.submit();}";
  echo "sendFormData();";
        echo "</script>";
 }
?>
</body>
</html>
nextPage.php
<?
 if(isset($_POST["info"]))
 {
  echo $_POST["info"];
 }
?>
* Click here for the demo.
^ Click here for the source files of the demo.

Friday, March 30, 2012

PHP: Creating / Generating XML results

Despite with all the new web technologies around us, I guess that XML is something that wouldn't die out so easily. Especially that its a friendly file type that can be opened by different browsers and softwares. Ex: Mozilla Firefox, Google Chrome, Microsoft Excel, etc... Therefore I'm going to share an example using php that would display the results as a xml data.

But let me show you the codes first.

Here's a simple php file that contains the necessary functions.
<?php
 //Header needed to display content as xml
 header ("Content-Type:text/xml");

 //function to create xml node
 //if $hasIllegalCharacters is true, then we will use CDATA to wrap the node values
 function createNode($nameOfNode, $valueOfNode, $hasIllegalCharacters=true)
 {
  $result = "";
  $result .= "<" . $nameOfNode . ">";
  if($hasIllegalCharacters)
  {
   $result .= "<![CDATA[";
  }
  $result .= $valueOfNode;
  if($hasIllegalCharacters)
  {
   $result .= "]]>";
  }
  $result .= "</" . $nameOfNode . ">";
  return $result;
 }

 //function to save result as xml file
 function createAttachment($filename)
 {
  header('content-disposition: attachment; filename='.$filename.'.xml');
 }
?>

The following would be the source codes of the example
<?php
 //include the xml custon library
 include("php/library/xml/XmlMainClass.php");
  
 //Create the nodes and populate the nodes with data
 $message = createNode("message", 'Meow !@#$%^&*()-=_+{}[]\|:"'.";'<>?,./`~");
 $lat = createNode("lat", "1.281270");
 $lng = createNode("lng", "103.825318");
 $coordinates = createNode("coordinates", $lat . $lng, false);
 $country = createNode("country", "Singapore");
 $street = createNode("street", "Jalan Membina");
 $address = createNode("address", $street . $country . $coordinates, false);
 $dob = createNode("dob", "></></><");
 $age = createNode("age", "28++");
 $name = createNode("name", "nekyouto");
 $profile = createNode("profile", $name.$age.$dob.$address.$message, false);

 //Output the results
 echo $profile;
?>

A similar example to the previous one but this time round rather than displaying the results, it will create a downloadable xml file.
<?php
 //include the xml custon library
 include("php/library/xml/XmlMainClass.php");
  
 //Create the nodes and populate the nodes with data
 $message = createNode("message", "Meow !@#$%^&*()-=_+{}[]\|:\";'<>?,./`~");
 $lat = createNode("lat", "1.281270");
 $lng = createNode("lng", "103.825318");
 $coordinates = createNode("coordinates", $lat . $lng, false);
 $country = createNode("country", "Singapore");
 $street = createNode("street", "Jalan Membina");
 $address = createNode("address", $street . $country . $coordinates, false);
 $dob = createNode("dob", "></></><");
 $age = createNode("age", "28++");
 $name = createNode("name", "nekyouto");
 $profile = createNode("profile", $name.$age.$dob.$address.$message, false);

 createAttachment("profile");
 //Output the results
 echo $profile;
?>

* Click here to view the demo of the first example.
^ Click here to view the demo of the second example.
~ Click here for the source files of this demo.

Wednesday, January 18, 2012

Flash AS3 + PHP: Publishing your flash contents into a PDF file (2)

Last week, I have shown you how to create a downloadable PDF using Flex + PHP + the Alive PDF library. As for this week, I shall move on to the step of printing out & breaking up a big datagrid into multiple pages.

The following would be the source file of my Main Application in Flex.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    creationComplete="creationCompleteHandler(event)">
 <mx:Script>
  <![CDATA[
   //Import the classes that are needed.
   import com.extentPDF.ExtendingPDF;
   
   import mx.collections.ArrayCollection;
   import mx.controls.dataGridClasses.DataGridColumn;
   import mx.events.FlexEvent;
   
   //Array to store the random data that I'm going to create
   private var dataArray:Array = new Array();
   private var dataColArray:ArrayCollection = new ArrayCollection();
   
   //Array to store the column sequence
   private var dgColumns:Array = new Array();
   
   protected function creationCompleteHandler(event:FlexEvent):void
   {
    //Add the respective column names into the array.
    dgColumns.push(new DataGridColumn("Name"));
    dgColumns.push(new DataGridColumn("Description"));
    dgColumns.push(new DataGridColumn("Price"));
    dgColumns.push(new DataGridColumn("Unit"));
    //Set the columns of the datagrid.
    dgDisplay.columns = dgColumns;
    
    //Create random data
    var j:int = 0;
    var tempObject:Object;
    for(var i:int = 1; i <= 100; i ++)
    {
     tempObject = new Object();
     if(i % 2 == 1)
     {
      tempObject.Name = "Item " + i;
     }else{
      tempObject.Name = "Product " + i;
     }
     tempObject.Price = "S$" + i;
     j = Math.round(Math.random() * 100);
     tempObject.Unit = i * j;
     tempObject.Description = "Description " + i;
     dataArray.push(tempObject);
    }
    //Pass the data into the datagrid
    dataColArray.source = dataArray;
    dgDisplay.dataProvider = dataColArray;
   }
   
   //Upon clicking on the button, make a downloadable pdf.
   protected function clickHandler(event:MouseEvent):void
   {
    saveContent();
   }  
   
   //Function that will be creating the downloadable PDF
   //with the help of PHP
   private function saveContent():void
   {
    //Create a new instance of ExtendingPDF class.
    var tempPDF:ExtendingPDF = new ExtendingPDF();
    //Add it to this application.
    this.addChild(tempPDF);
    this.validateNow();
    
    //Specify the first row that you are displaying
    var start:int = 0;
    //Specify the last row that you are displaying
    var end:int = 1;
    //Used to specify the row number of the data
    var row:int = 0;
    //Array to create a reference to the 'dataArray'
    //based on the start and the end
    var dummyArray:Array;
    //Array to store the result of the check upon
    //the PDF
    var checkResult:Array = null;
    //Should be add the last known good view to the PDF? 
    var mustInsertPrev:Boolean = false;
    //Loop through all the rows of the 'dataArray'
    //Add the view into the PDF if the view can fit in
    //else keep on adding a new row until it reach a point
    //where the new row cannot be added and then add the 
    //last known good view into the PDF.
    while(end <= dataArray.length)
    {
     dummyArray = new Array();
     row = 0;
     for(var i:int = start; i < end; i ++)
     {
      dummyArray[row] = dataArray[i];
      row ++;
     }
     dataColArray.source = dummyArray;
     dgDisplay.dataProvider = dataColArray;
     dgDisplay.verticalScrollPolicy = "off";
     dgDisplay.height = dgDisplay.headerHeight +
      dgDisplay.measureHeightOfItems(start, end - start);
     dgDisplay.validateNow();
     mustInsertPrev = false;
     checkResult = tempPDF.checkContentSize2PDFPage(dgDisplay);
     if(checkResult[0] == 1)
     {
      if((start + 1) == end)
      {
       tempPDF.addPage();
       checkResult = tempPDF.checkContentSize2PDFPage(dgDisplay);
       if(checkResult[0] == 0)
       {
        mustInsertPrev = false;
       }else{
        mustInsertPrev = true;
       }
      }else{
       mustInsertPrev = true;
      }
      if(mustInsertPrev)
      {
       end --;
       dummyArray = new Array();
       row = 0;
       for(i = start; i < end; i ++)
       {
        dummyArray[row] = dataArray[i];
        row ++;
       }
       dataColArray.source = dummyArray;
       dgDisplay.dataProvider = dataColArray;
       dgDisplay.verticalScrollPolicy = "off";
       dgDisplay.height = dgDisplay.headerHeight +
        dgDisplay.measureHeightOfItems(start, end - start);
       dgDisplay.validateNow();
       tempPDF.addContent2PDFPage(dgDisplay);
       start = end;
       end ++;
      }
     }else{
      end ++;
      if(end > dataArray.length)
      {
       tempPDF.addContent2PDFPage(dgDisplay);
      }
     }
    }
    //Create the PDF file that can be downloaded
    tempPDF.createContent();
    //Restore everything back to the state before
    //the PDF was created.
    dataColArray.source = dataArray;
    dgDisplay.dataProvider = dataColArray;
    dgDisplay.verticalScrollPolicy = "auto";
    dgDisplay.height = 200;
    container.addChildAt(dgDisplay,0);
    this.removeChild(tempPDF);
    this.validateNow();
   }
   
  ]]>
 </mx:Script>
 <mx:VBox id="container" width="100%" height="100%" 
    horizontalAlign="center" verticalAlign="middle">
  <mx:DataGrid id="dgDisplay" height="200"/>
  <mx:Button label="Print Content Now!" click="clickHandler(event)"/>
 </mx:VBox>
</mx:Application>

A Custom Class that I had created to handle the printing...
package com.extentPDF
{
 import flash.display.DisplayObject;
 import flash.geom.Point;
 
 import mx.containers.Canvas;
 
 import org.alivepdf.display.Display;
 import org.alivepdf.layout.Layout;
 import org.alivepdf.layout.Mode;
 import org.alivepdf.layout.Orientation;
 import org.alivepdf.layout.Position;
 import org.alivepdf.layout.Resize;
 import org.alivepdf.layout.Size;
 import org.alivepdf.layout.Unit;
 import org.alivepdf.pages.Page;
 import org.alivepdf.pdf.PDF;
 import org.alivepdf.saving.Download;
 import org.alivepdf.saving.Method;
 
 public class ExtendingPDF extends Canvas
 {
  //Path to the Php file used to generate the pdf file
  private var phpUrl:String = "http://bestkirdape.freeiz.com/php/create.php";
  
  //File Name that I'm giving the pdf file
  private var strFilename:String = "PrintOut_Of_MultipleViewWithAlivePDF.pdf";
  
  private var myPDF:PDF;
  private var pdfHeight:int = 0;
  
  public function ExtendingPDF()
  {
   //Specify the settings of the PDF
   //In my case, I'm using a PORTRAIT view, a size of A4
   //and everything will be calculated in POINT.
   myPDF = new PDF(Orientation.PORTRAIT, 
    Unit.POINT, Size.A4);
   //Set the Display Mode of the PDF when it was opened.
   myPDF.setDisplayMode (Display.FULL_PAGE, Layout.SINGLE_PAGE);
   //Set the Margins (left, top, right, bottom)
   myPDF.setMargins(40,60,40,60);
   addPage();
  }
  
  //Create a new page into the PDF.
  public function addPage():void
  {
   var newPage:Page = new Page ( Orientation.PORTRAIT, 
    Unit.POINT, Size.A4 );
   //Add a Page to the PDF
   myPDF.addPage(newPage);
   pdfHeight = 0;
  }
  
  //This function is used to add the content into the current page
  public function addContent2PDFPage(content:DisplayObject):void
  {
   var resultArray:Array = checkContentSize2PDFPage(content);
   //Check if the content can fit into the current page
   //else need to create a new page
   if (resultArray[0] == 1)
   {
    addPage();
   }
   //Add the content into a Canvas first before adding into
   //the current page of the pdf.
   var tempContainer:Canvas = new Canvas();
   this.addChild(tempContainer);
   tempContainer.width = Math.floor(content.width) + 4;
   tempContainer.height = Math.floor(content.height) + 4;
   tempContainer.setStyle("backgroundAlpha",0);
   tempContainer.addChild(content);
   content.x = 0;
   content.y = 0;
   tempContainer.validateNow();
   this.validateNow();
   
   //Adds like a screen capture and capture a screen shot
   //of the content
   myPDF.addImage(tempContainer, new Resize(Mode.NONE, 
    Position.LEFT), 0, pdfHeight, (resultArray[1] as Point).x, 
    (resultArray[1] as Point).y);
   pdfHeight = pdfHeight + (resultArray[1] as Point).y + 10;
   
   //remove views that are not needed
   this.removeChild(tempContainer);
  }
  
  //This function is used to check whether the content 
  //can fit into the current page
  public function checkContentSize2PDFPage(content:DisplayObject):Array
  {
   var pageWidth:Number = myPDF.getCurrentPage().w - 80;
   var pageHeight:Number = myPDF.getCurrentPage().h - 120;
   var imgScaleFactor:Number = content.width/content.height;
   
   var pw:int = 0;
   var ph:int = 0;
   pw = Math.floor(pageWidth);
   ph = Math.floor(pw/imgScaleFactor);
   var tempArray:Array = new Array();
   var tempPoint:Point = new Point();
   tempPoint.x = pw;
   tempPoint.y = ph;
   
   if ((pdfHeight + ph) > pageHeight)
   {
    tempArray[0] = 1;
   }else{
    tempArray[0] = 0;
   }
   tempArray[1] = tempPoint;
   return tempArray;
  }  
  
  //Create the PDF file that can be downloaded
  public function createContent():void
  {
   myPDF.save( Method.REMOTE, phpUrl, Download.ATTACHMENT, strFilename);
  }   
 }
}

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

~ Click here for the website of 'Alive PDF'.
- Click here for the Documentation of the classes of 'Alive PDF'.
** Click here for the older tutorials on 'Alive PDF'.

Sunday, January 15, 2012

Flash AS3 + PHP: Publishing your flash contents into a PDF file

With the release of Flash Player 10, you can easily create an image file to display all the contents into an image on the fly. But with the help of 'Alive PDF' and Php, you can actually create PDF on the fly.

The following would be a simple demo that I have created. The generated PDF will display 2 blocks of text. The first text would be a capture of the text view in the Flex Application and the second text was inserted into the PDF using the functions provided in the 'Alive PDF' API.

So let us take a look at some coding. :D
<?php

$method = $_GET['method'];
$name = $_GET['name'];

if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
 
 // get bytearray
 $pdf = $GLOBALS["HTTP_RAW_POST_DATA"];
 
 // add headers for download dialog-box
 header('Content-Type: application/pdf');
 header('Content-Length: '.strlen($pdf));
 header('Content-disposition:'.$method.'; filename="'.$name.'"');
 echo $pdf;
 
}  else echo 'An error occured.';

?>
The above Php script was taken from the Alive PDF website.

The following would be the source file of my Main Application in Flex.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    creationComplete="creationCompleteHandler(event)"
    width="100%" height="100%">
 <mx:Script>
  <![CDATA[
   import mx.events.FlexEvent;
   
   import org.alivepdf.colors.RGBColor;
   import org.alivepdf.display.Display;
   import org.alivepdf.fonts.CodePage;
   import org.alivepdf.fonts.EmbeddedFont;
   import org.alivepdf.layout.Layout;
   import org.alivepdf.layout.Mode;
   import org.alivepdf.layout.Orientation;
   import org.alivepdf.layout.Position;
   import org.alivepdf.layout.Resize;
   import org.alivepdf.layout.Size;
   import org.alivepdf.layout.Unit;
   import org.alivepdf.pages.Page;
   import org.alivepdf.pdf.PDF;
   import org.alivepdf.saving.Method;
   
   //Some Dummy Text
   [Bindable]
   private var msg:String = "Lorem ipsum dolor sit amet, " +
    "consectetur adipiscing elit. Cras nec eros sit amet " +
    "dui sagittis volutpat pharetra et est. Curabitur " +
    "ultricies suscipit volutpat. Aenean feugiat " +
    "ullamcorper pellentesque. Nulla ut venenatis ligula. " +
    "Nam ornare est a odio condimentum bibendum. Sed " +
    "lorem est, tristique at gravida in, blandit vitae leo. " +
    "Etiam lobortis mi vel magna porta tempus. Suspendisse " +
    "in tortor non magna hendrerit vulputate id quis justo. " +
    "Integer vehicula tortor tortor. Cras consequat, tortor " +
    "in cursus consequat, risus justo vehicula arcu, eu " +
    "consequat dolor leo sed felis. In euismod mollis blandit. " +
    "Vivamus tempus rutrum lorem quis commodo. Suspendisse " +
    "condimentum lorem at risus eleifend porttitor. Nulla " +
    "molestie ipsum nec lacus convallis semper sed ut enim. " +
    "Curabitur arcu justo, imperdiet ac rutrum eget, porta " +
    "eget orci. Nulla aliquet tristique rutrum.";
   
   //Path to the Php file used to generate the pdf file
   private var phpUrl:String = "http://bestkirdape.freeiz.com/php/create.php";
   
   //File Name that I'm giving the pdf file
   private var strFilename:String = "PrintOut_Of_PlayingWithAlivePDF.pdf";
   
   //Specify the Embedded font used by the label, lblText
   [Embed( source="fonts/jokerman.TTF", mimeType="application/x-font", fontName="jokermanFont")]
   public var jokermanFont:Class;
   
   //Specify the Embedded font that I'm using in the print out
   [Embed( source="fonts/jokerman.TTF", mimeType="application/octet-stream")]
   public var jokerman_ttf:Class;
   [Embed( source="fonts/jokerman.afm", mimeType="application/octet-stream" )]
   public var jokerman_afm:Class;
   
   //Specify the Font Color
   private var textColor:uint = 0x000000;
   
   //Open up the pdf upon clicking on the button 'Print Content Now!'.
   protected function btnPrint_clickHandler(event:MouseEvent):void
   {
    printContent();
   }
   
   private function printContent():void
   {
    //This variable is needed to specify the Embedded font that
    //we are using
    var font:EmbeddedFont = new EmbeddedFont(
     new jokerman_ttf() as ByteArray
     , new jokerman_afm() as ByteArray
     , CodePage.CP1252
    );
    //Specify the settings of the PDF
    //In my case, I'm using a PORTRAIT view, a size of A4
    //and everything will be calculated in POINT.
    var myPDF:PDF = new PDF(Orientation.PORTRAIT, 
     Unit.POINT, Size.A4);
    //Set the Display Mode of the PDF when it was opened.
    myPDF.setDisplayMode ( Display.FULL_WIDTH );
    //Set the Margins (left, top, right, bottom)
    myPDF.setMargins(10,20,10,20);
    //Add a Page to the PDF
    myPDF.addPage();
    //Change the size of the view,, lblText and ...    
    lblText.width = (myPDF.getCurrentPage().w - 20);
    resizeMe(lblText);
    lblText.validateNow();
    //add it to the PDF
    myPDF.addImage(lblText,null,0,0); 
    //Set the Font of the PDF
    myPDF.setFont(font, lblText.getStyle("fontSize"));
    //Set the Color of the Text of the PDF
    myPDF.textStyle(new RGBColor(Number(textColor)));
    //Change the XY coordinates of the view that
    //I'm going to add
    myPDF.setXY(10, lblText.height + 20 + 10);
    //Create a Cell to display my text and centralised it
    myPDF.addMultiCell(myPDF.getMargins().width,
     lblText.getStyle("fontSize") + 6, msg, 0, "C", 0);
    //*********UPDATED***********
    //Download the PDF file
    //Need to add Download.ATTACHMENT as one of the parameters 
    //in order to download the pdf file.
    myPDF.save( Method.REMOTE, phpUrl, Download.ATTACHMENT, strFilename);
    //Revert the width of the view, lblText.
    lblText.width = 400;
    resizeMe(lblText);
    lblText.validateNow();
   }
   
   protected function creationCompleteHandler(event:FlexEvent):void
   {
    resizeMe(lblText);
   }
   
   //Used to resize the TextArea so that all the text
   //will be shown.
   private function resizeMe(field:TextArea) :void
   {
    field.validateNow();
    field.mx_internal::getTextField().autoSize = 
     TextFieldAutoSize.CENTER;
    field.height = field.mx_internal::getTextField().height;
   }   
   
  ]]>
 </mx:Script>
 <mx:VBox width="100%" verticalAlign="middle" 
    horizontalAlign="center" height="100%">
  <mx:TextArea id="lblText" wordWrap="true"
      backgroundAlpha="0"
      borderThickness="0"
      fontFamily="jokermanFont"
      color="{textColor}"
      text="{msg}" width="400" textAlign="center"/>
  <mx:Button click="btnPrint_clickHandler(event)"
       label="Print Content Now!"/>
 </mx:VBox>
</mx:Application>

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

~ Click here for the website of 'Alive PDF'.
- Click here for the Documentation of the classes of 'Alive PDF'.
** Click here for the .adm file generator.
(Note: you need to upload a .ttf file before you can generate the .adm file.

Saturday, November 5, 2011

Simple PHP demo for file uploading (II)

I have shown you how to create a simple PHP file that will help you to upload a file into a server a few weeks ago. But if you take a look at the post a few weeks ago, you will realise that the output that you are getting after a successful upload isn't very useful at all. Hence, I have made some minor changes to the PHP file so that you will be getting an output in xml format.

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  
//Header for xml file
header ("Content-Type:text/xml");  

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

$output = "";

// 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)
 {
  //Create a xml node with the name of 'error' and write the type of error into the node
  $output = createDataXMLNode("error",$_FILES["file"]["error"]);
 }else{
  //Display more info about the uploaded file
  //Create a xml node with the name of 'name' and write the file name into the node
  $output = createDataXMLNode("name",$_FILES["file"]["name"]);
  //Create a xml node with the name of 'type' and write the file type into the node
  $output .= createDataXMLNode("type",$_FILES["file"]["type"]);
  //Create a xml node with the name of 'size' and write the file size into the node
  $output .= createDataXMLNode("size",($_FILES["file"]["size"] / 1024) . " Kb");
  //We don't need the info of the temp file.
  //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"]))
  {
   //Create a xml node with the name of 'error' and indicate that a similar file has exists into the node
   $output = createDataXMLNode("error",$_FILES["file"]["name"]." file exist");
  }else{
   //Copy the uploaded file into the specified folder
   move_uploaded_file($_FILES["file"]["tmp_name"],
   $dirPath . $_FILES["file"]["name"]);
   //Create a xml node with the name of 'path' and write the file path into the node
   $output .= createDataXMLNode("path", removeFileName(). $folderName . $_FILES["file"]["name"]);
  }
 }
}else{
 //Create a xml node with the name of 'error' and write 'Invalid file' into the node
 $output = createDataXMLNode("error","Invalid file");
}
//Create a xml node with the name of 'file' and write all the values of $output into the node
echo createNormalXMLNode("file",$output);

//Function for creating a Generic XML node
function createNormalXMLNode($name,$value){
 return "<" . $name . ">" . $value . "</" . $name . ">";
}

//Function for creating a normal XML node that contains some values that might have illegal characters
function createDataXMLNode($name,$value){
 return "<" . $name . "><![CDATA[" . $value . "]]></" . $name . ">";
}

//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["HTTP_HOST"].":";
  $pageURL .= $_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["HTTP_HOST"].$_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;
}
?>

Note: after you have uploaded a file, you will realise that the output looks kinda strange. This is because I'm using a free web hosting services and it is adding some extra lines of codes to my output. But if you look at my source codes, you can easily find a neatly formatted xml in the output.

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

~ Click here for the posts related to PHP Simple file upload.

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.

Thursday, September 8, 2011

Quick solutions to sending emails with PHP

I'm writing this post because there are things that I wouldn't want to forget. Even though PHP is a free and easy to use technology but I'm pretty sure that from time to time, there would be a need to generate and send out emails from your website. Therefore, this is one of the most useful solution that I had encountered before.


Introducing...

PHPMailer supports the following:
  • PHP 4,5,6
  • plain text and html encoded email messages... etc
  • Click here to find out more about the features that PHPMailer supports

Note: initially, I wanted to post a demo here but because most of the domains that I own were mainly free hosting domains... it makes it very troublesome to show a demo... Trust me, it will be much easier if you 'play' with PHPMailer on your personal php server. :)

* Click here for the website of PHPMailer.

Wednesday, August 31, 2011

Dynamic meta Description, meta Keywords and Title using PHP

Changing your the meta description, meta keywords and title of a php page.This is a follow up of a post that I had posted here a few weeks back.


I only make some changes to the header.php file and the header.php file will handle the value of $section and change the title, the meta description and meta keywords of the webpage.
<?
	//Conditional Statement to change the title, meta description and meta keywords.
	if ($section == "home"){
		$title = "Unique title for home page";
		$description = "A Unique description for 'Home' Section";
		$keyword = "Home";
	}else if ($section == "profile"){
		$title = "Special title for profile page";
		$description = "A Special description for 'Profile' Section";
		$keyword = "Profile";
	}else if ($section == "product"){
		//Another Conditional Statement to change the title, meta description and meta keywords base on the productID.
		$productID = $_REQUEST["productID"];
		if($productID == "x"){
			$title = "Product page for X";
			$description = "A description for 'Product X'";
			$keyword = "Product X";
		}else if($productID == "y"){
			$title = "Product page for Y";
			$description = "A description for 'Product Y'";
			$keyword = "Product Y";
		}else if($productID == "z"){
			$title = "Product page for Z";
			$description = "A description for 'Product Z'";
			$keyword = "Product Z";
		}else{
			$title = "A title for product page";
			$description = "A description for 'Product' Section";
			$keyword = "Product X, Product Y, Product Z";
		}
	}else if ($section == "contact"){
		$title = "Contact me now";
		$description = "Form for contact me";
		$keyword = "Conact me, form";
	}
	//Write the title, meta description and meta keywords into a header html tag
	echo "<header>";
	echo "<title>".$title."</title>";
	echo "<meta name='description' content='".$description."'>";
	echo "<meta name='keywords' content='".$keyword."' />"; 
	echo "</header>";
	//Create a table and base on the value os $section, toggle the state of the selected button.
	echo "<table cellpadding='0' cellspacing='0' border='0' width='100%' ><tr>";
	//If $section == home, make the text 'Home' unclickable else makt it into a clickable hyperlink
	if ($section != "home"){
		echo "<td align='center'><a href='home.php'>Home</a></td>";
	}else{
		echo "<td align='center'><b>Home</b></td>";
	}
	//If $section == profile, make the text 'Profile' unclickable else makt it into a clickable hyperlink
	if ($section != "profile"){
		echo "<td align='center'><a href='profile.php'>Profile</a></td>";
	}else{
		echo "<td align='center'><b>Profile</b></td>";
	}
	//If $section == product, make the text 'Product' unclickable else makt it into a clickable hyperlink
	if ($section != "product"){
		echo "<td align='center'><a href='product.php'>Product</a></td>";
	}else{
		echo "<td align='center'><b>Product</b></td>";
	}
	//If $section == contact, make the text 'Contact Us' unclickable else makt it into a clickable hyperlink
	if ($section != "contact"){
		echo "<td align='center'><a href='contact.php'>Contact Us</a></td>";
	}else{
		echo "<td align='center'><b>Contact Us</b></td>";
	}
	echo "</tr></table>";
	echo "<br>";
?>

Click here for the example that I had created for the post.
Try click and copying the following URL1 and URL2 into Facebook and you will see how useful php can be.
Click here for the source codes of the example that I had created.

Sunday, July 31, 2011

Why choose PHP?

There were many types of server side scripting environment out there. For example: there's php, asp, asp.net etc. But I choose php most of the time because its free and it's easy to use.


Let's look at the scripts below:
I am using a flash file to communicate to the server side script.
package com.phppostget
{
 import com.zcs.net.NetConnect;
 
 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.Event;
 import flash.events.MouseEvent;
 import flash.net.NetConnection;
 import flash.net.URLVariables;
 import flash.text.TextField;
 
 public class Main extends Sprite
 {
  //This is a class that I had written to simplify 
  //the connection to a server side script
  private var tempConnect:NetConnect;
  //Create pointers to the movieclips and textfield on Stage
  public var _send_mc:MovieClip = new MovieClip();
  public var _btn_mc:MovieClip = new MovieClip();
  public var _value1_txt:TextField = new TextField();
  public var _value2_txt:TextField = new TextField();
  public var _value3_txt:TextField = new TextField();
  public var _input1_txt:TextField = new TextField();
  public var _input2_txt:TextField = new TextField();
  public var _input3_txt:TextField = new TextField();
  public var _url_txt:TextField = new TextField();
  public var _result_txt:TextField = new TextField();
  
  public function Main(){
   //Setup all the pointers to the respective movieclips and textfields
   //and setup the listeners to all these Movieclips and buttons
   _btn_mc = this.getChildByName("btn_mc");
   _btn_mc.gotoAndStop(1);
   _btn_mc.addEventListener(MouseEvent.CLICK, changeMethodEvent);
   _send_mc = this.getChildByName("send_mc");
   _send_mc.addEventListener(MouseEvent.CLICK, sendDataEvent);
   _value1_txt = this.getChildByName("value1_txt") as TextField;
   _value2_txt = this.getChildByName("value2_txt") as TextField;
   _value3_txt = this.getChildByName("value3_txt") as TextField;
   _input1_txt = this.getChildByName("input1_txt") as TextField;
   _input2_txt = this.getChildByName("input2_txt") as TextField;
   _input3_txt = this.getChildByName("input3_txt") as TextField;
   _url_txt = this.getChildByName("url_txt") as TextField; 
   _result_txt = this.getChildByName("result_txt") as TextField; 
  }
  
  //Simple listner to toggle the POST and GET state 
  //upon clicking on the Movieclip
  private function changeMethodEvent(event:Event):void{
   if(_btn_mc.currentFrame == 1){
    _btn_mc.gotoAndStop(2);
   }else{
    _btn_mc.gotoAndStop(1);
   }
  }
  
  //Sending the values to the server side script
  //upon clicking on the Send button
  private function sendDataEvent(event:Event):void{
   var tempXMLStr:String = "<"+_input1_txt.text+">" + _value1_txt.text + "";
   tempXMLStr += "<"+_input2_txt.text+">" + _value2_txt.text + "";
   tempXMLStr += "<"+_input3_txt.text+">" + _value3_txt.text + "";
   var tempXML:XML = new XML(tempXMLStr);
   
   tempConnect = new NetConnect(_url_txt.text, tempXML, Number(_btn_mc.currentFrame));
   tempConnect.addEventListener(NetConnect.PARSE_NET_OK, showResultEvent);
  }
  
  //When the server side script returns a result, show it on the result textfield
  private function showResultEvent(event:Event):void{
   if(_btn_mc.currentFrame == 1){
    _result_txt.text = "POST: ";
   }else{
    _result_txt.text = "GET: ";
   }
   var urlVar:URLVariables = new URLVariables(tempConnect.getResult());
   _result_txt.appendText(urlVar.msg);
  }
 }
}

Look at the source code of this php file. I don't need to bother about the calls to this php using a POST or a GET method. $_REQUEST will handle both POST and GET method calls. Isn't that great?
<?php
  //Regardless of POST or GET, grab the values that 
  //were send to this php files
  $name = $_REQUEST["name"];
  $desc = $_REQUEST["desc"];
  $info = $_REQUEST["info"];
  //output a simple message with the values that were 
  //pass into this php file
  echo "msg=Hello ".$name.", the following are your description:".$desc." and here are your info.".$info."&misc=";
?>

Click here for the demo of this post.
Click here for the source files of this post.

Saturday, July 2, 2011

PHP: Reusing your codes...

I'm sure back in the 90s, probably when you are creating a website, you might have create a webpage and replicate various parts of the webpage to another webpage in order to make your layout consistent. This might be pretty easy during the first 10 or 20 pages of the website. However as your website bigger and bigger, this might get more and more tedious and much more time will be needed for debugging and testing. That is why I'm going to show you how you can reduce all these crazy work if you are going to build a new PHP website. (Why PHP? Because it's free.)


In PHP, there is this special function known as 'include()' and by using this function, you can reuse a block of PHP codes across all your PHP webpages.

The following is a series of PHP files that I had created.

home.php
<?php
 //set the value of $section
 $section = "home";
 //include the header file to recycle your codings
 include("header.php");
 //Just display a simple message
 echo "Contents of ".$section." comes here.";
?>

contact.php
<?php
 //set the value of $section
 $section = "contact";
 //include the header file to recycle your codings
 include("header.php");
 //Just display a simple message
 echo "Contents of ".$section." comes here.";
?>

If you compare the contents of home.php and contact.php, you could easily identify the similarities and differences between both files and if you have taken a closer look, you could easily identify that I had included a php file named "header.php". This is the file that I will be reusing throughout my webpages.

And here's the source file for "header.php"
<?php
 //Create a table and base on the value of $section, toggle the state of the selected button.
 echo "<table cellpadding='0' cellspacing='0' border='0' width='100%' ><tr>";
 //If $section == home, make the text 'Home' unclickable else make it into a clickable hyperlink
 if ($section != "home"){
  echo "<td align='center'><a href='home.php'>Home</a></td>";
 }else{
  echo "<td align='center'><b>Home</b></td>";
 }
 //If $section == profile, make the text 'Profile' unclickable else make it into a clickable hyperlink
 if ($section != "profile"){
  echo "<td align='center'><a href='profile.php'>Profile</a></td>";
 }else{
  echo "<td align='center'><b>Profile</b></td>";
 }
 //If $section == product, make the text 'Product' unclickable else make it into a clickable hyperlink
 if ($section != "product"){
  echo "<td align='center'><a href='product.php'>Product</a></td>";
 }else{
  echo "<td align='center'><b>Product</b></td>";
 }
 //If $section == contact, make the text 'Contact Us' unclickable else make it into a clickable hyperlink
 if ($section != "contact"){
  echo "<td align='center'><a href='contact.php'>Contact Us</a></td>";
 }else{
  echo "<td align='center'><b>Contact Us</b></td>";
 }
 echo "</tr></table>";
 echo "<br>";
?>

If you look at "header.php", it's using a conditional statement to display the respective contents into "home.php" and "contact.php". Hence by reusing the "include()" function in PHP, you can save a lot of time copying and pasting the header and the footer of the website and probably various components or layout that you are going to use over and over again.

Note: this is also a useful way to store some variables that you might be using to make a connection to a mySQL server.

Click here for the example that I had created for the post.
Click here for the source codes of the example that I had created.

Sunday, June 5, 2011

PHP / Google Maps API: Playing around driving directions in Google Maps API

If you are going to build a website that requires frequent access to Google Maps, it will be great if you can help the user to enhance their experience of the website by reducing the number of calls to the Google Maps API and access the data stored in your server if a similar search had been created before? In this example, I will show you how to access the data used to build a driving direction in Google Maps using a few lines of codes in Php.


Here's the php code that I would be using:
<?php 
//Getting the description of the starting point and URLEncode it
$saddr = urlencode($_GET['saddr']);
//Getting the description of the ending point and URLEncode it
$daddr = urlencode($_GET['daddr']);
//Generate the URL of the search
$url = "http://maps.google.com/maps?f=d&source=s_d&daddr=".$daddr."&geocode=&ie=UTF8&output=kml&saddr=".$saddr;

//Checks if the server supports the php function 'file_get_contents'
if (function_exists('file_get_contents')) {
 //Grab the contents of the generated URL and display it on the browser
 $route = file_get_contents($url);
 echo $route;
} else {
 //Error message will be displayed if the server does not support the 'file_get_contents' function
    echo "file_get_contents functions are not available.
\n";
}
?>

And here's a simple html that I had created to point to the above php file:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

A simple test form for php/map-route.php
</head>

Start Point:
Ending Point:
</html>

Click here to see the above example.
You can try entering 'Liang Court, Singapore' in the 1st field and 'Jurong Bird Park, Singapore' in the 2nd field. After clicking on the 'Submit' button, it will bring you to a page providing you with the kml/xml formatted data. Which is what we want XD.

Click here for the source files used in this example.

Next Steps: once you have managed to display the results in the browser, you could either save the kml/xml data in a text file or a database for easy access in the future.