Category Archives: sam

Basic PHP Contact Form Script

Basic PHP Contact Form Script accepts name, email and message as POST vars then strips tags (more security could be added here to prevent attacks, mysqli can be used but requires db connection to escape). It then constructs the message in HTML format with proper encoded and content type and finally sends the email using PHP’s mail() function.

<?php

/*
    Script to send email from website.
    Author: Sam Deering 2012
*/


header('content-type: application/json; charset=utf-8');

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["msg"]))
{
    $recipent = array(
        "name" => strip_tags($_POST["contact_name"]),
        "email" => strip_tags($_POST["contact_email"])
    );

    //specify your own here to override if you want.
    // $recipent = array(
    //     "name" => "Sam Deering",
    //     "email" => "info@jqmbuilder.com"
    // );

    $sender = array(
        "name" => strip_tags($_POST['name']),
        "email" => strip_tags($_POST['email']),
        "message" => strip_tags($_POST['msg'])
    );

    $subject = 'Contact message from website';

    $message = '<html><head><title>'.$title.'</title></head><body>'.$sender["message"].'</body></html>';

    // To send HTML mail, the Content-type header must be set
    $headers = "From: {$sender['name']} <{$sender['email']}>" . "\r\n";
    $headers .= "Reply-To: {$sender['email']}" . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if(mail($recipent["email"], $subject, $message, $headers))
    {
        echo json_encode(true);
    }
    else
    {
        echo json_encode(false);
    }

}
else
{
    echo json_encode(false);
}

?>

Recursive Zip Folder Using PHP no Absolute Realpath

Code snippets and functions to Recursive Zip Folder Using PHP no Absolute Realpath. Was real tricky to get working so documenting some code snippets here for future reference.

This function creates the zipped folder. Just provide the path of the folder you want to zip and it will happen.

function createZip($siteDir)
{
      //settings
      ini_set("max_execution_time", 300);

      $time = date("H-i-s"); //time appended to filename

      $zipFile = $siteDir.'.zip'; //download link

      // create object
      $zip = new ZipArchive();
      // open archive
      if ($zip->open($zipFile, ZIPARCHIVE::CREATE) !== TRUE)
      {
            die ("Could not open archive");
      }

      $zip = addDirectoryToZip($zip, $siteDir, str_replace(basename($siteDir), '', $siteDir));

      // close and save archive
      $zip->close();
      // echo "Archive created successfully.";

      //return more stuff
      return array(
          "downloadLink" => $zipFile,
          "viewLink" => $siteDir
      );
}

This function helped remove the realpath in the zipped content.

function addDirectoryToZip($zip, $dir, $base)
{
    $newFolder = str_replace($base, '', $dir);
    $zip->addEmptyDir($newFolder);
    foreach(glob($dir . '/*') as $file)
    {
        if(is_dir($file))
        {
            $zip = addDirectoryToZip($zip, $file, $base);
        }
        else
        {
            $newFile = str_replace($base, '', $file);
            $zip->addFile($file, $newFile);
        }
    }
    return $zip;
}

The original zip function.

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('
\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '
/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '
/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '
/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

Create Zip Archive of Folder and All Contents

PHP code snippet to Create Zip Archive of Folder and All Contents – without the full directory path being included.

<?php

//function to zip an entire folder to back a backup
//saves to archive/year/month/day/filename.zip
function createZip($zipName,$folderToZip)
{
      // get year digits
      $year = date("Y");
      //create year directory if doesn't exist
      if (!is_dir('archive/'.$year))
      {
          mkdir('archive/'.$year);
      }

      //get month digits
      $month = date("m");
      //create month directory if doesn't exist
      if (!is_dir('archive/'.$year.'/'.$month))
      {
          mkdir('archive/'.$year.'/'.$month);
      }

      //get day digits
      $day = date("d");
      //create day directory if doesn't exist
      if (!is_dir('archive/'.$year.'/'.$month.'/'.$day))
      {
          mkdir('archive/'.$year.'/'.$month.'/'.$day);
      }

      $zipFile = 'archive/'.$year.'/'.$month.'/'.$day.'/'.$zipName.'.zip';

      ini_set("max_execution_time", 300);
      // create object
      $zip = new ZipArchive();
      // open archive
      if ($zip->open($zipFile, ZIPARCHIVE::CREATE) !== TRUE)
      {
            die ("Could not open archive");
      }
      // initialize an iterator
      // pass it the directory to be processed
      $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderToZip."/"));
      // iterate over the directory
      // add each file found to the archive
      foreach ($iterator as $key=>$value)
      {
            $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
      }
      // close and save archive
      $zip->close();
      echo "Archive created successfully.";

      return $zipFile;
}
?>

