PHP functional HTML rendering

Working with HTML integration while writing code is sometimes tedious and time consuming, most of the times just copy paste.

Recently viewed a post about adding some fun in doing so.

Some may found it complicated, some may found unnecessary. but someone who are keen to explore new things or hidden things here is example.

 

First start with two basic functions that will carry out most of our complicated things

 

function tag(){
$args = func_get_args();
$nm = array_shift($args);
$content = array_shift($args);
$attrs = array_chunk($args, 2);
echo “<$nm “;
foreach($attrs as $chunk)
echo $chunk[0].’=’.'”‘.$chunk[1].'” ‘;
echo ‘>’;
if(is_string($content) || is_numeric($content) || empty($content))
echo $content;
else
$content();
echo “</$nm>”;
}

function etag(){
$args = func_get_args();
$nm = array_shift($args);
$attrs = array_chunk($args, 2);
echo “<$nm “;
foreach($attrs as $chunk)
echo $chunk[0].’=’.'”‘.$chunk[1].'” ‘;
echo “/>”;
}

So the first argument to our tag function is the tag name, second is the content to render inside the tag and the rest of the arguments are the attribute name and value pairs. Same goes for the etag function which renders empty elements, but then sans the content argument of course.

Below are a few examples of usage, first a simple login form.

tag(‘div’, function(){
tag(‘form’, function(){
echo ‘Username:’;
etag(‘input’, ‘type’, ‘text’, ‘name’, ‘username’);
echo ‘Password:’;
etag(‘input’, ‘type’, ‘password’, ‘name’, ‘password’);
etag(‘input’, ‘type’, ‘submit’, ‘value’, ‘Submit’, ‘name’, ‘submit’);
}, ‘method’, ‘post’);
}, ‘class’, ‘normal-pad’);

Then a more complicated scenario where we want to render a table of statistics:

function statsTable($stats, $headers, $fields, $sums){
tag(‘table’, function() use ($stats, $sums, $headers, $fields){
tag(‘tr’, function() use ($headers){
foreach($headers as $header)
tag(‘th’, $header);
});
foreach($stats as $s){
tag(‘tr’, function() use ($s, $fields){
foreach($fields as $field)
tag(‘td’, $s[$field]);
});
}
tag(‘tr’, function() use ($sums, $fields){
foreach($fields as $field)
tag(‘td’, is_numeric($sums[$field]) ? $sums[$field] : ”);
}, ‘class’, ‘sum-row’);
}, ‘class’, ‘stats-table’);
}

 

 

How to execute PHP code on existing html page?

The way to execute PHP on a .html page is to modify your .htaccess file. This file may be hidden, so depending upon your FTP program you may have to modify some settings to see it. Then you just need to add this line for .html:

AddType application/x-httpd-php .html

If you only plan on including the PHP on one page, it is better to setup this way:
<Files abc.html>
AddType application/x-httpd-php .html
</Files>
This code will only make the PHP executable on the abc.html file, and not on all of your html pages.

How to configure a basic php application on amazon ec2

The most important thing is you need your valid amazon login details

Login with the credentials and you will land on the home screen, dont get confused with various options to setup working php mysql application you need a few options.

The first most important thing is to generate a ssh key and import in the console A good guide on how to generate can be found HERE

Once imported name the key you can remember say php or mykey etc I use php.

Next you can go to Elastic Beanstalk section, select launch new environment.

Choose the required parameters the most important is container type

Select the one which suits you for your php mysql I selected 32 bit amazon linux running php 5.3

Check the parameters for most of columns dont change any but to keep the default one

After filling all the details your environment is can be seen on the same screen, wait for the color or environment to change to green which indicates ALL IS WELL…

You are now almost 50% done till this step.

Go to environment url to check the sample code working, some welcome app or sample application screen

If not then there is something wrong and you can check the environment logs or events to check status.

Next go to EC2 section and your newly created instance is waiting for you.

Its now time to access the newly created instance to upload some files.

Allocate one Elastic Ip from the EC2->Elastic IP section to your instance.

In the instance details you can now see the IP allocated. Just to confirm type that IP address in browser and you should see the same app page that was there while checking the environment url.

Next step is set up putty to access the instance.

Convert the generated key in first step to PPK (Putty Private Key) format. An illustrative guide can be found HERE.

For a Quick revision we followed steps as

  1. Generated key pair
  2. Created instance with default environment
  3.  Imported keys to ec2  environment
  4.  Edited instance to allocate the IP to allow SSH
Next step is to actually ssh your newly created instanceGo to instance section under EC2->instances and click on your instance and note down the elastic IP associated.
Now Open the Puty for SSH connection
In connection details put your elastic IP and under SSH -> Auth section browse the ppk file you created.
When prompted enter user name as ec2-user and password as what you selected while creating your key.

