Doc to PDF conversion | Laravel


Converting a Doc file to PDF has some techniques. Here I have followed a quickest and easiest one to make this happen.

Install LibreOffice on OS


sudo apt-get --no-install-recommends install -y libreoffice

Then just write a code like below sample to make this conversion



$path = storage_path() . "/app/public/documents/test.doc";

$savePath = storage_path() . "/app/public/documents";

//LibreOffice shell command to convert doc to pdf
        
$command = "export HOME=/tmp && libreoffice --headless --convert-to pdf $path --outdir $savePath";
        
$output = shell_exec ($command);  

echo $output;


How to POST values using cURL request and get the response


Make your POST variable first:


$params = array(
 'first_name' => 'Ziyed',
 'last_name' => 'Uddin',
 'email' => 'test@email.com'	
);

Write a function to prepare your cURL post variable:


private function build_params($params) {
 $return = array();
 foreach ($params as $key => $value) {
  $return[] = $key . '=' . urlencode($value);
 }
 return implode('&', $return);
}

Now define your cURL connection, send the request and get the response


$ch = curl_init(); // Create a cURL instance
curl_setopt($ch, CURLOPT_URL, 'http://www.yourwebsiteurl.com'); //Set your cURL POST url
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->build_params($params)); //Prepare your cURL POST variable
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch); //Execute cURL Request and Get the Response
curl_close($ch); // Close cURL instance

Unicode font like arabic or others displaying technique on webpage from mysql database at CakePHP or raw php


1. Make Sure that your database has UTF8 Character set, Run the following code

 ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 

2. Make Sure that your table has UTF8 Character set and Collate utf8_unicode_ci or utf8_general_ci

 ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 

3. Make Sure that your webpage has utf8 enable

 <meta charset="UTF-8">
 

4. Set utf8 before any mysql query in raw php

 mysql_query("SET NAMES utf8");
 

At CakePHP you can set this very easily at database config file:

Remove the comment line before ‘encoding’ and make this line available for execution.

 
 public $default = array(
	'datasource' => 'Database/Mysql',
	'persistent' => false,
	'host' => 'localhost',
	'login' => 'root',
	'password' => '',
	'database' => 'cake278',
	'prefix' => '',
	//'encoding' => 'utf8',
 );
 
 

Sorting a multi dimentional associative array with a array key value


Here we will sort the following multi dimentional associative array with comment_date key in DESC order.

Before start your sorting, your data may look like:


 $comments = Array
   (
		[0] => Array
			(
				[id] => 10				
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:52:10
			)

		[1] => Array
			(
				[id] => 8				
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:49:28
			)

		[2] => Array
			(
				[id] => 51
				[customer_id] => 2047080
				[comment] => This is a test comment.
				[comment_date] => 2015-11-10 10:23:28
			)

		[3] => Array
			(
				[id] => 43437
				[customer_id] => 1
				[comment] => This is a test comment.
				[comment_date] => 2011-12-22 13:33:05
			)

	)


So you need a php function that will manage your sorting list perfectly.


	function multi_sort($array, $key, $sort_flags = SORT_REGULAR, $order = SORT_DESC) {
        if (is_array($array) && count($array) > 0) {
            if (!empty($key)) {
                $mapping = array();
                foreach ($array as $k => $v) {
                    $sort_key = '';
                    if (!is_array($key)) {
                        $sort_key = $v[$key];
                    } else {
                        foreach ($key as $key_key) {
                            $sort_key .= $v[$key_key];
                        }
                    }
                    $mapping[$k] = $sort_key;
                }
                switch ($order) {
                    case SORT_ASC:
                        asort($mapping, $sort_flags);
                        break;
                    case SORT_DESC:
                        arsort($mapping, $sort_flags);
                        break;
                }
                $sorted = array();
                foreach ($mapping as $k => $v) {
                    $sorted[] = $array[$k];
                }
                return $sorted;
            }
        }
        return $array;
     }

Now time to call the function from your code to manage your sorting.


	
    $sorted_comments = $this->multi_sort($comments, array('comment_date'));   
	