script to log $_POST vars to a txt file

Just a script code snippet to log $_POST and $_GET vars to text file.

<?php

/* Author: Sam Deering 2012 */

/* script to log $_POST vars to file */

$file = "log.txt";
$date = new DateTime();
$data = $date->format('Y-m-d H:i:s') . "\n";
$data .= "-------------------------------------------------------------" . "\n";
//dynamically set vars from POST vars
foreach($_POST as $n => $v)
{
    $$n = $v;
    $data .= $n . '=' . $v . "\n";
}
//dynamically set vars from GET vars
foreach($_GET as $n => $v)
{
    $$n = $v;
    $data .= $n . '=' . $v . "\n";
}
$data .= "-------------------------------------------------------------" . "\n\n";

echo $data;
$fp = fopen($file, "w") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);


?>

Upload Image and Create Thumbnail PHP Script

This is a PHP script that i wrote which receives an image from front end and uploads it, creates a thumbnail and returns both the master and thumb image info as JSON. I’ve pumped it with comments which should explain what the code does. This scripts works with the frontend code to use AJAX to upload image.

<?php
/*
  Copyright PHP Scripts 4U 2012
  Author: Sam Deering
*/


$error = $filename = $filesize = $fileloc = $thumb_name = '';
$fileElementName = 'image-upload';
$img_base_dir = "../img/uploaded/";

define ("MAX_SIZE","2000");  //define a maxim size for the uploaded images

// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","350");
define ("HEIGHT","150");

