Saturday, May 12, 2018

Download file using - PHP

            $backup = "Your file data";

            $folder = 'assets/db/';

            if (!is_dir($folder))
                mkdir($folder, 0755, true);

            $date = date('m-d-Y-H-i-s', time());
            $file_name = "filename-" . $date . '.sql';
            $file_url = $folder . $file_name;

            $handle = fopen($file_url, 'w+');

            fwrite($handle, $backup);
            fclose($handle);

            header('Content-Type: application/octet-stream');
            header("Content-Transfer-Encoding: Binary");
            header("Content-disposition: attachment; filename=\"" . $file_name . "\"");
            readfile($file_url);

Pagination in codeigniter

public function select_data() {
        $this->config->load('pagination');
        $config = $this->config->item('pagination_config');

        $offset = $this->input->post("p") ? $this->input->post("p") : 1;
        $per_page = $this->input->post("pp") ? $this->input->post("pp") : 10;

        $this->uri->assign_segments(3, $offset);

        $config['base_url'] = site_url('account/select_data');
        $config['total_rows'] = $this->account_model->count_row();
        $config['per_page'] = $per_page;
        $config['uri_segment'] = "3";

        $start = ($offset - 1) * $config['per_page'];

        $this->pagination->initialize($config);

        $data["pagination"] = $this->pagination->create_links();
        $data["total"] = $config['total_rows'];
        $data['start'] = $data["total"] ? $start + 1 : 0;
        $data['end'] = (($start + $config['per_page']) < $config['total_rows']) ? $start + $config['per_page'] : $config['total_rows'];
        $data['account'] = $this->account_model->get_all_account($config['per_page'], $start);
//        $data = $this->account_model->get_account();        
        $this->load->view('account_table', $data);
    }

Image/File Upload Using Ajax

Image Upload HTML

This code shows photo icon in the middle of a preview box and an upload button. On clicking the photo icon a transparent preview of the image will be displayed in the preview box. Then, this image will be uploaded to a folder on clicking the upload button. It shows a window overlay with a loader to represent that the image upload is in progress.
<div class="form-group">
    <label>Logo</label>                               
    <?php $logo = isset($data['logo']) && $data['logo'] ? $data['logo'] : '' ?>
    <div id="uploadImageBox">
        <div id="targetLayer" style="position:relative;display: inline-block">
            <span class="remove_btn <?php echo $logo ? '' : 'hidden'; ?>" onclick="remove_image($(this))">&times;</span>
            <img src="<?php echo $logo ? base_url("assets/upload/customer/$logo") : base_url("assets/admin/img/no_image.jpg"); ?>" style="height:80px; width: 80px;" />
        </div>
        <input type="hidden" name="old_image" id="old_image" value="<?php echo $logo; ?>">
        <input type="hidden" name="remove_image" id="remove_image" value="">
        <div class="icon-choose-image" >
            <input name="userImage" id="userImage" type="file" class="inputFile" onChange="showPreview(this);" />
        </div>
    </div>
    <div class="error text-danger" id='logo_error'></div>
</div>


Uploading Image and Showing Preview using jQuery AJAX
This script contains a jQuery function showPreview(). It will be called when selecting the image file to be uploaded. This function is used to show a transparent preview of the selected image before upload.
<script type="text/javascript">
    var no_img = "<?php echo base_url("assets/admin/img/no_image.jpg"); ?>";
    function showPreview(objFileInput) {
        if (objFileInput.files[0]) {
            var fileReader = new FileReader();
            fileReader.onload = function (e) {
                $("#targetLayer").html('<img src="' + e.target.result + '" width="80px" height="80px" class="upload-preview" />');
                $("#targetLayer").css('opacity', '0.7');
                $(".icon-choose-image").css('opacity', '0.5');
                $("#targetLayer").append('<span class="remove_btn" onclick="remove_image($(this))">&times;</span>');
            }
            fileReader.readAsDataURL(objFileInput.files[0]);
        } else {
            $("#targetLayer").html('<img src="' + no_img + '" width="80px" height="80px" class="upload-preview" />');
        }
    }

    function remove_image(ele) {
        $('#userImage').val('');
        ele.closest('div').find('img').attr('src', no_img);
        ele.closest('#uploadImageBox').find('#remove_image').val(ele.closest('#uploadImageBox').find('#old_image').val());
        ele.closest('#uploadImageBox').find('#old_image').val('');
        ele.remove();
    }
</script>
 On clicking the upload button, it submits the form data to PHP via jQuery AJAX.In PHP code, it uploads the image to the target folder and returns the image HTML as an AJAX response. This AJAX response HTML will be added to the preview box.