After Sorting with multi_sort function your data will look like:


	Array
	(
		[0] => Array
			(
				[id] => 51
				[customer_id] => 2047080
				[comment] => This is a test comment.
				[comment_date] => 2015-11-10 10:23:28
			)

		[1] => Array
			(
				[id] => 43437
				[customer_id] => 1
				[comment] => This is a test comment.
				[comment_date] => 2011-12-22 13:33:05
			)

		[2] => Array
			(
				[id] => 10
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:52:10
			)

		[3] => Array
			(
				[id] => 8
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:49:28
			)

	)

php class to manage image upload, resize, crop


Save the class as “image_manage.php” under project root folder or where ever you want.


<?php

class image_manipulation {

    public $relative_path_to_point_img_folder;   //Relative folder path of image going to be uploaded. example "./upload/"
    public $absolute_path_to_point_img_folder;   //Absolute folder path of image going to be uploaded. example "http://www.mysite.com/upload/"
    public $fileFieldName;                       //Image File input field name
    public $allowedMimeTypes = array(
        'jpg|jpeg|jpe' => 'image/jpeg',
        'gif' => 'image/gif',
        'png' => 'image/png',
        'bmp' => 'image/bmp',
        'tif|tiff' => 'image/tiff',
        'ico' => 'image/x-icon'
    );

    /*
     *  constructor takes three arguments
     *  1st: relative path of image folder.  example "./upload/"
     *  2nd: absolute path of image folder.  example "http://www.mysite.com/upload/"
     *  3rd: image file input field name
     */    
    public function __construct($img_folder_relative_path, $img_folder_absolute_path, $img_file_field_name) {
        $this->relative_path_to_point_img_folder = $img_folder_relative_path;
        $this->absolute_path_to_point_img_folder = $img_folder_absolute_path;
        $this->fileFieldName = $img_file_field_name;
    }

    /*
     * validateType function used to check image type and error occured
     * @param
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: if ture return image type otherwise false
     */
    public function validateType($data) {
        if (isset($data[$this->fileFieldName]['type']) && $data[$this->fileFieldName]['error'] == 0) {
            return in_array($data[$this->fileFieldName]['type'], $this->allowedMimeTypes);
        }
        return false;
    }

    /*
     * validateUpload function used to check image upload error and size error
     * @param
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: true if no error occure otherwise return false
     */
    public function validateUpload($data) {
        if ($data[$this->fileFieldName]['error'] != 0) {
            return $this->uploadError[$data[$this->fileFieldName]['error']];
        }
        if ($data[$this->fileFieldName]['size'] == 0) {
            return false;
        }
        return true;
    }