Bingo…….

If  ALL IS WELL you can see the favorite black screen for linux console.. Its now your play ground.. and now time to do some settings.
Check for php version and apache version for curiosity, Its not necessary but to start with or to brush your knowledge if you are accessing it after long time like me.
The default apache location is /etc/httpd/
and default webroot will be /var/www/html
Edit some files or create a new one..using VI editor and check on front end..

Fancy Gradient Buttons for Android

Design elements for android is some what complex task in the beginning, but as you explore the internet you will find
Default buttons for android code not so cool so I decided to use the image button instead of regular buttons, then too for some low end devices that is not looking good

After searching for internet I got concept to use the Stylesheet properties for buttons HERE

Its pretty simple and straight forward

First you need to define the xml for color gradient effect. I choose Red color first

File 1 res/drawable/btn_red.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#ef4444" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#ef4444"
                android:endColor="#992f2f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

After this file you need to define the style resources for button text

Include following style tag in res/values/strings.xml

<style name="ButtonText">
 <item name="android:layout_width">fill_parent</item>
 <item name="android:layout_height">wrap_content</item>
 <item name="android:textColor">#ffffff</item>
 <item name="android:gravity">center</item>
 <item name="android:layout_margin">3dp</item>
 <item name="android:textSize">30dp</item>
 <item name="android:textStyle">bold</item>
 <item name="android:shadowColor">#000000</item>
 <item name="android:shadowDx">1</item>
 <item name="android:shadowDy">1</item>
 <item name="android:shadowRadius">2</item>
</style>

Finally Include the button code where you want the fancy gradient button to appear as follows

<Button
 android:id="@+id/button1"
 style="@style/ButtonText"
 android:layout_width="match_parent"
 android:background="@drawable/btn_red"
 android:text="RedButton" >
</Button>

Note the background attribute and style attribute .

PHP class to send mail via SMTP AUTH

If anyone needs it here is a PHP class for sending mail via SMTP AUTH to the local smtp server. This can be used instead of the php mail function which is due to be turned off on the shared platforms. It’s not perfect, but it’s not too bad either: –

Class Email.php

<?php

/**
* Class Email.php Used to send email via SMTP authentication
* 
*/

class EMail
{
  const newline = "\r\n";

  private
    $Server, $Port, $Localhost,
    $skt;

  public
    $Username, $Password, $ConnectTimeout, $ResponseTimeout,
    $Headers, $ContentType, $From, $To, $Cc, $Subject, $Message,
    $Log;

  function __construct()
  {
    $this->Server = "127.0.0.1"; // get replaced with your SMTP server
    $this->Port = 25; // replace this with SMTP Port
    $this->Localhost = "localhost";
    $this->ConnectTimeout = 30;
    $this->ResponseTimeout = 8;
    $this->From = array();
    $this->To = array();
    $this->Cc = array();
    $this->Log = array();
    $this->Headers['MIME-Version'] = "1.0";
    $this->Headers['Content-type'] = "text/plain; charset=iso-8859-1";
  }

  private function GetResponse()
  {
    stream_set_timeout($this->skt, $this->ResponseTimeout);
    $response = '';
    while (($line = fgets($this->skt, 515)) != false)
    {
	$response .= trim($line) . "\n";
	if (substr($line,3,1)==' ') break;
    }
    return trim($response);
  }

  private function SendCMD($CMD)
  {
    fputs($this->skt, $CMD . self::newline);

    return $this->GetResponse();
  }

  private function FmtAddr(&$addr)
  {
    if ($addr[1] == "") return $addr[0]; else return "\"{$addr[1]}\" <{$addr[0]}>";
  }

  private function FmtAddrList(&$addrs)
  {
    $list = "";
    foreach ($addrs as $addr)
    {
      if ($list) $list .= ", ".self::newline."\t";
      $list .= $this->FmtAddr($addr);
    }
    return $list;
  }

  function AddTo($addr,$name = "")
  {
    $this->To[] = array($addr,$name);
  }

  function AddCc($addr,$name = "")
  {
    $this->Cc[] = array($addr,$name);
  }

  function SetFrom($addr,$name = "")
  {
    $this->From = array($addr,$name);
  }