if(!empty($_FILES[$fileElementName]['error']))
{
    switch($_FILES[$fileElementName]['error'])
    {
        case '1':
            $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
            break;
        case '2':
            $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
            break;
        case '3':
            $error = 'The uploaded file was only partially uploaded';
            break;
        case '4':
            $error = 'No file was uploaded.';
            break;

        case '6':
            $error = 'Missing a temporary folder';
            break;
        case '7':
            $error = 'Failed to write file to disk';
            break;
        case '8':
            $error = 'File upload stopped by extension';
            break;
        case '999':
        default:
            $error = 'No error code avaiable';
    }
}
elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
{
    $error = 'No file was uploaded..';
}
else
{
    //save master image to temp folder, name it using a temp name
    //resize and save thumb image, name it using the same temp name as master

    //this is the function that will create the thumbnail image from the uploaded image
    //the resize will be done considering the width and height defined, but without deforming the image
    function make_thumb($img_name,$filename,$new_w,$new_h)
    {
        //get image extension.
        $ext=getExtension($img_name);
        //creates the new image using the appropriate function from gd library
        if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
          $src_img=imagecreatefromjpeg($img_name);

          if(!strcmp("png",$ext))
          $src_img=imagecreatefrompng($img_name);

          //gets the dimmensions of the image
        $old_x=imageSX($src_img);
        $old_y=imageSY($src_img);

        //next we will calculate the new dimmensions for the thumbnail image
        //the next steps will be taken:
        //  1. calculate the ratio by dividing the old dimmensions with the new ones
        //  2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
        //      and the height will be calculated so the image ratio will not change
        //  3. otherwise we will use the height ratio for the image
        // as a result, only one of the dimmensions will be from the fixed ones
        $ratio1=$old_x/$new_w;
        $ratio2=$old_y/$new_h;
        if($ratio1>$ratio2)
        {
          $thumb_w=$new_w;
          $thumb_h=$old_y/$ratio1;
        }
        else
        {
          $thumb_h=$new_h;
          $thumb_w=$old_x/$ratio2;
        }

        // we create a new image with the new dimmensions
        $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

        // resize the big image to the new created one
        imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

        // output the created image to the file. Now we will have the thumbnail into the file named by $filename
        if(!strcmp("png",$ext))
          imagepng($dst_img,$filename);
        else
          imagejpeg($dst_img,$filename);

          //destroys source and destination images.
        imagedestroy($dst_img);
        imagedestroy($src_img);
    }

       // This function reads the extension of the file.
       // It is used to determine if the file is an image by checking the extension.
       function getExtension($str)
       {
           $i = strrpos($str,".");
           if (!$i) { return ""; }
           $l = strlen($str) - $i;
           $ext = substr($str,$i+1,$l);
           return $ext;
       }

        //reads the name of the file the user submitted for uploading
       $image=$_FILES[$fileElementName]['name'];

    // if it is not empty
    if ($image)
    {
        // get the original name of the file from the clients machine
        $filename = stripslashes($_FILES[$fileElementName]['name']);

        // get the extension of the file in a lower case format
        $extension = getExtension($filename);
        $extension = strtolower($extension);
        // if it is not a known extension, we will suppose it is an error, print an error message
        //and will not upload the file, otherwise we continue
        if (($extension != "jpg")  && ($extension != "jpeg") && ($extension != "png"))
        {
            $error .= 'Unknown extension!';
            $errors=1;
        }
        else
        {
            // get the size of the image in bytes
            // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which
            //the uploaded file was stored on the server
            $size=getimagesize($_FILES[$fileElementName]['tmp_name']);
            $sizekb=filesize($_FILES[$fileElementName]['tmp_name']);

            //compare the size with the maxim size we defined and print error if bigger
            if ($sizekb > MAX_SIZE*1024)
            {
                $error .= 'You have exceeded the size limit!';
                $errors=1;
            }
            else {

            //we will give an unique name, for example the time in unix time format
            $image_name=time();

            //the new name will be containing the full path where will be stored (images folder)
            $master_name= $img_base_dir . 'temp/masters/' . $image_name . '.' .$extension;
            $copied = copy($_FILES[$fileElementName]['tmp_name'], $master_name);

            //we verify if the image has been uploaded, and print error instead
            if (!$copied)
            {
                $error .= 'Copy unsuccessfull!';
                $errors=1;
            }
            else
            {
                // the new thumbnail image will be placed in images/thumbs/ folder
                $thumb_name= $img_base_dir . 'temp/thumbs/'.$image_name .'_350.'.$extension;
                // call the function that will create the thumbnail. The function will get as parameters
                //the image name, the thumbnail name and the width and height desired for the thumbnail
                $thumb=make_thumb($master_name,$thumb_name,WIDTH,HEIGHT);
            }}
        }
    }


      //--------- END SECOND SCRIPT --------------------------------------------------------------------

      //return variables to javascript
      $filename = $_FILES[$fileElementName]['name'];
      $filesize = $sizekb;
      $fileloc = $thumb_name;
      //for security reason, we force to remove all uploaded file
      @unlink($_FILES[$fileElementName]);

      //image dimensions
      $masterWH = getimagesize($master_name);
      $masterW = $masterWH[0];
      $masterH = $masterWH[1];
      $thumbWH = getimagesize($thumb_name);
      $thumbW = $thumbWH[0];
      $thumbH = $thumbWH[1];
    }

    $ret = array(
        "master" => array(
            "orig_name" => $filename,
            "img_src" => str_replace("../", "", $master_name),
            "size" => round((filesize($master_name)/1000), 0) . 'kb',
            'h' => $masterH,
            'w' => $masterW
        ),
        "thumb" => array(
            "img_src" => str_replace("../", "", $thumb_name), //tweak return path of img
            "size" => round((filesize($thumb_name)/1000), 0) . 'kb',
            'h' => $thumbH,
            'w' => $thumbW
        )
    );

    if ($error !== "")
    {
        $ret["error"] = $error;
    }

    echo json_encode($ret);

?>

mySQLi Login Script

Basic mySQLi Login Script which includes JavaScript for AJAX login, PHP login script, PHP logout script.

Login form

Login success

Login error

Demo

login.php

Grabs $_POST vars, escapes, creates new mySQLi connection. Logs the user in and stores PHP session with project name. Returns JSON to front end with success or incorrect login.

<?php

/**
* Escape a variable for MySQL
* @param var - the variable.  Only null, booleans, integers, floats and strings.  Everything else will error out
**/