    /**
     * @param array $fileInfo
     * array index
     * location: relative path to image file
     * width (int): width to resize
     * height (int): height to resize
     * propotional (bool): resize image ratio and original image ration will be same
     * direction (string x): 
     * crop (stirng zoom-in): zoom in crop image would be resized and crop the unmached part
     * quality (int 0~100): quality of the resized image
     * @return: new image url with absolute path
     */
    public function resize($fileInfo) {
        if (!isset($fileInfo['location'])) {
            return false;
        }

        //if not width and height provided return the original file
        if ((!isset($fileInfo['width']) || !$fileInfo['width']) && (!isset($fileInfo['height']) || !$fileInfo['height'])) {
            return $fileInfo['location'];
        }

        //load the image
        $imgInfo = getimagesize($fileInfo['location']);
        $originalWidth = $imgInfo[0];
        $originalHeight = $imgInfo[1];
        $type = $imgInfo[2];
        $propotional = isset($fileInfo['propotional']) ? $fileInfo['propotional'] : false;
        $propotionDirection = isset($fileInfo['direction']) ? $fileInfo['direction'] : 'x';
        $crop = isset($fileInfo['crop']) ? $fileInfo['crop'] : 'zoom-in';
        $quality = isset($fileInfo['quality']) ? $fileInfo['quality'] : 90;
        $srcX = 0;
        $srcY = 0;
        $dstX = 0;
        $dstY = 0;

        //set vars
        $originalRatio = $originalWidth / $originalHeight;
        $resizedWidth = isset($fileInfo['width']) ? $fileInfo['width'] : 0;
        $resizedHeight = isset($fileInfo['height']) ? $fileInfo['height'] : 0;
        if ($resizedWidth == 0) {
            $resizedWidth = round($originalRatio * $resizedHeight);
        }
        if ($resizedHeight == 0) {
            $resizedHeight = round($resizedWidth / $originalRatio);
        }

        if ($propotional) {
            if ($propotionDirection == 'x') {
                $resizedHeight = round($resizedWidth / $originalRatio);
            } else {
                $resizedWidth = round($originalRatio * $resizedHeight);
            }

            $resizedImageName = $resizedWidth . 'X' . $resizedHeight;
        } else {
            $resizedImageName = $resizedWidth . 'X' . $resizedHeight;

            $newRatio = $resizedWidth / $resizedHeight;

            if ($newRatio > $originalRatio) {
                if ($crop == 'zoom-in') {
                    $newWidth = $originalWidth;
                    $newHeight = $newWidth / $newRatio;
                    $resizedImageName .= '_w_zoom_in_';
                } else {
                    $newHeight = $originalHeight;
                    $newWidth = $newRatio * $newHeight;
                    $dstX = ($resizedWidth - $resizedHeight * $originalRatio) / 2;

                    $resizedImageName .= '_w_zoom_out_';
                }
            } else {
                if ($crop == 'zoom-in') {
                    $newHeight = $originalHeight;
                    $newWidth = $newRatio * $newHeight;
                    $srcX = $originalWidth / 2 - $newWidth / 2;

                    $resizedImageName .= '_h_zoom_in_';
                } else {
                    $newWidth = $originalWidth;
                    $newHeight = $newWidth / $newRatio;
                    $dstY = ($resizedHeight - ($resizedWidth / $originalRatio)) / 2;

                    $resizedImageName .= '_w_zoom_out_';
                }
            }

            $originalHeight = $newHeight;
            $originalWidth = $newWidth;
        }


        $resizedImageName .= $quality . '_' . str_replace(' ', '_', strtolower($fileInfo['file_name']));
        $destination = $this->relative_path_to_point_img_folder . $resizedImageName;
        $image_return_url = $this->absolute_path_to_point_img_folder . $resizedImageName;

        //check if file already exits
        if (file_exists($destination)) {
            return $destination;
        }

        $canvas = imagecreatetruecolor($resizedWidth, $resizedHeight);

        //transparency staff
        if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {
            //not working need to fix
            //imagefill($canvas, 0, 0, IMG_COLOR_TRANSPARENT);
            //imagesavealpha($canvas, true);
            //imagealphablending($canvas, true);
        }

        switch ($type) {
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($fileInfo['location']);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($fileInfo['location']);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($fileInfo['location']);
                break;
            default:
                return false;
        }
        imagecopyresampled($canvas, $image, $dstX, $dstY, $srcX, $srcY, $resizedWidth, $resizedHeight, $originalWidth, $originalHeight);


        switch ($type) {
            case IMAGETYPE_GIF:
                imagegif($canvas, $destination);
                break;
            case IMAGETYPE_JPEG:
                imagejpeg($canvas, $destination, $quality);
                break;
            case IMAGETYPE_PNG:
                $quality = 9 - (int) ((0.9 * $quality) / 10.0);
                imagepng($canvas, $destination, $quality);
                break;
            default:
                return false;
        }

        //return $destination;
        return $image_return_url;
    }