  function Send()
  {
    $newLine = self::newline;

    //Connect to the host on the specified port
    $this->skt = fsockopen($this->Server, $this->Port, $errno, $errstr, $this->ConnectTimeout);

    if (empty($this->skt))
      return false;

    $this->Log['connection'] = $this->GetResponse();

    //Say Hello to SMTP
    $this->Log['helo']     = $this->SendCMD("EHLO {$this->Localhost}");

    //Request Auth Login
    $this->Log['auth']     = $this->SendCMD("AUTH LOGIN");
    $this->Log['username'] = $this->SendCMD(base64_encode($this->Username));
    $this->Log['password'] = $this->SendCMD(base64_encode($this->Password));

    //Email From
    $this->Log['mailfrom'] = $this->SendCMD("MAIL FROM:<{$this->From[0]}>");

    //Email To
    $i = 1;
    foreach (array_merge($this->To,$this->Cc) as $addr)
      $this->Log['rcptto'.$i++] = $this->SendCMD("RCPT TO:<{$addr[0]}>");

    //The Email
    $this->Log['data1'] = $this->SendCMD("DATA");

    //Construct Headers
    if (!empty($this->ContentType))
      $this->Headers['Content-type'] = $this->ContentType;
    $this->Headers['From'] = $this->FmtAddr($this->From);
    $this->Headers['To'] = $this->FmtAddrList($this->To);
    if (!empty($this->Cc))
      $this->Headers['Cc'] = $this->FmtAddrList($this->Cc);
    $this->Headers['Subject'] = $this->Subject;
    $this->Headers['Date'] = date('r');

    $headers = '';
    foreach ($this->Headers as $key => $val)
      $headers .= $key . ': ' . $val . self::newline;

    $this->Log['data2'] = $this->SendCMD("{$headers}{$newLine}{$this->Message}{$newLine}.");

    // Say Bye to SMTP
    $this->Log['quit']  = $this->SendCMD("QUIT");

    fclose($this->skt);

    return substr($this->Log['data2'],0,3) == "250";
  }
}
?>

The Sample code to use above class is as follows

<?php

require "email.php";

$mail = new EMail;
$mail->Username = 'youremail@example.com';
$mail->Password = 'YourEmailPassword';

$mail->SetFrom("fromemail@example.com","Sender Name");		// Name is optional
$mail->AddTo("toemail@example.com","Guest Name");	// Name is optional
$mail->AddTo("toemail2@example.com","Guest 2 Name");
$mail->Subject = "Some subject or other";
$mail->Message = "Some html message";

//Optional stuff
$mail->AddCc("ccaddress@example.com","CC Name"); 	// Set a CC if needed, name optional
$mail->ContentType = "text/html";        		// Defaults to "text/plain; charset=iso-8859-1"
$mail->Headers['X-SomeHeader'] = 'abcde';		// Set some extra headers if required
$mail->ConnectTimeout = 30;		// Socket connect timeout (sec)
$mail->ResponseTimeout = 8;		// CMD response timeout (sec)

$success = $mail->Send();

?>

Extra notes to consider 

  • An SMTP session log is available for debugging, stored as an array in $mail->Log.
  • $mail->Headers Will NOT override To,From,Cc,Subject
  • $mail->Headers can be used to set Content-Type but $mail->ContentType will override if set.
  • $mail->Headers can be read after send to see the final headers used.

Android Save SD Card file to Remote server using PHP

In the previous post I explained about listing the specific extension files in Android list view. Now lets have a look to upload the file to remote server using a server side coding in PHP

private String SaveFileToServer() {
    String serverurl ="http://example.com/uploadfile.php"; // this is your server url to which you post the file contents
    String fileurl = "absolute_path_to_file_stored_on_sd_card"; // the path should be absoulute starting with /mnt/sdcard/filename.doc etc
  
    try {
      FileInputStream fis = new FileInputStream(new File(fileurl));
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
        bos.write(buf, 0, readNum); // no doubt here is 0
      }
   } catch (IOException ex) {
      ex.printStackTrace();
 }
 byte[] bytes = bos.toByteArray();
 byte[] filetosend = Base64.encode(bytes, Base64.DEFAULT);
 String fts = new String(filetosend);
 this.user.setBase_64_encoded_filestring(fts);
 String parameters = this.user.tofileString();
 try {
   this.message = ServerCommunication.post_string(serverurl, parameters); // this is custom function to post the data to post the remote url
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
 }
} catch (FileNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
return this.message;
 }
}

After this lets have a look at server side php code that will accept the data save on server and in return give you full path for the file saved

<?php 
if(isset($_POST['filedata'])) $filedata=$_POST['filedata']; else $filedata=""; // check for filedata to save
if(isset($_POST['file_url'])) $filename=$_POST['file_url']; else $filename=""; // check for filename not empty
$filename=date("ymdhis")."-".$fname;// change the filename to append the timestamp to avoid overwrite
$location="../../files/".$filename;// decide the location
//now write the file
 $filedata1=base64_decode($filedata);
 $ftw=fopen($location,'wb');
 if(fwrite($ftw,$filedata1)) {
 $fileurl="http://www.example.com/files/".$filename;
 echo $fileurl;
 } 
 
 fclose($ftw);
 ?>

So on success it will give you full path as output which you can save in your ANDROID code for future refecence

The code was simple but I have done some modifications as per the requirement. Hope you find this useful, ENJOY the stuff.