<script type="text/javascript">
$(document).ready(function (e) {
 $("#uploadForm").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "upload.php",
   type: "POST",
   data:  new FormData(this),
   beforeSend: function(){$("#body-overlay").show();},
   contentType: false,
   processData:false,
   success: function(data){
           $("#targetLayer").html(data);
           $("#targetLayer").css('opacity','1');
           setInterval(function() {$("#body-overlay").hide(); },500);
   },
   error: function(){
   }          
  });
 }));
});
</script>

CSS

            .remove_btn{
                position: absolute;
                right: 0;
                height: 20px;
                width: 20px;
                background: red;
                text-align: center;
                color: #fff;
                font-size: 15px;
                font-weight: 700;
            }

Controller Code
//upload configuration
$upload_path = FCPATH . 'assets/upload/customer/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
//upload file to directory
if (empty($_FILES['userImage']['name']) || $this->upload->do_upload('userImage')) {
    /*
     * insert file information into the database
     * .......
     */
    $uploadData = $this->upload->data();
    $logo = $uploadData['file_name'];
    $old_image = $this->input->post('old_image') ? $this->input->post('old_image') : '';
    $remove_image = $this->input->post('remove_image') ? $this->input->post('remove_image') : '';
    if ((!empty($logo) && file_exists($upload_path . $old_image)) || ($remove_image && file_exists($upload_path . $remove_image)) ) {
         $old_image  ? @unlink($upload_path.$old_image) : @unlink($upload_path.$remove_image);
    }
   //write hear any database code or anything you need...
} else {
    $result['status'] = 'validation';
    $result['logo'] = $this->upload->display_errors();
}




Friday, May 11, 2018

Database Backup using php Mysql


//Backup Manually
$dbHost = 'localhost';
$dbName = 'billing';
$dbUsername = 'root';
$dbPassword = '';
$tables = '*';
$return = '';
$folder = "db_backup/";

//connect & select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

//get all of the tables
if ($tables == '*') {
    $tables = array();
    $result = $db->query("SHOW TABLES");
    while ($row = $result->fetch_row()) {
        $tables[] = $row[0];
    }
} else {
    $tables = is_array($tables) ? $tables : explode(',', $tables);
}

//loop through the tables
foreach ($tables as $table) {
    $result = $db->query("SELECT * FROM $table");
    $numColumns = $result->field_count;

    $return .= "DROP TABLE IF EXISTS $table;";

    $result2 = $db->query("SHOW CREATE TABLE $table");
    $row2 = $result2->fetch_row();

    $return .= "\n\n" . $row2[1] . ";\n\n";

    for ($i = 0; $i < $numColumns; $i++) {
        while ($row = $result->fetch_row()) {
            $return .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $numColumns; $j++) {
                $row[$j] = addslashes($row[$j]);
                $row[$j] = preg_replace("/\n/", "/\\n/", $row[$j]);
                if (isset($row[$j])) {
                    $return .= '"' . $row[$j] . '"';
                } else {
                    $return .= '""';
                }
                if ($j < ($numColumns - 1)) {
                    $return .= ',';
                }
            }
            $return .= ");\n";
        }
    }

    $return .= "\n\n\n";
}

// Create Backup Folder
if (!is_dir($folder))
    mkdir($folder, 0775, true);
//chmod($folder, 0775);

$date = date('m-d-Y-H-i-s', time());
$filename = $dbName . "_" . $date . ".sql";
$path = $folder . $filename;

//save file
$handle = fopen($path, 'w+');
fwrite($handle, $return);
fclose($handle);

if (file_exists($path)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($path) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($path));
    readfile($path);
//            echo $return;
    exit;
}

NOTE: when you import this database into your phpmyadmin at that time uncheck the Enable foreign key checks 

Wednesday, November 15, 2017

PHP Pagination


HOW to Use:

// Create the pagination object
      $pagination = new pagination($data, (isset($_GET['page']) ? $_GET['page'] : 1), $perpage);
// Decide if the first and last links should show
       $pagination->setShowFirstAndLast(false);
// You can overwrite the default seperator
       $pagination->setMainSeperator('');
// Parse through the pagination class

       $shopPages = $pagination->getResults();

$pageNumbers = '<div class="pagination">' . $pagination->getLinks($_GET) . '</div>';


Class pagination :


class pagination {

    /**
     * Properties array
     * @var array 
     * @access private
     */
    private $_properties = array();

    /**
     * Default configurations
     * @var array 
     * @access public
     */
    public $_defaults = array(
        'page' => 1,
        'perPage' => 10
    );

    /**
     * Constructor
     *
     * @param array $array   Array of results to be paginated
     * @param int   $curPage The current page interger that should used
     * @param int   $perPage The amount of items that should be show per page
     * @return void   
     * @access public 
     */
    public function __construct($array, $curPage = null, $perPage = null) {
        $this->array = $array;
        $this->curPage = ($curPage == null ? $this->defaults['page'] : $curPage);
        $this->perPage = ($perPage == null ? $this->defaults['perPage'] : $perPage);
    }