    /**
     * @param 
     * $filename: only image file name going to be croped
     * x1 (int): x1 coordinate value
     * y1 (int): y1 coordinate value
     * x4 (int): x4 coordinate value
     * y4 (int): y4 coordinate value
     * @return: new image url with absolute path
     */
    public function crop($filename, $x1, $y1, $x4, $y4) {
        
        $filename_location = $this->relative_path_to_point_img_folder . $filename;
        
        if (!file_exists($filename_location)) {
            return false;
        }
                
        $imgInfo = getimagesize($filename_location);
        $originalWidth = $imgInfo[0];
        $originalHeight = $imgInfo[1];
        $type = $imgInfo[2];
        $new_width = ( $x4 - $x1 );
        $new_height = ( $y4 - $y1 );
        
        $cropedImageName = $x1.$y1."_".$new_width."X".$new_height."_".$filename;
        $destination = $this->relative_path_to_point_img_folder . $cropedImageName;
        $image_return_url = $this->absolute_path_to_point_img_folder . $cropedImageName;

        //check if file already exits
        if (file_exists($destination)) {
            return $image_return_url;
        }

        $canvas = imagecreatetruecolor($new_width, $new_height);
        
        switch ($type) {
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($filename_location);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($filename_location);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($filename_location);
                break;
            default:
                return false;
        }        
        
        imagecopyresampled($canvas, $image, 0, 0, $x1, $y1, $new_width, $new_height, $new_width, $new_height);
        
        switch ($type) {
            case IMAGETYPE_GIF:
                imagegif($canvas, $destination);
                break;
            case IMAGETYPE_JPEG:
                $quality = 95;
                imagejpeg($canvas, $destination, $quality);
                break;
            case IMAGETYPE_PNG:
                $quality = 9 - (int) ((0.9 * $quality) / 10.0);
                imagepng($canvas, $destination, $quality);
                break;
            default:
                return false;
        }
        
        return $image_return_url;
    }

    /**
     * @param 
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: if uploaded successfully its return an array with values otherwise it return empty array
     */
    public function upload($data) {
        $original_file_name = $data[$this->fileFieldName]['name'];
        $new_file_name = time() . $original_file_name;
        $image_actual_file_location = $this->relative_path_to_point_img_folder . $new_file_name;
        $image_return_url = $this->absolute_path_to_point_img_folder . $new_file_name;
        $file_temp_name = $data[$this->fileFieldName]['tmp_name'];
        $arr = array();
        if ($this->validateType($data)) {
            if (move_uploaded_file($file_temp_name, $image_actual_file_location)) {
                $arr = array(
                    'original_file_name' => $original_file_name,
                    'new_file_name' => $new_file_name,
                    'image_relative_url' => $image_actual_file_location,
                    'image_absolute_url' => $image_return_url
                );
                return $arr;
            } else {
                return $arr;
            }
        } else {
            return $arr;
        }
    }

    /**
     * @param 
     * $img_name: Image name going to be removed completely.
     * @return: if removed it will return true otherwise false.
     */
    public function remove($img_name){        
        $destination = $this->relative_path_to_point_img_folder . $img_name;        
        if (!file_exists($destination)) {
            $this->error = 'File not found';
            return false;
        }        
        $res = unlink($destination);
        return $res;        
    }

}

?>

To make it workable at view please check the below how i am calling:


<?php
//include the image_manage.php class by defining its actual location
include './image_manage.php';  

//create an object of image_manipulation class
$image = new image_manipulation('./upload/', 'http://www.mysite.com/upload/', 'fileToUpload');
$url = $image->crop('mytest_image.jpg', 100, 50, 700, 400);

?>


Basic php crud operation to manage mysql database using pdo




<?php

class db extends PDO {
    
    public $pid = 'id'; // $pid is a primaty key of a table

    function __construct($dsn, $username, $passwd, $options = array()) {
        parent::__construct($dsn, $username, $passwd, $options);
    }