function escape($db_con, &$var)
{
    if (!isset($var))
    {
        return 'NULL';
    }
    elseif (is_string($var))
    {
        return "'" . $db_con->real_escape_string($var) . "'";
    }
    elseif (is_int($var) || is_float($var))
    {
        return "'" . $var . "'";
    }
    elseif (is_bool($var))
    {
        return ($var) ? "'1'" : "'0'";
    }
    else
    {
        throw new Exception("Type of $var not accepted by escape");
    }
}

if (!isset($_SESSION)) {
  session_start();
}
// echo $_SESSION['samdeering']['uid'];

//login script
if (!isset($_SESSION['projectname']['uid']))
{
    //check login
    if (isset($_POST['username']) && isset($_POST['password']))
    {
        //get vars
        $username = $_POST['username'];
        $password = $_POST['password'];

        //settings
        $settings = array(
            'host' => 'localhost',
            'user' => 'root',
            'password' => '',
            'database' => 'db'
        );

        //connect to db
        $db_con = new mysqli($settings['host'], $settings['user'], $settings['password'], $settings['database']);
        if ($db_con->connect_errno)
        {
            die("Database connection error: " . $db_con->connect_error);
        }

        //get password
        $query = "SELECT uPwd from users WHERE uAcc = ".escape($db_con, $username).";";
        $results = $db_con->query($query);
        $results = $results->fetch_assoc();
        // var_dump($results['uPwd']);
        // var_dump(md5($password));

        //check password
        if ($results['uPwd'] == md5($password))
        {
            $_SESSION['projectname']['uid'] = $username;
            $data = array(
                "result" => true,
                "msg" => "<div id='user'><p>Logged in as ".$username." |  <a href='/php/logout.php'>Logout</a></p></div>"
            );
            echo json_encode($data);
            exit();
        }
        else
        {
            $data = array(
                "result" => false,
                "msg" => "<div id='user'><p class='error'>Username or password incorrect.</p></div>"
            );
            echo json_encode($data);
            exit();
        }
    }

    echo "You must be logged in to view this page. <a href='http://".$_SERVER['SERVER_NAME']."'>Login</a>";
    exit();
}
?>

logout.php

Clears the session for the projectname only. Redirects back to home.

<?php
    if (!isset($_SESSION)) {
      session_start();
    }
    unset($_SESSION['projectname']);
    header("Location: http://" . $_SERVER['SERVER_NAME']);
?>

script.js

Processes a form with username and password. Sends to backend login script, reads json returned to display login details or incorrect login.

//ajax login script
$(function()
{
    $(document).ready(function()
    {
          $('#login-submit').on('click', function(e)
          {
              e.preventDefault();
              var formData = $('#login-form').serialize();
              // console.log(formData);

              $formLoading = $('#login-form .loading');
              $formLoading.show();
              $.ajax(
              {
                  type: "POST",
                  url: 'login.php',
                  dataType: "json",
                  data: formData,
                  success: function(ret)
                  {
                      // console.dir(ret);
                      if(ret.result)
                      {
                          $('#login-form').after(ret.msg).fadeOut(500, function()
                          {
                              $('#user').fadeIn(500);
                          })
                      }
                      else
                      {
                          $('#login-form').after(ret.msg).fadeOut(500, function()
                          {
                              $('#user').fadeIn(500);
                              setTimeout(function()
                              {
                                 $('#user').fadeOut(500, function()
                                 {
                                    $('#login-form').fadeIn(500);
                                 });
                              }, 1500);
                          })
                      }
                  },
                  error: function(xhr, textStatus, errorThrown)
                  {
                      console.log(xhr, textStatus, errorThrown + 'error');
                      return false;
                  },
                  complete: function()
                  {
                      $formLoading.hide(); //hide loading image
                  }
              });

          });
    });

});

HTML Form

This is a modified version of the HTML form provided by Bootstrap.

<form class="navbar-form pull-right" id="login-form">
     <input type="text" name="username" placeholder="username" class="span2">
     <input type="password" name="password" placeholder="password" class="span2">
     <button class="btn" type="submit" id="login-submit">Sign in</button>
</form>

Using Putty to connect to EC2