    /**
     * Global setter
     *
     * Utilises the properties array
     *
     * @param string $name  The name of the property to set
     * @param string $value The value that the property is assigned
     * @return void   
     * @access public 
     */
    public function __set($name, $value) {
        $this->_properties[$name] = $value;
    }

    /**
     * Global getter
     *
     * Takes a param from the properties array if it exists
     *
     * @param string $name The name of the property to get
     * @return mixed Either the property from the internal
     * properties array or false if isn't set
     * @access public 
     */
    public function __get($name) {
        if (array_key_exists($name, $this->_properties)) {
            return $this->_properties[$name];
        }
        return false;
    }

    /**
     * Set the show first and last configuration
     *
     * This will enable the "<< first" and "last >>" style
     * links
     *
     * @param boolean $showFirstAndLast True to show, false to hide.
     * @return void   
     * @access public 
     */
    public function setShowFirstAndLast($showFirstAndLast) {
        $this->_showFirstAndLast = $showFirstAndLast;
    }

    /**
     * Set the main seperator character
     *
     * By default this will implode an empty string
     *
     * @param string $mainSeperator The seperator between the page numbers
     * @return void   
     * @access public 
     */
    public function setMainSeperator($mainSeperator) {
        $this->mainSeperator = $mainSeperator;
    }

    /**
     * Get the result portion from the provided array
     *
     * @return array Reduced array with correct calculated offset
     * @access public
     */
    public function getResults() {
        // Assign the page variable
        if (empty($this->curPage) !== false) {
            $this->page = $this->curPage; // using the get method
        } else {
            $this->page = 1; // if we don't have a page number then assume we are on the first page
        }

        // Take the length of the array
        $this->length = count($this->array);

        // Get the number of pages
        $this->pages = ceil($this->length / $this->perPage);

        // Calculate the starting point
        $this->start = ceil(($this->page - 1) * $this->perPage);

        // return the portion of results
        return array_slice($this->array, $this->start, $this->perPage);
    }

    /**
     * Get the html links for the generated page offset
     *
     * @param array $params A list of parameters (probably get/post) to
     * pass around with each request
     * @return mixed  Return description (if any) ...
     * @access public
     */
    public function getLinks($params = array()) {
        // Initiate the links array
        $plinks = array();
        $links = array();
        $slinks = array();

        // Concatenate the get variables to add to the page numbering string
        $queryUrl = '';
        if (!empty($params) === true) {
            unset($params['page']);
            $queryUrl = '&amp;' . http_build_query($params);
        }
        // If we have more then one pages
        if (($this->pages) > 1) {
            // Assign the 'previous page' link into the array if we are not on the first page
            if ($this->page != 1) {
                if ($this->_showFirstAndLast) {
                    $plinks[] = ' <li><a href="?page=1' . $queryUrl . '">&laquo;&laquo; First </a></li> ';
                }
                $plinks[] = ' <li><a href="?page=' . ($this->page - 1) . $queryUrl . '">&laquo; Prev</a></li> ';
            }

            // Assign all the page numbers & links to the array
            for ($j = 1; $j < ($this->pages + 1); $j++) {
                if ($this->pages > 7) {
                    if ($this->page == $j) {
                        $links[] = ' <li class="active"><a class="selected">' . $j . '</a></li> '; // If we are on the same page as the current item
                    } else {
                        if ($this->page <= 4) {
                            if ($j <= 5) {
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                                if ($j == 5) {
                                    $links[] = '<li class="paginate_button disabled" id="dataTable_ellipsis"><a href="#" aria-controls="dataTable" data-dt-idx="6" tabindex="0">…</a></li>';
                                }
                            }
                            if ($j == $this->pages) {
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                            }
                        }
                        if (($this->page > 4) && ($this->page < ($this->pages - 3))) {
                            if ($j == 1) {
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                            }
                            if ($j == ($this->page - 1)) {
                                $links[] = '<li class="paginate_button disabled" id="dataTable_ellipsis"><a href="#" aria-controls="dataTable" data-dt-idx="6" tabindex="0">…</a></li>';
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                            }
                            if ($j == ($this->page + 1)) {
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                                $links[] = '<li class="paginate_button disabled" id="dataTable_ellipsis"><a href="#" aria-controls="dataTable" data-dt-idx="6" tabindex="0">…</a></li>';
                            }
                            if ($j == $this->pages) {
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                            }
                        }
                        if (($this->page >= ($this->pages - 3))) {
                            if (($j >= ($this->pages - 4))) {
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                            }
                            if ($j == 1) {
                                $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                                $links[] = '<li class="paginate_button disabled" id="dataTable_ellipsis"><a href="#" aria-controls="dataTable" data-dt-idx="6" tabindex="0">…</a></li>';
                            }
                        }
                    }
                } else {
                    if ($this->page == $j) {
                        $links[] = ' <li class="active"><a class="selected">' . $j . '</a></li> '; // If we are on the same page as the current item
                    } else {
                        $links[] = ' <li><a href="?page=' . $j . $queryUrl . '">' . $j . '</a></li> '; // add the link to the array
                    }
                }
            }

            // Assign the 'next page' if we are not on the last page
            if ($this->page < $this->pages) {
                $slinks[] = ' <li><a href="?page=' . ($this->page + 1) . $queryUrl . '"> Next &raquo; </a></li> ';
                if ($this->_showFirstAndLast) {
                    $slinks[] = ' <li><a href="?page=' . ($this->pages) . $queryUrl . '"> Last &raquo;&raquo; </a></li> ';
                }
            }

            // Push the array into a string using any some glue
            return implode(' ', $plinks) . implode($this->mainSeperator, $links) . implode(' ', $slinks);
        }
        return;
    }

}