    /*
     * Function 'get_data_by_id' return single table row by an id
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Row id to get the result, id must be a primary key of a table
     * 3rd:  Return type 'object' or 'array', Default is object
     * Returns the row if found
     * 
     *  $row = $db->get_data_by_id('images', 3, 'array');
     * 
     */
    function get_data_by_id($tablename, $id, $output_type = 'object') {
        $stmt = $this->prepare("SELECT * FROM $tablename WHERE $this->pid=?");
        $stmt->execute(array($id));
        if ($output_type == 'object') {
            $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
        } else {
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        return $rows;
    }
    
    

    /*
     * Function 'get_all_datas 'return table rows by any condition
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take associative array of condition. example:  array('id'=>3)
     * 3rd:  Return type 'object' or 'array'. Default is object
     * Returns the rows if found
     * 
     *  $param = array(
     *     'id' => 3,
     *  );
     *  $row = $db->get_all_datas('images', $param, 'array');
     * 
     */
    function get_all_datas($tablename, $param = array(), $output_type = 'object') {
        if (!empty($param)) {
            $keys = '';
            $values_ = array();
            $i = 1;
            foreach ($param as $key => $value) {
                if (!empty($key)) {
                    ($i == 1) ? $keys = $keys . "$key=?" : $keys = $keys . "AND $key=?";
                }
                $i++;
            }
            $values_ = array_values($param);
            $stmt = $this->prepare("SELECT * FROM $tablename WHERE $keys");
            $stmt->execute($values_);
        } else {
            $stmt = $this->prepare("SELECT * FROM $tablename");
            $stmt->execute();
        }

        if ($output_type == 'object') {
            $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
        } else {
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        return $rows;
    }
    

    /*
     * Function 'insert' insert values to a table by condition
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take associative array of values, array key must be same as table column name. example:  array('city'=> 'Dhaka', 'name'=>'Mr. Jonson').
     * Returns last inserted id of a table.
     * 
     *  $param = array(
     *     'caption' => 'Edited',
     *     'original_file_name' => 'bangladehbeautyful.png',
     *     'file_name' => '54458888beautyful.png'
     *  );
     *  $last_inserted_id = $db->insert('images', $param);
     * 
     */
    function insert($tablename, $param) {
        
        $keys = '';
        $values = '';
        $values_ = array();
        $i = 1;
        foreach ($param as $key => $value) {
            if (!empty($key)) {
                ($i == 1) ? $keys = $keys . "`$key`" : $keys = $keys . ", `$key`";
                ($i == 1) ? $values = $values . "?" : $values = $values . ", ?";
            }
            $i++;
        }
        $values_ = array_values($param);
        $sql = "INSERT INTO $tablename($keys) VALUES($values)";
        $stmt = $this->prepare($sql);
        $stmt->execute($values_);
        return $this->lastInsertId();
    }
    

    /*
     * Function 'update' update values to a table by id
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take an id of a table, id must be a primary key of a table.
     * 3rd:  Take associative array of values, array key must be same as table column name. example:  array('city'=>'Dhaka', 'name'=>'Mr. Jonson').
     * Returns the counter how much row updated.
     * 
     *  $param = array(
     *     'caption' => 'Edited',
     *     'original_file_name' => 'bangladehbeautyful.png',
     *     'file_name' => '54458888beautyful.png'
     *  );
     *  $row_effected = $db->update('images', 2, $param);
     * 
     */
    function update($tablename, $id, $param) {
        $keys = '';
        $values = '';
        $values_ = array();
        $i = 1;
        foreach ($param as $key => $value) {
            if (!empty($key)) {
                ($i == 1) ? $keys = $keys . "$key=?" : $keys = $keys . ", $key=?";
            }
            $i++;
        }
        $values_ = array_values($param);
        array_push($values_, $id);
        $sql = "UPDATE $tablename SET $keys WHERE $this->pid=?";
        $stmt = $this->prepare($sql);
        $stmt->execute($values_);
        return $stmt->rowCount();
    }
    
    /*
     * Function 'delete' delete the table row by id
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take an id of a table, id must be a primary key of a table.
     * Returns the counter how much row updated.
     * 
     *  $row_effected = $db->delete('images', 2);
     * 
     */
    function delete($tablename, $id) {
        $sql = "DELETE FROM $tablename WHERE $this->pid=:id";
        $stmt = $this->prepare($sql);
        $stmt->bindValue(':id', $id, PDO::PARAM_STR);
        $stmt->execute();
        return $stmt->rowCount();
    }

}

$HostName = 'localhost';
$dbName = 'dbname';
$username = 'root';
$password = '';


$db = new db("mysql:host=$HostName;dbname=$dbName;charset=utf8", $username, $password);
//$db->id = 'id';

?>


Mailchimp integration with php


Please Download MCAPI class from git url given below

https://github.com/ziyed/mailchimp_php_class.git

Or

http://apidocs.mailchimp.com/api/downloads/#php

How to use mailchimp php class and manipulate user data.


<?php 

  require_once 'MCAPI.php';

  // grab an API Key from http://admin.mailchimp.com/account/api/
  $api = new MCAPI($apiKey);

  // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
  // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
  $list_id = "58d58d54d5s";
                    
  $merge_vars = Array(                       
	'FNAME' => 'First Name'
  );

  if ($api->listSubscribe($list_id, $useremail, $merge_vars) === true) {
	// It worked!
  } else {
	// An error ocurred, return error message
  }

?>

Capture image and upload to server using PhoneGap


Client Side Script

PhoneGap Capture Image API: Capture Image PhoneGap API



//Camera Section
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);

// PhoneGap is ready
function onDeviceReady() {}

// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {    
    uploadFile(mediaFiles[0]);
}