This is very basic but how you can use Putty to connect to EC2 to run linux commands. you can also Use FileZila FTP to connect to EC2 if you prefer using an FTP client to transfer files. For the connection you will need a PEM file (you get one when you setup your security group on EC2).

Prerequisites

Download Putty (the client).
Download Putty Key Gen (converts your PEM to PPK).

1. Create your PPK file

Use Putty Key Gen to create your PPK file.

Menu > Conversions > Import Key

Select your PEM file

Click generate and move your mouse over the area.

Click Save private key.

Select yes to save without a passphrase.

Enter a name and save you key.

2. Connect to EC2 using Putty

Open Putty > Connection > SSH > Auth – add your PPK file.

Session > enter server IP (elastic IP or public DNS or server name) click open.

Enter bitnami as the username and your in!

Howto use FileZilla with AWS EC2 Bitnami AMI

This is how you can setup FileZilla FTP client to connect to AWS EC2 Bitnami AMI instance volume to transfer files to/from as you would do to any other normal web server using an FTP client. When you setup your security group on EC2 you will get a security file called a PEM file. This file allows you to authenticate when connecting to your EC2 instance. As predominantly a windows user there are two ways I use this file to connect to my site in the cloud. 1. Using Putty to connect to EC2 and 2. Using FileZila FTP to connect to EC2.

Step by step setup

Menu > Edit > Settings

Connection > FTP > select passive
Connection > FTP > select allow fail back to other transfer mode

Connection > FTP > Active Mode > select ask your operating system for the external ip address

Connection > SFTP > click add keyfile

Select your .PEM file.

Click yes to convert to PPK (private key).

Enter a name for the file and click save.

Your private key should now appear in the list. Click OK.

Now you can add your new site in the Site Manager as normal and it will connect to your instance (if your using Bitnami AMI then the username is bitnami and no password is required as you key provides the authentication).

Here’s some more connection screenshots to help those who are really struggling!

Your wordpress installation folder should be located here: /opt/bitnami/apps/wordpress/wordpress/htdocs/.

More important tips

Tip: Change FileZilla FTP to passive mode to make uploads faster.

Edit > settings > FTP > passive mode.

Tip: Don’t lose your .pem file, keep it safe.

Tip: Check that the server has install VSFTP (“Very Secure FTP Daemon”) is the default FTP server. Should be installed by default but worth a check.

# sudo apt-get install vsftpd

How to Setup Apache monitoring package MONIT

This is how to How to Setup Apache monitoring package MONIT on bitnami AWS EC2. Once it’s done you’ll be able to actively monitor your server memory usage.

To install it run this command:

sudo apt-get install monit

To change the config file:

sudo vim /etc/monit/monitrc

Enable port 2812 by adding the port to AWS EC2 2812 port to your security group.

Start monit services with this command:

sudo /etc/init.d/monit start
or
sudo service monit start

To check you monit file synax:

monit -t
monit summary

You should see this if it’s running correctly.

To access the GUI go to:

domain.com/2812 ie- http://jquery4u.com:2812/
enter username and password

Enable more services in config to monitor mySQL and others.

To find out where your httpd file is located:

//should be /opt/bitnami/apache/bin/httpd
find / -name httpd

When a resource limit is matched you will see something like this (and also emailed if your alert is set).

PHP Output Table with Where Condition

Simple PHP code snippet to output table with where condition, outputs table headings, and fields as rows in a HTML table.

  //OUTPUT TABLE
  function output_table($tablename,$condition="")
  {
    //PRINT FIELD PROPERTIES FROM DATABASE
    $sql = "SHOW COLUMNS FROM tablename";
    $headings = $this->execute_query($sql);
    // echo "<pre>";
    // print_r($headings);
    // echo "</pre>";
    // foreach($headings as $i => $value) {
    //    echo $value["Field"];
    // }

    $sql = "SELECT * FROM ".$tablename . ' ' . $condition; // WHERE id = '{$category}'";
    $table = $this->execute_query($sql);

    echo '<table>';
    foreach($headings as $i => $value) {
       echo '<th>' . $value["Field"] . '</th>';
    }
    foreach ($table as $row) {
        echo '<tr>';
        foreach ($row as $field) {
            echo '<td>'.$field.'</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
  }