Wednesday, September 20, 2017

PHP Demo For- image resize while uploading

/******* This code is for converting height with of jpeg, jpg, png and gif image*********
<?php
function makeName($text) {
    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    $text = trim($text, '-');
    $text = strtolower($text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    if (strlen($text) > 70) {
        $text = substr($text, 0, 70);
    }
    if (empty($text)) {
        return time();
    }
    return $text;
}

if (isset($_FILES['files']) && !empty($_FILES['files'])) {
    $errors = array();
    if (isset($_FILES['files']['tmp_name'][0]) && $_FILES['files']['tmp_name'][0]) {
        foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
       
            $file = pathinfo($file_name);
            $extension = strtolower($file['extension']);
            $new_name = makeName($file['filename'] . date('d-m-Y h:i:s')) . "." . $extension;

            //****This code is for converting height with of Jpeg, Jpg, Png and Gif image
            $desired_dir = "../../../data/images/";

            if (is_dir($desired_dir) == false) {
                mkdir("$desired_dir", 0700);  // Create directory if it does not exist
            }
            $filepath = $desired_dir . $new_name;


            $uploadedfile = $_FILES['files']['tmp_name'][$key];

            list($width, $height) = getimagesize($uploadedfile);

            if (($width > 1024) || $height > 768 || ($file_size > 300000)) {

                if ($width > 1024) {
                    $newwidth = 1024;
                    $newheight = ($height / $width) * $newwidth;
                } else if ($height > 768) {
                    $newheight = 768;
                    $newwidth = ($width / $height) * $newheight;
                } else {
                    $newwidth = $width;
                    $newheight = $height;
                }

                if ($extension == "jpg" || $extension == "jpeg" || $extension == "JPG" || $extension == "JPEG") {
                    $src = imagecreatefromjpeg($uploadedfile);
                } else if ($extension == "png" || $extension == "PNG") {
                    $src = imagecreatefrompng($uploadedfile);
                } else {
                    $src = imagecreatefromgif($uploadedfile);
                }

                $tmp = imagecreatetruecolor($newwidth, $newheight);

//                imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127));
//                imagealphablending($tmp, false);
//                imagesavealpha($tmp, true);

                imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);



                if ($file_size > 300000) {
                    if ($extension == "jpg" || $extension == "jpeg" || $extension == "JPG" || $extension == "JPEG") {
                        imagejpeg($tmp, $filepath, 70);
                    } else if ($extension == "png" || $extension == "PNG") {
                        imagepng($tmp, $filepath, 7);
                    } else {
                        imagegif($tmp, $filepath);
                    }
                } else {
                    if ($extension == "jpg" || $extension == "jpeg" || $extension == "JPG" || $extension == "JPEG") {
                        imagejpeg($tmp, $filepath, 90);
                    } else if ($extension == "png" || $extension == "PNG") {
                        imagepng($tmp, $filepath);
                    } else {
                        imagegif($tmp, $filepath);
                    }
                }

                imagedestroy($src);
                imagedestroy($tmp);
            } else {
                if (is_dir($filepath) == false) {
                    move_uploaded_file($file_tmp, $filepath);
                } else {         // rename the file if another one exist
                    $new_dir = $filepath;
                    rename($file_tmp, $new_dir);
                }
            }
            $size = filesize($filepath);
         
        }
     
    } else {
        echo "Please, Upload atlist one file";
    }
}
?>

Product Category Demo in laravel

https://drive.google.com/file/d/1kuyeT3LA22IuN3o_kypOyXesEXMLv31e/view?usp=sharing