// Called if something bad happens.
//
function captureError(error) {
    var msg = 'An error occurred during capture: ' + error.code;
    navigator.notification.alert(msg, null, 'Uh oh!');
}

// A button will call this function
//
function captureImage() {
    // Launch device camera application,
    // allowing user to capture only one image by {limit: 1}
    navigator.device.capture.captureImage(captureSuccess, captureError, { limit: 1 });
}

// Upload files to server
function uploadFile(mediaFile) {
    path = mediaFile.fullPath;
    name = mediaFile.name;
    
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=mediaFile.name;
    options.mimeType="image/jpeg";

    var params = new Object();
    params.fullpath = path;
    params.name = name;

    options.params = params;
    options.chunkedMode = false;
    
    var ft = new FileTransfer();
    ft.upload( path, "http://www.serverurl.com/image_upload",
        function(result) {
			//upload successful            
        },
        function(error) {
            //upload unsuccessful, error occured while upload. 
        },
        options
        );
}

Server Side Code


    $new_image_name = $_FILES["file"]["name"];
    move_uploaded_file($_FILES["file"]["tmp_name"], WWW_ROOT . "/products/" . $new_image_name);

Sending email with uploaded attachment using raw php



$upload_path = dirname(__FILE__) . '/uploads/';
if (is_dir($upload_path) === false)
    mkdir($upload_path, 0777);
    $to = 'test@gmail.com';

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path . $filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: " . $from_name . " \r\n";
    $header .= "Reply-To: " . $replyto . "\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--" . $uid . "\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message . "\r\n\r\n";
    $header .= "--" . $uid . "\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n";
    $header .= $content . "\r\n\r\n";
    $header .= "--" . $uid . "--";
    if (mail($mailto, $subject, "", $header)) {
        echo"success"; // header('location: /?success');
    } else {
        echo"No";
        //header('location: /?success');
    }
}

//end mail_attachment

function mail_plain($mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $header = "From: " . $from_name . " \r\n";
    $header .= "Reply-To: " . $replyto . "\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";

   if (mail($mailto, $subject, $message, $header)) {
        echo"success"; //header('location: /?success');
    } else {
        echo"No"; //header('location: /?success');
    }
}

//end function mail_plain

if (!empty($_FILES['resume']['name'])) {
    $filename = time() . '_' . $_FILES['resume']['name'];

    if (move_uploaded_file($_FILES['resume']['tmp_name'], $upload_path . $filename)) {
        $attachment = $filename;
    }
}

$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // not required
$comments = $_POST['message']; // required

$subject = "Email Subject";
$from = $email_from; //$_POST['reply_email'];

$message  = "Form details below.\n\n";
$message .= "Name: " . $name . "\n";
$message .= "Email: " . $email_from. "\n";
$message .= "Phone: " . $phone . "\n";
$message .= "Message: " . $comments . "\n";
$from_name = $name;

if (isset($attachment)) {
    //echo $return="Attach";
    mail_attachment($attachment, $upload_path, $to, $from, $from_name, $from, $subject, $message);
} else {
    //echo $return="No Attach";
    mail_plain($to, $from, $from_name, $from, $subject, $message);
}

header('Location: test.html');