Category

Category: PHP

Installing MongoDB in Laragon Windows

Installing MongoDB in Windows can be very confusing when you’re a beginner. Your first thought was probably to just google and find a article that will summarize it for you, well you came to the right place. Let’s dive into the installation right away

  1. Download and install the latest version of the following if you have not already:
  2. Download MongoDB PHP extension: https://pecl.php.net/package/mongodb
    • Make sure to download the correct DLL that matches your PHP version.
    • If you do not know which PHP version you’re running, right click on Laragon -> PHP > Version – you should see the version of PHP displayed here.
  3. From the start menu tray, right click on Laragon -> PHP > php.ini, then add the following code: extension=php_mongodb.dll then save the file. Then restart Laragon
  4. Test, create a PHP  file in your laragon www directory then add the following: <?php phpinfo(); then save the file. Access the file in your browser, you should see the following:

How to install Xdebug in Laragon

Installation in Laragon:

  1. Create a file on your server and output phpinfo()
  2. Go to this URL: https://xdebug.org/download
    • then download xdebug depending on your PHP version.
    • select the one with “TS”, example: “PHP 5.6 VC11 TS (64 bit)”
  3. Enable xdebug by right click on the icon of laragon in your task bar.
    • then select PHP > Extensions > click xdebug-2.5.5#### to enable it.
  4. Access in your browser the file you created in step 1, make sure that it shows xdebug installed.
  5. Open php.ini of laragon then at the bottom of the file, add:
    • [XDebug]
      xdebug.profiler_enable = 1
      xdebug.profiler_output_dir = "C:\laragon\www\xdebug"
      • IMPORTANT: make sure that this directory exists. This is where all data will be logged.
      • for additional functions, see this link: https://xdebug.org/docs/profiler
      • make sure to restart laragon for changes to take effect.

Basically Xdebug creates a file which contains all the information that it profiled on your web page. You can use a tool called QCacheGrind to display the results in a much easier to understand graphical interface.

Zip and Unzip Files with PHP

Example code for zipping and unzipping files. Code taken from a tool called phpfilemanager.php

/* Source: https://github.com/gbif/dwca-adapters/tree/master/classes/zip */
/*--------------------------------------------------
 | TAR/GZIP/BZIP2/ZIP ARCHIVE CLASSES 2.1
 | By Devin Doucette
 | Copyright (c) 2005 Devin Doucette
 | Email: darksnoopy@shaw.ca
 +--------------------------------------------------
 | Email bugs/suggestions to darksnoopy@shaw.ca
 +--------------------------------------------------
 | This script has been created and released under
 | the GNU GPL and is free to use and redistribute
 | only if this copyright statement is not removed
 +--------------------------------------------------*/
class archive
{
	function archive($name)
	{
		$this->options = array (
			'basedir' => ".",
			'name' => $name,
			'prepend' => "",
			'inmemory' => 0,
			'overwrite' => 0,
			'recurse' => 1,
			'storepaths' => 1,
			'followlinks' => 0,
			'level' => 3,
			'method' => 1,
			'sfx' => "",
			'type' => "",
			'comment' => ""
		);
		$this->files = array ();
		$this->exclude = array ();
		$this->storeonly = array ();
		$this->error = array ();
	}
	function set_options($options)
	{
		foreach ($options as $key => $value)
			$this->options[$key] = $value;
		if (!empty ($this->options['basedir']))
		{
			$this->options['basedir'] = str_replace("\\", "/", $this->options['basedir']);
			$this->options['basedir'] = preg_replace("/\/+/", "/", $this->options['basedir']);
			$this->options['basedir'] = preg_replace("/\/$/", "", $this->options['basedir']);
		}
		if (!empty ($this->options['name']))
		{
			$this->options['name'] = str_replace("\\", "/", $this->options['name']);
			$this->options['name'] = preg_replace("/\/+/", "/", $this->options['name']);
		}
		if (!empty ($this->options['prepend']))
		{
			$this->options['prepend'] = str_replace("\\", "/", $this->options['prepend']);
			$this->options['prepend'] = preg_replace("/^(\.*\/+)+/", "", $this->options['prepend']);
			$this->options['prepend'] = preg_replace("/\/+/", "/", $this->options['prepend']);
			$this->options['prepend'] = preg_replace("/\/$/", "", $this->options['prepend']) . "/";
		}
	}
	function create_archive()
	{
		$this->make_list();
		if ($this->options['inmemory'] == 0)
		{
			$pwd = getcwd();
			chdir($this->options['basedir']);
			if ($this->options['overwrite'] == 0 && file_exists($this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : "")))
			{
				$this->error[] = "File {$this->options['name']} already exists.";
				chdir($pwd);
				return 0;
			}
			else if ($this->archive = @fopen($this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : ""), "wb+"))
				chdir($pwd);
			else
			{
				$this->error[] = "Could not open {$this->options['name']} for writing.";
				chdir($pwd);
				return 0;
			}
		}
		else
			$this->archive = "";
		switch ($this->options['type'])
		{
		case "zip":
			if (!$this->create_zip())
			{
				$this->error[] = "Could not create zip file.";
				return 0;
			}
			break;
		case "bzip":
			if (!$this->create_tar())
			{
				$this->error[] = "Could not create tar file.";
				return 0;
			}
			if (!$this->create_bzip())
			{
				$this->error[] = "Could not create bzip2 file.";
				return 0;
			}
			break;
		case "gzip":
			if (!$this->create_tar())
			{
				$this->error[] = "Could not create tar file.";
				return 0;
			}
			if (!$this->create_gzip())
			{
				$this->error[] = "Could not create gzip file.";
				return 0;
			}
			break;
		case "tar":
			if (!$this->create_tar())
			{
				$this->error[] = "Could not create tar file.";
				return 0;
			}
		}
		if ($this->options['inmemory'] == 0)
		{
			fclose($this->archive);
			if ($this->options['type'] == "gzip" || $this->options['type'] == "bzip")
				unlink($this->options['basedir'] . "/" . $this->options['name'] . ".tmp");
		}
	}
	function add_data($data)
	{
		if ($this->options['inmemory'] == 0)
			fwrite($this->archive, $data);
		else
			$this->archive .= $data;
	}
	function make_list()
	{
		if (!empty ($this->exclude))
			foreach ($this->files as $key => $value)
				foreach ($this->exclude as $current)
					if ($value['name'] == $current['name'])
						unset ($this->files[$key]);
		if (!empty ($this->storeonly))
			foreach ($this->files as $key => $value)
				foreach ($this->storeonly as $current)
					if ($value['name'] == $current['name'])
						$this->files[$key]['method'] = 0;
		unset ($this->exclude, $this->storeonly);
	}
	function add_files($list)
	{
		$temp = $this->list_files($list);
		foreach ($temp as $current)
			$this->files[] = $current;
	}
	function exclude_files($list)
	{
		$temp = $this->list_files($list);
		foreach ($temp as $current)
			$this->exclude[] = $current;
	}
	function store_files($list)
	{
		$temp = $this->list_files($list);
		foreach ($temp as $current)
			$this->storeonly[] = $current;
	}
	function list_files($list)
	{
		if (!is_array ($list))
		{
			$temp = $list;
			$list = array ($temp);
			unset ($temp);
		}
		$files = array ();
		$pwd = getcwd();
		chdir($this->options['basedir']);
		foreach ($list as $current)
		{
			$current = str_replace("\\", "/", $current);
			$current = preg_replace("/\/+/", "/", $current);
			$current = preg_replace("/\/$/", "", $current);
			if (strstr($current, "*"))
			{
				$regex = preg_replace("/([\\\^\$\.\[\]\|\(\)\?\+\{\}\/])/", "\\\\\\1", $current);
				$regex = str_replace("*", ".*", $regex);
				$dir = strstr($current, "/") ? substr($current, 0, strrpos($current, "/")) : ".";
				$temp = $this->parse_dir($dir);
				foreach ($temp as $current2)
					if (preg_match("/^{$regex}$/i", $current2['name']))
						$files[] = $current2;
				unset ($regex, $dir, $temp, $current);
			}
			else if (@is_dir($current))
			{
				$temp = $this->parse_dir($current);
				foreach ($temp as $file)
					$files[] = $file;
				unset ($temp, $file);
			}
			else if (@file_exists($current))
				$files[] = array ('name' => $current, 'name2' => $this->options['prepend'] .
					preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($current, "/")) ?
					substr($current, strrpos($current, "/") + 1) : $current),
					'type' => @is_link($current) && $this->options['followlinks'] == 0 ? 2 : 0,
					'ext' => substr($current, strrpos($current, ".")), 'stat' => stat($current));
		}
		chdir($pwd);
		unset ($current, $pwd);
		usort($files, array ("archive", "sort_files"));
		return $files;
	}
	function parse_dir($dirname)
	{
		if ($this->options['storepaths'] == 1 && !preg_match("/^(\.+\/*)+$/", $dirname))
			$files = array (array ('name' => $dirname, 'name2' => $this->options['prepend'] .
				preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($dirname, "/")) ?
				substr($dirname, strrpos($dirname, "/") + 1) : $dirname), 'type' => 5, 'stat' => stat($dirname)));
		else
			$files = array ();
		$dir = @opendir($dirname);
		while ($file = @readdir($dir))
		{
			$fullname = $dirname . "/" . $file;
			if ($file == "." || $file == "..")
				continue;
			else if (@is_dir($fullname))
			{
				if (empty ($this->options['recurse']))
					continue;
				$temp = $this->parse_dir($fullname);
				foreach ($temp as $file2)
					$files[] = $file2;
			}
			else if (@file_exists($fullname))
				$files[] = array ('name' => $fullname, 'name2' => $this->options['prepend'] .
					preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($fullname, "/")) ?
					substr($fullname, strrpos($fullname, "/") + 1) : $fullname),
					'type' => @is_link($fullname) && $this->options['followlinks'] == 0 ? 2 : 0,
					'ext' => substr($file, strrpos($file, ".")), 'stat' => stat($fullname));
		}
		@closedir($dir);
		return $files;
	}
	function sort_files($a, $b)
	{
		if ($a['type'] != $b['type'])
			if ($a['type'] == 5 || $b['type'] == 2)
				return -1;
			else if ($a['type'] == 2 || $b['type'] == 5)
				return 1;
		else if ($a['type'] == 5)
			return strcmp(strtolower($a['name']), strtolower($b['name']));
		else if ($a['ext'] != $b['ext'])
			return strcmp($a['ext'], $b['ext']);
		else if ($a['stat'][7] != $b['stat'][7])
			return $a['stat'][7] > $b['stat'][7] ? -1 : 1;
		else
			return strcmp(strtolower($a['name']), strtolower($b['name']));
		return 0;
	}
	function download_file()
	{
		if ($this->options['inmemory'] == 0)
		{
			$this->error[] = "Can only use download_file() if archive is in memory. Redirect to file otherwise, it is faster.";
			return;
		}
		switch ($this->options['type'])
		{
		case "zip":
			header("Content-Type: application/zip");
			break;
		case "bzip":
			header("Content-Type: application/x-bzip2");
			break;
		case "gzip":
			header("Content-Type: application/x-gzip");
			break;
		case "tar":
			header("Content-Type: application/x-tar");
		}
		$header = "Content-Disposition: attachment; filename=\"";
		$header .= strstr($this->options['name'], "/") ? substr($this->options['name'], strrpos($this->options['name'], "/") + 1) : $this->options['name'];
		$header .= "\"";
		header($header);
		header("Content-Length: " . strlen($this->archive));
		header("Content-Transfer-Encoding: binary");
		header("Cache-Control: no-cache, must-revalidate, max-age=60");
		header("Expires: Sat, 01 Jan 2000 12:00:00 GMT");
		print($this->archive);
	}
	function save_file( $output_file = 'tmp' )
	{
		if ($this->options['inmemory'] == 0)
		{
			$this->error[] = "Can only use download_file() if archive is in memory. Redirect to file otherwise, it is faster.";
			return;
		}
		file_put_contents( $output_file, $this->archive);
	}
}

Zip FIle Method

class zip_file extends archive
{
	function zip_file($name)
	{
		$this->archive($name);
		$this->options['type'] = "zip";
	}
	function create_zip()
	{
		$files = 0;
		$offset = 0;
		$central = "";
		if (!empty ($this->options['sfx']))
			if ($fp = @fopen($this->options['sfx'], "rb"))
			{
				$temp = fread($fp, filesize($this->options['sfx']));
				fclose($fp);
				$this->add_data($temp);
				$offset += strlen($temp);
				unset ($temp);
			}
			else
				$this->error[] = "Could not open sfx module from {$this->options['sfx']}.";
		$pwd = getcwd();
		chdir($this->options['basedir']);
		foreach ($this->files as $current)
		{
			if ($current['name'] == $this->options['name'])
				continue;
			$timedate = explode(" ", date("Y n j G i s", $current['stat'][9]));
			$timedate = ($timedate[0] - 1980 << 25) | ($timedate[1] << 21) | ($timedate[2] << 16) |
				($timedate[3] << 11) | ($timedate[4] << 5) | ($timedate[5]);
			$block = pack("VvvvV", 0x04034b50, 0x000A, 0x0000, (isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate);
			if ($current['stat'][7] == 0 && $current['type'] == 5)
			{
				$block .= pack("VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']) + 1, 0x0000);
				$block .= $current['name2'] . "/";
				$this->add_data($block);
				$central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000,
					(isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate,
					0x00000000, 0x00000000, 0x00000000, strlen($current['name2']) + 1, 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset);
				$central .= $current['name2'] . "/";
				$files++;
				$offset += (31 + strlen($current['name2']));
			}
			else if ($current['stat'][7] == 0)
			{
				$block .= pack("VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']), 0x0000);
				$block .= $current['name2'];
				$this->add_data($block);
				$central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000,
					(isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate,
					0x00000000, 0x00000000, 0x00000000, strlen($current['name2']), 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset);
				$central .= $current['name2'];
				$files++;
				$offset += (30 + strlen($current['name2']));
			}
			else if ($fp = @fopen($current['name'], "rb"))
			{
				$temp = fread($fp, $current['stat'][7]);
				fclose($fp);
				$crc32 = crc32($temp);
				if (!isset($current['method']) && $this->options['method'] == 1)
				{
					$temp = gzcompress($temp, $this->options['level']);
					$size = strlen($temp) - 6;
					$temp = substr($temp, 2, $size);
				}
				else
					$size = strlen($temp);
				$block .= pack("VVVvv", $crc32, $size, $current['stat'][7], strlen($current['name2']), 0x0000);
				$block .= $current['name2'];
				$this->add_data($block);
				$this->add_data($temp);
				unset ($temp);
				$central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000,
					(isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate,
					$crc32, $size, $current['stat'][7], strlen($current['name2']), 0x0000, 0x0000, 0x0000, 0x0000, 0x00000000, $offset);
				$central .= $current['name2'];
				$files++;
				$offset += (30 + strlen($current['name2']) + $size);
			}
			else
				$this->error[] = "Could not open file {$current['name']} for reading. It was not added.";
		}
		$this->add_data($central);
		$this->add_data(pack("VvvvvVVv", 0x06054b50, 0x0000, 0x0000, $files, $files, strlen($central), $offset,
			!empty ($this->options['comment']) ? strlen($this->options['comment']) : 0x0000));
		if (!empty ($this->options['comment']))
			$this->add_data($this->options['comment']);
		chdir($pwd);
		return 1;
	}
}

Unzip File Method

function unzip_file($zip_name, $current_path, $destination_path){
	$zip = zip_open($current_path.$zip_name);
	if($zip){
		while ($zip_entry = zip_read($zip)){
			if(zip_entry_filesize($zip_entry)){
				$complete_path = dirname(zip_entry_name($zip_entry));
				$complete_name = zip_entry_name($zip_entry);
				if(!file_exists($destination_path.$complete_path)){
					$tmp = '';
					foreach(explode('/',$complete_path) as $k){
						$tmp .= $k.'/';
						if(!file_exists($destination_path.$tmp)){
							@mkdir($destination_path.$tmp, 0755);
							@chmod($destination_path.$tmp, 0755 );
						}
					}
				}
				
				if(zip_entry_open($zip, $zip_entry, "r")){
					if($fd = fopen($destination_path.$complete_name, 'w')){
						fwrite($fd, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
						fclose($fd);
						@chmod($destination_path, 0644);
					} else {
						echo "fopen($destination_path.$complete_name) error<br>";
					}
					zip_entry_close($zip_entry);
				} else {
					echo "zip_entry_open($zip,$zip_entry) error<br>";
				}
			}
		}
		zip_close($zip);
	}
}

Example Usage:

Zipping Files:

$current_dir = getcwd();
$files = array('front-page.php', 'functions.php', 'header.php', 'carlo-fontanos');
$zipname = 'myzip_carlo.zip';

ignore_user_abort(true);
ini_set("display_errors",0);
ini_set("max_execution_time",0);
				
$zipfile = new zip_file($zipname);
if($zipfile){
	$zipfile->set_options(array('basedir'=>$current_dir,'overwrite'=>1,'level'=>3));
	
	if($files){
		foreach($files as $file){
			$zipfile->add_files(trim($file));
		}
	}
	
	$zipfile->create_archive();
}

unset($zipfile);

Unzipping Files:

$current_dir = getcwd();
unzip_file('theme-backup-12-11-2017.zip', $current_dir . '/', $current_dir . '/extracted/');

Simple PHP Pagination with AJAX

<?php 
require_once('load.php');

if( isset( $_POST ) ){
	$response = '';
	
    if( isset( $_POST['page'] ) ){
        $page = $_POST['page'];
        $cur_page = $page;
        $page -= 1;
        $per_page = 20;
        $previous_btn = true;
        $next_btn = true;
        $first_btn = true;
        $last_btn = true;
        $start = $page * $per_page;
        
        $all_blog_posts = DB::db_get_results("
            SELECT * FROM item ORDER BY id DESC LIMIT %d, %d", array( $start, $per_page ) );
        
        $count = DB::db_get_var("
            SELECT COUNT(id) FROM item", array() );
        
        foreach( $all_blog_posts as $key => $post ){ 
            $response .= '
            <div class = "col-md-12">       
                <h3>' . $post->iname . '</h3>
                <p>Item ID: ' . $post->id . '</p>
                <p>Date Entered:  ' . $post->entry . '</p>
            </div>';
            
		}
        
        $no_of_paginations = ceil( $count / $per_page );

        if($cur_page >= 7){
            $start_loop = $cur_page - 3;
            if( $no_of_paginations > $cur_page + 3 )
                $end_loop = $cur_page + 3;
            else if( $cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6 ){
                $start_loop = $no_of_paginations - 6;
                $end_loop = $no_of_paginations;
            } else {
                $end_loop = $no_of_paginations;
            }
        } else {
            $start_loop = 1;
            if( $no_of_paginations > 7 ){
                $end_loop = 7;
            } else {
                $end_loop = $no_of_paginations;
			}
        }
        
        $response .= "
		<div class='pagination'>
			<ul>";

				if( $first_btn && $cur_page > 1 ){
					$response .= "<li p='1' class='active'>First</li>";
				} else if($first_btn){
					$response .= "<li p='1' class='inactive'>First</li>";
				}

				if( $previous_btn && $cur_page > 1 ){
					$pre = $cur_page - 1;
					$response .= "<li p='" . $pre . "' class='active'>Previous</li>";
				} else if( $previous_btn ){
					$response .= "<li class='inactive'>Previous</li>";
				}
				
				for ($i = $start_loop; $i <= $end_loop; $i++ ){
					if($cur_page == $i){
						$response .= "<li p='" . $i . "' class = 'selected' >" . $i . "</li>";
					} else {
						$response .= "<li p='" . $i . "' class='active'>" . $i . "</li>";
					}
				}
				
				if( $next_btn && $cur_page < $no_of_paginations ){
					$nex = $cur_page + 1;
					$response .= "<li p='" . $nex . "' class='active'>Next</li>";
				} else if( $next_btn ){
					$response .= "<li class='inactive'>Next</li>";
				}

				if( $last_btn && $cur_page < $no_of_paginations ){
					$response .= "<li p='" . $no_of_paginations . "' class='active'>Last</li>";
				} else if($last_btn){
					$response .= "<li p='" . $no_of_paginations . "' class='inactive'>Last</li>";
				}

				$response .= "
			</ul>
		</div>";
        
        echo $response;
		exit();
    }
}


?>

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Pagination by Carl Victor C. Fontanos</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<style>
	.pagination ul {margin: 0; padding: 0;}
	.pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }
	.pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }
	.pagination ul li.inactive {background: #7E7E7E;}
	.pagination ul li.selected {background: #1E8CBE; color: white;}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="col-md-12 content">
	<div class = "inner-box content no-right-margin darkviolet">
		<div class = "response-container"></div>
	</div>      
</div>

<script type="text/javascript">
jQuery(document).ready(function($){
	var ajaxurl = window.location.href;
	
	function load_posts(page){
		var data = {
			page: page
		};
		
		$.post(ajaxurl, data, function(response){
			$(".response-container").html(response);
		});
	}
	
	load_posts(1);
	
	$('body').on('click', '.response-container .pagination li.active', function(){
		var page = $(this).attr('p');
		load_posts(page);
		
	});
				
}); 
</script>

</body>
</html>

 

Setting-up AWS CodeDeploy

Bellow is what I used to succesfully deploy my Web Application via AWS Code Deploy. This came from my notes, thought I’d share it. I hope it will help you guys get started faster with your deployement.

  1. Create a bucket in AWS Console under S3 -> “Create Bucket” blue buttton.
    1. Enter a unique name for your S3 bucket: carlofontanos-cd
    2. Region: “US Standard”
    3. Click “Create”
  2. Create a new Role. Go to IAM -> Roles -> “Create New Role” button.
    1. Set role name for EC2: carlofontanos-ec2-role then clck “Next step”
    2. On the next screen “Select Role Type” = select “Amazon EC2”
    3. On the next screen “Attach Policy” just click “Next Step” button without touching anything.
    4. On the next screen “Review” click “Create Role” button
  3. On the list of roles, click on the newly created role “carlofontanos-ec2-role”.
    1. Under “Permissions” tab, expand “inline policy” then click on the “click here” link
    2. On the next screen expand “Custom Policy” then click on “Select” button
    3. Fill up the boxes using the following:
      • Policy Name: carlofontanos-policy-ec2-s3
      • Policy Document (make sure to change the line “carlofontanos-cd” under “Resource” in the code bellow):
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        {
          "Version":"2012-10-17",
          "Statement":[
            {
              "Effect":"Allow",
              "Action":[
                "s3:Get*",
                "s3:List*"
              ],
              "Resource":[
                "arn:aws:s3:::carlofontanos-cd/*",
                "arn:aws:s3:::aws-codedeploy-us-east-1/*"
              ]
            }
          ]
        }
  4. Under the same role, go to “Trust Relationships” tab then clik on the
    “Edit Trust Relationship” button then replace everything with the code bellow then click “Update Trust Policy” button:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    {
      "Version":"2012-10-17",
      "Statement":[
        {
          "Effect":"Allow",
          "Principal":{
            "Service":"ec2.amazonaws.com"
          },
          "Action":"sts:AssumeRole"
        }
      ]
    }
  5. Create another role by navigating to the IAM -> Roles then click on “Create New Role” button
    Role Name: carlofontanos-service-role
  6. On the next screen “Select Role Type” = select “AWS Code Deploy”
  7. On the next screen “Attach Policy”, check the box for “AWSCodeDeployRole”
  8. On the next screen “Review” click “Create Role” button
  9. Go to AWS Console -> IAM -> Users, click on the “Add User” button
    • User Name: carlofontanos-user
    • Then make sure to check the box “Programmatic access” under “Access type”
  10. On the next screen, click “Attach Existing Policies directly” then from the list – check the boxes of the following then Click “Next review” button when you’re done.
    1. AmazonEC2FullAccess
    2. AWSCodeDeployFullAccess
  11. On the next screen, click on “Create User” button
  12. Save the “Access key ID” and “Secret access key” in a txt file for your reference later on.
  13. Click Close buttton when you are done.
  14. Next is we are going to create 3 inline custom policies for our user. On the list of users, click on the newly
    created user “carlofontanos-user” then under “Permissions” tab click on “Add inline policy” link.
  15. On the new screen select “Custom Policy” radio button then under it click “Select” button
  16. Create the follwing 3 roles:
    1. Policy Name: carlofontanos-s3-bucket-full
      Policy Document (make sure to change the line “carlofontanos-cd” under “Resource” in the code bellow):

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      {
        "Version":"2012-10-17",
        "Statement":[
          {
            "Effect":"Allow",
            "Action":[
              "s3:PutObject",
              "s3:GetObject",
              "s3:DeleteObject"
            ],
            "Resource":"arn:aws:s3:::carlofontanos-cd/*"
          }
        ]
      }
    2. Policy Name: carlofontanos-cloud-formation
      Policy Document:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      {
        "Version":"2012-10-17",
        "Statement":[
          {
            "Effect":"Allow",
            "Action":[
              "cloudformation:*"
            ],
            "Resource":"*"
          }
        ]
      }
    3. Policy Name: carlofontanos-iam-role
      Policy Document:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      {
        "Version":"2012-10-17",
        "Statement":[
          {
            "Effect":"Allow",
            "Action":[
              "iam:PassRole",
              "iam:ListInstanceProfiles"
            ],
            "Resource":"*"
          }
        ]
      }
  17. Now we need to create a key pair. Go to EC2 -> Network & Security -> Key Pairs then click on “Create Key Pair” button
  18. Key Pair Name: carlofontanos-key-pair
    – Note: after you click on “Create” button, a file PEM will automatically be downloaded into your disk.
    Example PEM name is: carlofontanos-key-pair.pem
    – You need to convert this file into a PPK using PuTTYGen, you can use instructions bellow:
    1. Open PuTTYGen then go to “Conversion” tab -> select “Import key”
    2. Browse for the file, then select “Save Private key” button
    3. Enter a unique name for your private key then click save.
  19. Go to EC2 -> Instance then click “Launch Instance” button.
  20. On the new screen, select “Amazon Linux AMI”
  21. Select the “Free tier eligible” type then click “Review and Launch” button.
  22. Then on the next screen, review everything then click “Launch” button. A popup will show
    up, select the key-pair we created earlier then make sure to check the “I acknowledge that I have access….” checkbox.
  23. Click “View Instance” button to preview your newly created EC2 instance, make sure the Instance state is “running” before proceeding with the next steps of this tutorial.
  24. Now that our new instance is up and running, we now need to SSH to it. For this part I will be using PuTTY
    1. Copy the public IP of our new Instance then paste it on the “Host name (or IP address)” text field on PuTTY
    2. On the left side bar of PuTTY, go to: Connection -> SSH -> Auth then browse the Key Pair PPK file we generated earlier (ex. carlofontanos-key-pair.ppk).
    3. Click open to launch the SSH Command Line, if a PuTTY secruity alert shows up – just click “Yes”
    4. On the SSH command line, Enter the following information:
      • Login as: ec2-user
    5. Ok now that we’re logged-in, let’s configure AWS by running the command:
      • aws configure
    6. Supply the following:
    7. A. AWS Access Key: YOUR_KEY
      B. AWS Secret access key: YOUR_SECRET_KEY
      C. Default Region Name: us-east-1
      D. Default ouput format: json
    8. Login to your FTP client, if you are using FileZilla, you can follow the tutorial bellow:
      1. Open FileZilla then go to File -> Site Manager then click on “New Site” button then name it anything you want
      2. Under the General Tab, fill up / select the follwing:
        Host: [public IP of your EC2 instance]
        Protocol: SFTP – SSH File Transfer Protocol
        Login Type: Normal
        User: ec2-user
        Password: [leave blank or enter it if you have]
      3. From the menu, go to Edit -> Settings, from the left tab go to Connection -> SFTP then click on the “Add key file” button. Select the PPK file we generated earlier then click the “OK” button when you’re done
      4. Click “Connect” button to start listing the directoy files.
    9. Download this zip file and save it to your computer: default-app.zip
    10. Using your FTP client – upload the file “default-app.zip” to the root folder “/home/ec2-user” of your EC2 instance.
    11. Go back to the SSH command line then enter: “unzip default-app.zip” to start unzipping the conents.
    12. From the SSH command line, cd to the “default-app” using the command:
      • cd default-app
    13. Now go back to your FTP client open the file: /home/ec2-user/default-app/cfTemplate.json using your favorite editor then locate the following keys:
      A. “KeyName” – change its value to the name of the key-pair we generated in AWS earlier. In my case it is: “carlofontanos-key-pair”
      B. “IamInstanceProfile” – change its value to the name of the IAM Role we generated in AWS earlier. In my case it is: “carlofontanos-ec2-role”
      – When you’re done, save the file then upload it via FTP.
    14. From you FTP client, open the file: /home/ec2-user/default-app/deploy.sh then locate the following keys:
      A. Under line 26, change “cdtutorial-uwf” to “carlofontanos-cd”
      B. Under line 38, change the value of “KEY_AND_VALUE –service-role-arn” to the value listed under AWS Console ->
      AIM -> Roles -> carlofontanos-service-role -> Role ARN
      C. Under line 40, change the value of –s3-location bucket to “carlofontanos-cd”
    15. From the SSH command line, enter “chmod +x cleanup.sh” then press enter.
    16. From the SSH command line, enter “chmod +x deploy.sh”
    17. From the SSH command line, enter “ls” – which will display cleanup.sh and deploy.sh in green text color, which means it will work.
    18. Finally, run “./deploy.sh” to start deploying – this should take about 6 minutes to complete.
  25. Open your browser then navigate to [public IP of your EC2 instance]:8000. Ex. 54.164.193.11:8000

Organize Diretory Files into Year-Month-Day Heirarchy using PHP

Do you have large amount of files sitting in just one directory? Have you ever thought about organizing them in Year-Month-Day path programatically?

What the code bellow does is it loops through each file on the specified directory then takes the date the file was created and formats it into a path, ex. 2017/January/12, now that we know the path – we can use it for creating the directory heirarchy tree. If the path does not exist yet – we create it. After the path is created, we then move the file inside it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
$image_folder = 'images/';
$files = glob( $image_folder . '*.{jpg,png,gif}', GLOB_BRACE) ;

foreach( $files as $file ) {
    $time_stamp = filemtime( $file ); /* Get date create of the file */
    $path_date = date( 'Y/F/d', $time_stamp ); /* Returns the format: [Year]/[Month]/[Day] */
   
    /* Create path if not yet existing */
    if ( ! file_exists( $image_folder . $path_date ) ) {
        mkdir( $image_folder . $path_date, 0777, true );
    }
   
    /* Use "rename" instead of "copy" if you want to MOVE the file */
    copy( $file, $image_folder . $path_date . '/' . explode( 'images/', $file )[1] );
   
    /* Do database update here if necessary */ 
}

Build your own Custom File Manager for CKEditor using PHP

There are many available extensions that can be coupled with CKEditor for managing files, but if you want to build your own from scaratch, then here are easy steps to help you get started:

Create a file “index.php“, in it, place the code bellow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
    <title>CKEditor Example</title>
    <script src="//cdn.ckeditor.com/4.5.7/full/ckeditor.js"></script>
</head>
<body>
    <div class="container">
        <div class = "col-md-12">
            <br />
            <textarea name="termpage">Please type your auction terms and conditions here !</textarea>
            <script>
                CKEDITOR.replace( 'termpage', {
                    toolbar: null,
                    toolbarGroups: null
                } );
                CKEDITOR.config.filebrowserBrowseUrl = 'browse.php';
                CKEDITOR.config.filebrowserUploadUrl = 'upload.php';
            </script>
        </div>
    </div>
</body>
</html>

The CKEditor CDN is updated from time to time so make sure to get the latest CKEditor from here: https://cdn.ckeditor.com/

Now we need to store the files to our server, bellow is a simple PHP code that handles posted files.

Create a file “upload.php“, in it, place the code bellow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$funcNum = $_GET['CKEditorFuncNum'];
$url = '';

// Make sure that the anonymous function reference number used to pass the URL of a file to CKEditor is set
if( $funcNum ){

    // Check if there is an error
    if( ! $_FILES['upload']['error'] ) {
               
        // Replace file name spaces and convert to lower case.
        $file = pathinfo( $_FILES['upload']['name'] );
        $new_file_name = str_replace(' ', '_', strtolower( $file['filename'] ) ) . '-' . time() . '.' . $file['extension'];
   
        // Check if file was uploaded
        if( move_uploaded_file( $_FILES['upload']['tmp_name'], 'uploads/' . $new_file_name )){
           
            $message = 'File successfully uploaded';       
           
            // Check if we're running locally or live
            if( $_SERVER['SERVER_NAME'] == 'localhost' ) {
                $url = $_SERVER['HTTP_HOST'] . '/ckeditor/uploads/' . $new_file_name;
            } else {
                $url = $_SERVER['HTTP_HOST'] . '/uploads/' . $new_file_name;
            }
        }
                   
    } else {
        // Output all errors
        $message = 'Oops!  Your upload triggered the following error:  ' . $_FILES['upload']['error'];
    }
   
    // Return the message to the CKEDITOR File Manager
    echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";

}

And here’s where you put the codes of your custom file manager.

Create a file “browse.php“, in it, place the code bellow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example: Browsing Files</title>
    <script>
        // Helper function to get parameters from the query string.
        function getUrlParam( paramName ) {
            var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
            var match = window.location.search.match( reParam );

            return ( match && match.length > 1 ) ? match[1] : null;
        }
        // Simulate user action of selecting a file to be returned to CKEditor.
        function returnFileUrl() {

            var funcNum = getUrlParam( 'CKEditorFuncNum' );
            var fileUrl = '/path/to/file.txt';
            window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
            window.close();
        }
    </script>
</head>
<body>
    <button onclick="returnFileUrl()">Select File</button>
</body>
</html>

Note that the only functionality privded above is just the browse button and file selection handler, you will have to build your own file browser then receive the file in CKEditor on-click of the “Select File” button.

Clear Cache of Modified Files using PHP

Most large websites nowadays do a lot of updates to their JS and CSS files to give their customers a better browsing experience. The problem that most Web Developers face is the new codes are not pushed to the users, instead they are served the old cached version of the file.

Most of the answers when you Google this up is to simply add a time stamp to the end of your file URL. Sure! that works but your user’s browser will always have to re-download the file every time they load a new page in your website – this is not very efficient especially when you are working on large scaled websites. So what if we just change the time stamp ONLY when the file was modified?

Here is how you can do it:

1
2
3
4
5
6
7
function check_if_modified( $file_location ) {
    if( file_exists( $file_location ) ) {
        return filemtime( $file_location );
    } else {
        return false;
    }
}

The function above simply returns the time the file was last modified, this would mean that if the file was never modofied – the time stamp will never change.

Usage

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
    <head>
        <script src="app.js?<?php echo check_if_modified('/app.js'); ?>"></script>
    </head>
    <body>
        <h1>Carl Fontanos</h1>
        <p>Test!</p>
    </body>
</html>

NOTE: If you are running on a framework or platform like WordPress, the parameter must be the PATH to your file, as the functions that checks the existence and modification time of the file requires a valid path.

1
<script src="app.js?<?php echo check_if_modified( PATH_TO_FILE . '/app.js'); ?>"></script>

Clear Browser Cache Every Nth Day(s) in PHP

This code is useful when you are making a lot of changes to your styles and js scripts and you want your visitors / users to see the updated version page and not the old cached version.

The Process

  1. Create a cookie variable where we will be storing the current time when user visits the website
  2. Subtract current time to old time then get the result in days
  3. Check if the result is greater or equal to the provided nth day(s) $no_of_days
  4. If greater, execute our AJAX cache cleaner script with the help of location.reload(true) then set the cookie variable to the current time. Setting the parameter to true will prevent the browser from fetching the cached version of the page.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$ajax_cache_cleaner = '
<script type = "text/javascript">
 $.ajax({
    url: window.location.href,
    headers: {
        "Pragma": "no-cache",
        "Expires": -1,
        "Cache-Control": "no-cache"
    }
}).done(function () {
    window.location.reload(true);
});
</script>'
;

if( isset( $_COOKIE['clear_browser_cache'] ) ) {
    $old_time = $_COOKIE['clear_browser_cache'];
    $current_time = time();
    $secs = $current_time - $old_time; // seconds between the two times
    $days = $secs / 86400;
    if( $days >= $no_of_days ) {
        setcookie('clear_browser_cache', time(), time() + 86400); // 86400 = 1 day
        echo $ajax_cache_cleaner;
           
    }
} else {
    setcookie('clear_browser_cache', time(), time() + ( $no_of_days * 86400 ) ); // 86400 = 1 day
    echo $ajax_cache_cleaner;
}

Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
 * Clears the browser cache everyday nth days.
 */

function clear_browser_cache( $no_of_days ) {
   
    $ajax_cache_cleaner = '
    <script type = "text/javascript">
     $.ajax({
        url: window.location.href,
        headers: {
            "Pragma": "no-cache",
            "Expires": -1,
            "Cache-Control": "no-cache"
        }
    }).done(function () {
        window.location.reload(true);
    });
    </script>'
;
   
    if( isset( $_COOKIE['clear_browser_cache'] ) ) {
        $old_time = $_COOKIE['clear_browser_cache'];
        $current_time = time();
        $secs = $current_time - $old_time; // seconds between the two times
        $days = $secs / 86400;
        if( $days >= $no_of_days ) {
            setcookie('clear_browser_cache', time(), time() + 86400); // 86400 = 1 day
            echo $ajax_cache_cleaner;
               
        }
    } else {
        setcookie('clear_browser_cache', time(), time() + ( $no_of_days * 86400 ) ); // 86400 = 1 day
        echo $ajax_cache_cleaner;
    }
   
}

Parameter equals the number of days before executing the cache cleaner script.

Note:

  • Make sure jQuery is loaded first before using the above function.
  • Run the function on the Head part of your HTML document.

Parsing a CSV File using PHP

There will be times you will be tasked to enter all the data stored inside an excel file into the database. Why waste your time encoding all the data or hiring someone to do it for you if you can simply create a simple script that will read through the columns of your spreadsheet?

In this tutorial I am going to discuss how you can access the columns of your spreadsheet and insert it into your database.

Setting up a CSV File

First you will want to create a CSV file, create a new text file in your desktop or project folder, name it anything you want without spaces. For the extension you will have to enter “.csv”, now open the file you just created using your Excel Reader. You will notice that the interface looks similar to Excel. Now open the file containing your Excel table data and copy and paste it into the CSV file you created then save it.

Parsing the CSV File

There is a cool function called “fgetcsv()” which we will be using in parsing the data from your CSV file:

In your project folder, create a file: index.php and add the following code then save it:

1
2
3
4
5
6
7
$file = fopen('folder_name/csv_file.csv', 'r');
while ( ( $line = fgetcsv( $file ) ) !== FALSE) {
    echo '<pre>';
    print_r($line);
    echo '</pre>';
}
fclose( $file );

Make sure to change first parameter of the fopen to the destination of your CSV file.

To make sure everything is working perfectly without errors, try accessing your project folder from your browser. If successful, you should see several Arrays containing the data of each row of your CSV file.

Accessing the Columns within the Loop

To access the column, simply use the reference key of the columns:

1
echo $line[0];
1
$column1 = $line[1];

Inserting Data into the Database

Bellow is a simple example of inserting data into the database using MySQLi Object-oriented.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$file = fopen('folder_name/csv_file.csv', 'r');
while ( ( $line = fgetcsv( $file ) ) !== FALSE) {
    $sql = "INSERT INTO table_name (column1, column2, column3)
    VALUES ('"
. $file[0] . "', '" . $file[1] . "', '" . $file[2] . "')";
}
fclose( $file );

$conn->close();
?>

Polymorphism – OOP PHP Tutorial

In general, “Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms.

Most beginners would find the above description confusing, so let me give you real world example for you to better understand how it really works.

Let’s say we have a Dog, Cat and a Rabbit class. They’re all different but they all fall under the same category as Animal. So, it would make sense to create an interface named Animal and have all these classes implement it. That is basically Polymorphism, it’s a collection(interface) of classes that have many forms.

Assuming that we define Animal as a class instead of an interface, then forget about the Dog, Cat and Rabbit classes. The Animal class is very broad because there is so many kinds of Animal. Every animal is different, but they’re all categorized under Animal. Because of these you will have to create multiple conditional statements which makes a long and messy class that is not very efficient.

Instead of creating a class for a broad subject, you can create an interface for a bunch of different classes that run differently.

Example

Let’s use ‘Shape’ as our category:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php

// Shape is the base class
interface Shape {
    // Define method(s) that will be used by classes who will be implementing this interface.
    public function getArea();
}

class Square implements Shape {
    private $width;
    private $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function getArea(){
        return $this->width * $this->height;
    }
}

class Circle implements Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function getArea(){

        return $this->radius * $this->radius * 3.14;
    }
}

function calculateArea(Shape $shape) {
    return $shape->getArea();
}

echo calculateArea(new Square(5, 5)) . "<br/>";
echo calculateArea(new Circle(7));

Conclusion

Polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs.

GET Request using cURL

There will be times that you will need to pull out data from a web service using PHP’s GET method. In this tutorial I will be demonstrating how you can make a GET Request using cURL.

Example of GET Request:

You can test cURL in your own local server as it’s the same with using a regular form with an action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$url = "https://website.com/api.php?action=get_data&x=1&y=2";

//  Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Print the return data
print_r(json_decode($result, true));

Use json_decode if the return is in json format.

Function:

It’s best to put your cURL GET Request in a function if your a dealing with many get request in all parts of your website

1
2
3
4
5
6
7
8
9
10
11
12
function cvf_curl_get($url) {
   
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);
    $result=curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
   
}

Fastest way to Convert Associative Arrays to Objects

Simply cast an Associative array:

1
2
3
4
5
$obj = (object) array('animal' => 'dog', 'name' => 'simon');

// Then you can access values as objects:
echo $obj->animal; // Outputs dog
echo $obj->name; // Outputs simon

No need to create a class or Function to accomplish it.

Generate CSV file and send as Email attachment PHP

generate-csv-then-send-to-email

Recently I was tasked to create a module that will automatically generate a CSV report then send it to the admin email every month. The following code worked for me, which is included in a separate PHP file. To achieve a monthly notification email, you can use www.setcronjob.com which is basically a time-based scheduler that can be configured to visit your PHP link anytime depending on the schedule you set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function create_csv_string($data) {
   
    mysql_connect(HOST, USERNAME, PASSWORD);
    mysql_select_db(DATABASE);
   
    $data = mysql_query('SELECT id, company, name, company_account_number, email, phone_number, invoice FROM carlofontanos_table');

    // Open temp file pointer
    if (!$fp = fopen('php://temp', 'w+')) return FALSE;
   
    fputcsv($fp, array('ID', 'Company', 'Name', 'Company Account Number', 'Email', 'Phone Number', 'Invoice'));
   
    // Loop data and write to file pointer
    while ($line = mysql_fetch_assoc($data)) fputcsv($fp, $line);
   
    // Place stream pointer at beginning
    rewind($fp);

    // Return the data
    return stream_get_contents($fp);

}

function send_csv_mail($csvData, $body, $to = 'email@example.com', $subject = 'Website Report', $from = 'noreply@carlofontanos.com') {

    // This will provide plenty adequate entropy
    $multipartSep = '-----'.md5(time()).'-----';

    // Arrays are much more readable
    $headers = array(
        "From: $from",
        "Reply-To: $from",
        "Content-Type: multipart/mixed; boundary="$multipartSep""
    );

    // Make the attachment
    $attachment = chunk_split(base64_encode(create_csv_string($csvData)));

    // Make the body of the message
    $body = "--$multipartSep\r\n"
        . "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\r\n"
        . "Content-Transfer-Encoding: 7bit\r\n"
        . "\r\n"
        . "$body\r\n"
        . "--$multipartSep\r\n"
        . "Content-Type: text/csv\r\n"
        . "Content-Transfer-Encoding: base64\r\n"
        . "Content-Disposition: attachment; filename="Website-Report-" . date("F-j-Y") . ".csv"\r\n"
        . "\r\n"
        . "$attachment\r\n"
        . "--$multipartSep--";

    // Send the email, return the result
    return @mail($to, $subject, $body, implode("\r\n", $headers));

}

$array = array(array(1,2,3,4,5,6,7), array(1,2,3,4,5,6,7), array(1,2,3,4,5,6,7));

send_csv_mail($array, "Website Report \r\n \r\n www.carlofontanos.com");

If you just want to generate a CSV File and make it available for download as soon as you access the page, then you can use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

$output = fopen('php://output', 'w');

fputcsv($output, array('ID', 'Company', 'Name', 'Company Account Number', 'Email', 'Phone Number', 'Invoice'));

mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DATABASE);

$rows = mysql_query('SELECT id, company, name, company_account_number, email, phone_number, invoice FROM transaxle_rewards_data');

while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

Building a Real-Time Chat Application Using Pusher

824b1c56-87f0-11e1-9712-8f15a4b24539

Demo

WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. In this tutorial we are going to create a simple chat application using Pusher. Pusher is a simple hosted API for quickly, easily and securely adding realtime bi-directional functionality via WebSockets to web and mobile apps, or any other Internet connected device.

Browser Support

Old browsers do not support WebSockets, you need latest browser that supports HTML5 WebSocket features, Please see caniuse.com to find-out all WebSocket supported browsers.

Scripts we need for our Chat Application:

  • jQuery
  • Pusher
  • Bootstrap JS and CSS (For the UI)
  • Bootbox (For our alert box)
  • Custom Styles

Create a Pusher Account

Step 1. Create an account at www.pusher.com
Step 2. Login to your pusher account then create an App, name it anything you want.
Step 3. After you have successfully created your app – the following will be generated: app_id, key, and secret.
Step 4. Go over the codes in this tutorial and replace the following: ‘your_app_id’, ‘your_app_key’, ‘your_app_secret’ with your app_id, key, and secret.
Step 5. Test the chat application in your server or local machine. Use 2 different browsers for the testing.


The Tutorial

Include the following code in the header part of your file.

1
2
3
4
5
6
7
8
9
10
11
12
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript" ></script>
<script src="//js.pusher.com/2.2/pusher.min.js" type="text/javascript" type="text/javascript" ></script>   
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" type="text/javascript" ></script>  
<script src="//cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.3.0/bootbox.min.js" type="text/javascript" ></script>

<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<style = "text/css">
<!--       
.messages_display {height: 300px; overflow: auto;}     
.messages_display .message_item {padding: 0; margin: 0; }      
.bg-danger {padding: 10px;} -->
</style>

Create the chat form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div class = "container">      
    <div class = "col-md-6 chat_box">                      
        <div class = "form-control messages_display"></div>        
        <br />                     
        <div class = "form-group">             
            <label>Name</label>            
            <input type = "text" class = "input_name form-control" placeholder = "Name" />         
        </div>                     
        <div class = "form-group">             
            <label>Message</label>             
            <textarea class = "input_message form-control" placeholder = "Message"></textarea>         
        </div>                     
        <div class = "form-group input_send_holder">               
            <input type = "submit" value = "Send" class = "btn btn-primary input_send" />          
        </div>                 
    </div> 
</div>

Client Side script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<script type="text/javascript">        
// Enter your own Pusher App key
var pusher = new Pusher('your_app_key');
// Enter a unique channel you wish your users to be subscribed in.
var channel = pusher.subscribe('test_channel');
channel.bind('my_event', function(data) {
    // Add the new message to the container
    $('.messages_display').append('<p class = "message_item">' + data.message + '</p>');
    // Display the send button
    $('.input_send_holder').html('<input type = "submit" value = "Send" class = "btn btn-primary input_send" />');
    // Scroll to the bottom of the container when a new message becomes available
    $(".messages_display").scrollTop($(".messages_display")[0].scrollHeight);
});

// AJAX request
function ajaxCall(ajax_url, ajax_data) {
    $.ajax({
        type: "POST",
        url: ajax_url,
        dataType: "json",
        data: ajax_data,
        success: function(response, textStatus, jqXHR) {
            console.log(jqXHR.responseText);
        },
        error: function(msg) {}
    });
}

// Trigger for the Enter key when clicked.
$.fn.enterKey = function(fnc) {
    return this.each(function() {
        $(this).keypress(function(ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        });
    });
}

// Send the Message
$('body').on('click', '.chat_box .input_send', function(e) {
    e.preventDefault();
   
    var message = $('.chat_box .input_message').val();
    var name = $('.chat_box .input_name').val();
   
    // Validate Name field
    if (name === '') {
        bootbox.alert('<br /><p class = "bg-danger">Please enter a Name.</p>');
   
    } else if (message !== '') {
        // Define ajax data
        var chat_message = {
            name: $('.chat_box .input_name').val(),
            message: '<strong>' + $('.chat_box .input_name').val() + '</strong>: ' + message
        }
        // Send the message to the server
        ajaxCall('message_relay.php', chat_message);
       
        // Clear the message input field
        $('.chat_box .input_message').val('');
        // Show a loading image while sending
        $('.input_send_holder').html('<input type = "submit" value = "Send" class = "btn btn-primary" disabled /> &nbsp;<img src = "loading.gif" />');
    }
});

// Send the message when enter key is clicked
$('.chat_box .input_message').enterKey(function(e) {
    e.preventDefault();
    $('.chat_box .input_send').click();
});
</script>

Server Side Script (message_relay.php):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
require('lib/Pusher.php');

// Change the following with your app details:
// Create your own pusher account @ www.pusher.com
$app_id = 'your_app_id'; // App ID
$app_key = 'your_app_key'; // App Key
$app_secret = 'your_app_secret'; // App Secret
$pusher = new Pusher($app_key, $app_secret, $app_id);

// Check the receive message
if(isset($_POST['message']) && !empty($_POST['message'])) {    
    $data['message'] = $_POST['message'];  
   
    // Return the received message
    if($pusher->trigger('test_channel', 'my_event', $data)) {              
        echo 'success';        
    } else {       
        echo 'error';  
    }
}

Simple File Upload with PHP

simple-file-upload-with-php-screenshot

Demo Download

The Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$message = '';

if(isset($_POST['submit'])){
   
    // Check if there is an error
    if(!$_FILES['photo']['error']){
       
        // Limit file size to 1MB
        if($_FILES['photo']['size'] > (1024000)){
            $message = '<p class = "bg-danger">Oops!  The size of your file is too large.</p>';
       
        } else {       
            // Replace file name spaces and convert to lower case.
            $new_file_name = str_replace(' ', '_', strtolower($_FILES['photo']['name']));
       
            // Check if file was uploaded
            if(move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name)){
                $message = '<p class = "bg-success">File successfully uploaded</p>';
            }
        }
       
    } else {
        // Output all errors
        $message = '<p class = "bg-danger">Oops!  Your upload triggered the following error:  '.$_FILES['photo']['error'] . '</p>';
    }
     
}

Accessing HTML DOM Elements with PHP

extract-url-contents

Demo Download Demo

 

Tutorial

Download Library

Include the Library

1
include_once("include/simple_html_dom.inc.php");

Get URL Content:

1
2
3
$get_url = 'https://carlofontanos.com';
$get_content = file_get_html($get_url);
print_r($get_content);

Get Page Title:

1
2
3
4
5
$get_content = file_get_html($get_url);
foreach($get_content->find('title') as $element) {
    $page_title = $element->plaintext;
    print_r($page_title);
}

Get Body Text

1
2
3
4
5
6
7
$get_content = file_get_html($get_url);
foreach($get_content->find('body') as $element) {
    $page_body = trim($element->plaintext);
    $pos = strpos($page_body, ' ', 200); //Find the numeric position to substract
    $page_body = substr($page_body,0,$pos ); //shorten text to 200 chars
    print_r($page_body . '<br />');
}

Get all images in the content:

1
2
3
4
5
6
$image_urls = array();
foreach($get_content->find('img') as $element) {
    if($element->src){
        echo '<img src ="' . $element->src . '" width = "100" height = "100" />';
    }  
}

Post Class for Resume Database

Useful functions for building a resume database in WordPress

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
<?php
/**
 * @ Author: Carl Victor Fontanos.
 * @ Class: NGP_Posts
 *
 */



add_action('wp_ajax_cvf_ngp_frontend_display_resumes', array('NGP_Posts', 'cvf_ngp_frontend_display_resumes') );
add_action('wp_ajax_nopriv_cvf_ngp_frontend_display_resumes', array('NGP_Posts', 'cvf_ngp_frontend_display_resumes') );

add_action('wp_ajax_cvf_ngp_create_new_resume', array('NGP_Posts', 'cvf_ngp_create_new_resume') );
add_action('wp_ajax_nopriv_cvf_ngp_create_new_resume', array('NGP_Posts', 'cvf_ngp_create_new_resume') );

add_action('wp_ajax_cvf_ngp_create_new_resume_form', array('NGP_Posts', 'cvf_ngp_create_new_resume_form') );
add_action('wp_ajax_nopriv_cvf_ngp_create_new_resume_form', array('NGP_Posts', 'cvf_ngp_create_new_resume_form') );

add_action('wp_ajax_cvf_ngp_pagination_load_resumes', array('NGP_Posts', 'cvf_ngp_pagination_load_resumes') );
add_action('wp_ajax_nopriv_cvf_ngp_pagination_load_resumes', array('NGP_Posts', 'cvf_ngp_pagination_load_resumes') );

add_action('wp_ajax_cvf_ngp_preveiw_resume', array('NGP_Posts', 'cvf_ngp_preveiw_resume') );
add_action('wp_ajax_nopriv_cvf_ngp_preveiw_resume', array('NGP_Posts', 'cvf_ngp_preveiw_resume') );

add_action('wp_ajax_cvf_ngp_edit_resume', array('NGP_Posts', 'cvf_ngp_edit_resume') );
add_action('wp_ajax_nopriv_cvf_ngp_edit_resume', array('NGP_Posts', 'cvf_ngp_edit_resume') );

add_action('wp_ajax_cvf_ngp_update_resume', array('NGP_Posts', 'cvf_ngp_update_resume') );
add_action('wp_ajax_nopriv_cvf_ngp_update_resume', array('NGP_Posts', 'cvf_ngp_update_resume') );

add_action('wp_ajax_cvf_ngp_delete_attachment', array('NGP_Posts', 'cvf_ngp_delete_attachment') );
add_action('wp_ajax_nopriv_cvf_ngp_delete_attachment', array('NGP_Posts', 'cvf_ngp_delete_attachment') );

add_action('wp_ajax_cvf_ngp_delete_resume', array('NGP_Posts', 'cvf_ngp_delete_resume') );
add_action('wp_ajax_nopriv_cvf_ngp_delete_resume', array('NGP_Posts', 'cvf_ngp_delete_resume') );

add_action('before_delete_post', array('NGP_Posts', 'cvf_ngp_delete_all_resume_attachments') );

add_action('init', array('NGP_Posts', 'cvf_ngp_register_resume_post_type') );

add_action('init', array('NGP_Posts', 'cvf_ngp_register_blog_post_type') );
add_action('init', array('NGP_Posts', 'cvf_ngp_create_blog_categories') );

add_action('generate_rewrite_rules', array('NGP_Posts', 'cvf_ngp_blog_datearchives_rewrite_rules') );

add_action( 'admin_menu', array('NGP_Posts', 'cvf_ngp_remove_menus') );

add_filter ('wp_mail_content_type', array('NGP_Posts', 'cvf_ngp_mail_content_type') );



class NGP_Posts {

    public function __construct() {}

    public static function cvf_ngp_get_category_posts($category_slug, $limit) {

        global $post;

        $args = array(
            'numberposts' => $limit,
            'category_name' => $category_slug,
            'order' => 'ASC',
            'post_status' => 'publish'
        );

        $posts = get_posts( $args );

        return $posts;

    }

    public static function cvf_ngp_get_forums($limit, $type){

        if($type = 'category'){
            $post_parent = 'post_parent = 0';
        } else {
            $post_parent = 'post_parent > 0';
        }
        global $wpdb;

        $table = $wpdb->prefix . 'posts';
        $forums = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM $table WHERE post_type = 'forum' AND $post_parent
            ORDER BY post_title ASC LIMIT %d
            "
, $limit ));

        return $forums;
    }

    public static function cvf_ngp_register_resume_post_type() {

        $labels = array(
            'name'                  => _x('NGP Resumes', 'post type general name'),
            'singular_name'         => _x('Resume', 'post type singular name'),
            'all_items'             => _x('All Resumes', 'post type name'),
            'add_new'               => _x('Create New Resume', 'new post'),
            'add_new_item'          => __('Create New Resume'),
            'edit_item'             => __('Edit Resume'),
            'new_item'              => __('New Resume'),
            'view_item'             => __('View Resume'),
            'search_items'          => __('Search Resumes'),
            'not_found'             => __('No resumes found'),
            'not_found_in_trash'    => __('No resumes found in the Trash'),
            'parent_item_colon'     => ''
        );
        $args = array(
            'labels'                => $labels,
            'public'                => true,
            'publicly_queryable'    => true,
            'show_ui'               => true,
            'query_var'             => true,
            'rewrite'               => true,
            'capability_type'       => 'post',
            'hierarchical'          => false,
            'menu_position'         => 8,
            'supports'              => array('title','editor','thumbnail')
        );

        register_post_type( 'resume' , $args );
    }
   
    public static function cvf_ngp_register_blog_post_type() {

        $labels = array(
            'name'                  => _x('NGP Blogs', 'post type general name'),
            'singular_name'         => _x('Blog', 'post type singular name'),
            'all_items'             => _x('All Blogs', 'post type name'),
            'add_new'               => _x('Create New Blog', 'new post'),
            'add_new_item'          => __('Create New Blog'),
            'edit_item'             => __('Edit Blog'),
            'new_item'              => __('New Blog'),
            'view_item'             => __('View Blog'),
            'search_items'          => __('Search Blogs'),
            'not_found'             => __('No blogs found'),
            'not_found_in_trash'    => __('No blogs found in the Trash'),
            'parent_item_colon'     => ''
        );
        $args = array(
            'labels'                => $labels,
            'public'                => true,
            'publicly_queryable'    => true,
            'show_ui'               => true,
            'query_var'             => true,
            'rewrite'               => true,
            'capability_type'       => 'post',
            'hierarchical'          => false,
            'menu_position'         => 8,
            'has_archive'           => true,
            'supports'              => array('title','editor','thumbnail')
        );

        register_post_type( 'blog' , $args );
    }
   
    public static function cvf_ngp_create_blog_categories() {
        $labels = array(
            'name'              => _x( 'Blog Categories', 'taxonomy general name' ),
            'singular_name'     => _x( 'Blog Category', 'taxonomy singular name' ),
            'search_items'      => __( 'Search Blog Categories' ),
            'all_items'         => __( 'All Blog Categories' ),
            'parent_item'       => __( 'Parent Blog Category' ),
            'parent_item_colon' => __( 'Parent Blog Category:' ),
            'edit_item'         => __( 'Edit Blog Category' ),
            'update_item'       => __( 'Update Blog Category' ),
            'add_new_item'      => __( 'Create New Blog Category' ),
            'new_item_name'     => __( 'New Blog Category Name' ),
            'menu_name'         => __( 'Categories' ),
        );

        $args = array(
            'hierarchical'      => true,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => 'blog-category' ),
        );

        register_taxonomy( 'blog_categories', array( 'blog' ), $args );
    }

    public static function cvf_ngp_frontend_display_resumes() {

        global $wpdb, $current_user;
        $msg = '';

        if(isset($_POST['page'])){
            $page = sanitize_text_field($_POST['page']);
            $cur_page = $page;
            $page -= 1;
            $per_page = 10;
            $previous_btn = true;
            $next_btn = true;
            $first_btn = true;
            $last_btn = true;
            $start = $page * $per_page;

            $posts = $wpdb->prefix . "posts";
            $postmeta = $wpdb->prefix . "postmeta";

            $where_name = ''; $where_experience = ''; $where_education = ''; $where_country = ''; $where_industry = '';

            if(!empty($_POST['ngp_name'])){
                $where_name = ' AND (p.post_title LIKE "%%' . $_POST['ngp_name'] . '%%") ';
            }
            if(!empty($_POST['ngp_industry'])){
                $where_industry = ' AND (m1.meta_value LIKE "%%' . $_POST['ngp_industry'] . '%%") ';
            }
            if(!empty($_POST['ngp_experience'])){
                $where_experience = ' AND (m2.meta_value LIKE "%%' . $_POST['ngp_experience'] . '%%") ';
            }
            if(!empty($_POST['ngp_country'])){
                $where_country = ' AND (m3.meta_value LIKE "%%' . $_POST['ngp_country'] . '%%") ';
            }
            if(!empty($_POST['ngp_education'])){
                $where_education = ' AND (m4.meta_value LIKE "%%' . $_POST['ngp_education'] . '%%") ';
            }

            $joins = '
                LEFT JOIN '
. $postmeta . ' m1 ON p.ID = m1.post_id AND m1.meta_key = "ngp_industry"
                LEFT JOIN '
. $postmeta . ' m2 ON p.ID = m2.post_id AND m2.meta_key = "ngp_experience"
                LEFT JOIN '
. $postmeta . ' m3 ON p.ID = m3.post_id AND m3.meta_key = "ngp_country"
                LEFT JOIN '
. $postmeta . ' m4 ON p.ID = m4.post_id AND m4.meta_key = "ngp_education" ';

            $all_user_resumes = $wpdb->get_results($wpdb->prepare("
                SELECT p.ID, p.post_title, m1.meta_value as 'ngp_industry', m2.meta_value as 'ngp_experience', m3.meta_value as 'ngp_country', m4.meta_value as 'ngp_education'
                FROM "
. $posts . ' p ' . $joins . "
                WHERE p.post_type = 'resume' AND p.post_status = 'publish' "
. $where_name . $where_industry . $where_experience . $where_country . $where_education . "
                ORDER BY p.post_date DESC LIMIT %d, %d"
, $start, $per_page ) );


            $count = $wpdb->get_var($wpdb->prepare("
                SELECT COUNT(p.ID)
                FROM "
. $posts . ' p ' . $joins . "
                WHERE p.post_type = 'resume' AND post_status = 'publish' "
. $where_name . $where_industry . $where_experience . $where_country . $where_education, array() ) );

            $msg .= '
            <br class = "clear" />

            <table class="table table-striped table-hover table-responsive table-resume">
                <tr>
                    <th>Name</th>
                    <th>Industry</th>
                    <th>Experience</th>
                    <th>Education</th>             
                    <th>Country</th>
                </tr>'
;

            if($all_user_resumes):
                foreach($all_user_resumes as $key => $resume):
                    $msg .= '
                    <tr class = "resume_'
. $resume->ID . '">
                        <td><a href="'
.get_permalink($resume->ID).'" id = "resume-'.$resume->ID.'" class = "resume_title">' . $resume->post_title . '</a></td>
                        <td>'
. $resume->ngp_industry .'</td>
                        <td>'
. $resume->ngp_experience .'</td>
                        <td>'
. $resume->ngp_education .'</td>                 
                        <td>'
. $resume->ngp_country .'</td>
                    </tr>'
;
                endforeach;
            else:
                $msg .= '<tr><td colspan="5">No results found.</td></tr>';
            endif;

            $msg .= '</table>';

            $msg = "<div class='cvf-universal-content'>" . $msg . "</div><br class = 'clear' />";

            $no_of_paginations = ceil($count / $per_page);

            if ($cur_page >= 7) {
                $start_loop = $cur_page - 3;
                if ($no_of_paginations > $cur_page + 3)
                    $end_loop = $cur_page + 3;
                else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
                    $start_loop = $no_of_paginations - 6;
                    $end_loop = $no_of_paginations;
                } else {
                    $end_loop = $no_of_paginations;
                }
            } else {
                $start_loop = 1;
                if ($no_of_paginations > 7)
                    $end_loop = 7;
                else
                    $end_loop = $no_of_paginations;
            }

            $pag_container .= "
            <div class='cvf-universal-pagination'>
                <ul>"
;

            if ($first_btn && $cur_page > 1) {
                $pag_container .= "<li p='1' class='active'>First</li>";
            } else if ($first_btn) {
                $pag_container .= "<li p='1' class='inactive'>First</li>";
            }

            if ($previous_btn && $cur_page > 1) {
                $pre = $cur_page - 1;
                $pag_container .= "<li p='$pre' class='active'>Previous</li>";
            } else if ($previous_btn) {
                $pag_container .= "<li class='inactive'>Previous</li>";
            }
            for ($i = $start_loop; $i <= $end_loop; $i++) {

                if ($cur_page == $i)
                    $pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
                else
                    $pag_container .= "<li p='$i' class='active'>{$i}</li>";
            }

            if ($next_btn && $cur_page < $no_of_paginations) {
                $nex = $cur_page + 1;
                $pag_container .= "<li p='$nex' class='active'>Next</li>";
            } else if ($next_btn) {
                $pag_container .= "<li class='inactive'>Next</li>";
            }

            if ($last_btn && $cur_page < $no_of_paginations) {
                $pag_container .= "<li p='$no_of_paginations' class='active'>Last</li>";
            } else if ($last_btn) {
                $pag_container .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
            }

            $pag_container = $pag_container . "
                </ul>
            </div>"
;

            echo
            '<div class = "cvf-pagination-content">' . $msg . '</div>' .
            '<div class = "cvf-pagination-nav">' . $pag_container . '</div>';

        }
        exit();
    }

    public static function cvf_ngp_create_new_resume() {

        global $current_user, $wpdb;

        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'create_new_resume') {

            foreach($_POST as $k => $value) {
                $_POST[$k] = sanitize_text_field($value);
            }

            $ngp_resume = array(
                'post_title'    => wp_strip_all_tags( $_POST['ngp_name'] ),
                'post_status'   => 'publish',
                'post_type'     => 'resume',
                'post_author'   => $current_user->ID,
            );

            $post_id = wp_insert_post( $ngp_resume );

            update_post_meta($post_id, 'ngp_phone', $_POST['ngp_phone']);
            update_post_meta($post_id, 'ngp_industry', $_POST['ngp_industry']);
            update_post_meta($post_id, 'ngp_headline', $_POST['ngp_headline']);
            update_post_meta($post_id, 'ngp_experience', $_POST['ngp_experience']);
            update_post_meta($post_id, 'ngp_education', $_POST['ngp_education']);
            update_post_meta($post_id, 'ngp_country', $_POST['ngp_country']);
            update_post_meta($post_id, 'ngp_zipcode', $_POST['ngp_zipcode']);
           
            echo $post_id;
           
            $subsribed_users = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM wp_users u
            LEFT JOIN wp_usermeta um ON u.ID = um.user_id
            WHERE um.meta_key = 'ngp_subscribe_joblistings'
            AND um.meta_value = 1"
, array() ));
           
            foreach($subsribed_users as $key => $user) {
               
                $from = get_option('admin_email');
                $headers = 'From: NGPPortfolioCo <"' . $from . '">';
                $subject = "New Job Application Submitted ". $_POST['ngp_headline'] . " (" . $_POST['ngp_industry'] .") - " . $_POST['ngp_name'];
               
                ob_start();
                           
               
                echo '
                <p>Dear '
. $user->display_name . ', <br />
                A new job was posted on NGPPortfolioCo, and the details can be found bellow:
                </p><br />
               
                <table style="width:100%; color: #333; font-family: Arial, Helvetica, sans-serif;" border = "1" >
                    <tr>
                        <th colspan = "2" style = "font-size: 30px; padding: 10px 0; background: #5C0F26; color: #fff; ">NGPPortfolioCO</th>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Country</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_country', true) . '</td>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Country</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_country', true) . '</td>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Zip Code</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_zipcode', true) . '</td>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Education</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_education', true) . '</td>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Experience</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_experience', true) . '</td>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Phone</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_phone', true) . '</td>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Industry</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_industry', true) . '</td>
                    </tr>
                    <tr>
                        <th style = "padding: 10px; margin: 10px;">Job Title / Headline</th>
                        <td style = "padding: 10px;">'
. get_post_meta($post_id, 'ngp_headline', true) . '</td>
                    </tr>
                    </tr>
                        <th style = "padding: 10px; margin: 10px;">Resume</th>
                        <td style = "padding: 10px;">Go to our <a href = "'
. home_url() . '">website</a> to view the attached resume</td>
                    </tr>
                </table>
                <br />
                <p>As a member of NGPPortfolioCo, we will send you new job listings. To view other joba, search our list of current openings:'
. home_url('/resume-database/') . '</p>         
                <br />
                <p>Thank you,<br />
                NGPPortfolioCo Team</p>                
                '
;
                   
                $message = ob_get_contents();
               
                ob_end_clean();

                wp_mail($user->user_email, $subject, $message, $headers);
            }
        }

        exit();
    }
   
    public static function cvf_ngp_mail_content_type() {
        return 'text/html';
    }



    public static function cvf_ngp_create_new_resume_form() {

        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'create_new_resume_form') {

            $ngp_field = self::cvf_ngp_get_all_pre_resume_fields(166);

            $new_resume_form .= '
            <h1>Step 1</h1>
            <hr /><br />

            <div class = "col-sm-12 pads">
                <div class = "create-new-resume-response"></div>
            </div>

            <div class = "ngp-create-new-resume-form">
                <div class = "col-sm-6 pads">
                    <div class="form-group">
                        <label for="ngp_name">Full Name</label><br />
                        <input type="text" name="ngp_name" class="form-control ngp_name" />
                    </div>'
;

                    foreach( array_slice($ngp_field, 0, 5) as $field ):
                        $ngp_val = get_post_meta(166, $field->meta_key, false);

                        if ($ngp_val[0]['type'] == 'text' || $ngp_val[0]['type'] == 'number'):
                            $new_resume_form .= '
                            <div class="form-group">
                                <label for="'
. $ngp_val[0]['name'] . '">' . $ngp_val[0]['label'] . ':</label><br />
                                <input type="text" name="'
. $ngp_val[0]['name'] . '" class="form-control ' . $ngp_val[0]['name'] . '" />
                            </div>'
;

                        elseif ($ngp_val[0]['type'] == 'select'):
                            $new_resume_form .= '
                            <div class="form-group">
                                <label for="'
. $ngp_val[0]['name'] . '">' . $ngp_val[0]['label'] . ':</label><br />

                                <select id = "'
. $ngp_val[0]['name'] . '" name="' . $ngp_val[0]['name'] . '" class="ngp-select form-control ' . $ngp_val[0]['name'] . '">
                                    <option value="">- Select '
. $ngp_val[0]['label'] . ' -</option>';
                                    foreach ($ngp_val[0]['choices'] as $val):
                                        $new_resume_form .= '<option value="' . $val . '">' . $val . '</option>';
                                    endforeach;
                                $new_resume_form .= '
                                </select>
                            </div>'
;

                        endif;

                    endforeach;

                $new_resume_form .= '
                </div>

                <div class = "col-sm-6 pads">'
;
                    foreach( array_slice($ngp_field, 5, 12) as $field ):
                        $ngp_val = get_post_meta(166, $field->meta_key, false);

                        if ($ngp_val[0]['type'] == 'text' || $ngp_val[0]['type'] == 'number'):
                            $new_resume_form .= '
                            <div class="form-group">
                                <label for="'
. $ngp_val[0]['name'] . '">' . $ngp_val[0]['label'] . ':</label><br />
                                <input type="text" name="'
. $ngp_val[0]['name'] . '" class="form-control ' . $ngp_val[0]['name'] . '" />
                            </div>'
;

                        elseif ($ngp_val[0]['type'] == 'select'):
                            $new_resume_form .= '
                            <div class="form-group">
                                <label for="'
. $ngp_val[0]['name'] . '">' . $ngp_val[0]['label'] . ':</label><br />

                                <select id = "'
. $ngp_val[0]['name'] . '" name="' . $ngp_val[0]['name'] . '" class="ngp-select form-control ' . $ngp_val[0]['name'] . '">
                                    <option value="">- Select '
. $ngp_val[0]['label'] . ' -</option>';
                                    foreach ($ngp_val[0]['choices'] as $val):
                                        $new_resume_form .= '<option value="' . $val . '">' . $val . '</option>';
                                    endforeach;
                                $new_resume_form .= '
                                </select>
                            </div>'
;
                        endif;
                    endforeach;

                    $new_resume_form .= '
                    <input type = "submit" value = "Submit Resume" class = "btn btn-primary create-new-resume" />
                </div>
            </div>

            <br class = "clear" /><br />
            '
;

            echo $new_resume_form;

        }

        exit();
    }

    public static function cvf_ngp_get_all_pre_resume_fields($post_id) {

        global $wpdb;

        $table = $wpdb->prefix . 'postmeta';
        $pre_resume_fields = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM $table WHERE post_id = %d AND meta_key LIKE '%%field_%%'"
, $post_id ));

        return $pre_resume_fields;

    }

    public static function cvf_ngp_get_all_user_resumes() {

        global $wpdb, $current_user;

        $table = $wpdb->prefix . 'posts';
        $user_resumes = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM $table WHERE post_author = %d
            AND post_type = 'resume' AND post_status = 'publish'"
, $current_user->ID ));

        return $user_resumes;

    }

    public static function cvf_ngp_pagination_load_resumes() {

        global $wpdb, $current_user;
        $msg = '';

        if(isset($_POST['page'])){
            $page = sanitize_text_field($_POST['page']);
            $cur_page = $page;
            $page -= 1;
            $per_page = 5;
            $previous_btn = true;
            $next_btn = true;
            $first_btn = true;
            $last_btn = true;
            $start = $page * $per_page;

            $posts = $wpdb->prefix . "posts";
            $postmeta = $wpdb->prefix . "postmeta";

            $where_name = ''; $where_experience = ''; $where_education = ''; $where_country = ''; $where_industry = '';

            if(!empty($_POST['ngp_name'])){
                $where_name = ' AND (p.post_title LIKE "%%' . $_POST['ngp_name'] . '%%") ';
            }
            if(!empty($_POST['ngp_industry'])){
                $where_industry = ' AND (m1.meta_value LIKE "%%' . $_POST['ngp_industry'] . '%%") ';
            }
            if(!empty($_POST['ngp_experience'])){
                $where_experience = ' AND (m2.meta_value LIKE "%%' . $_POST['ngp_experience'] . '%%") ';
            }
            if(!empty($_POST['ngp_country'])){
                $where_country = ' AND (m3.meta_value LIKE "%%' . $_POST['ngp_country'] . '%%") ';
            }
            if(!empty($_POST['ngp_education'])){
                $where_education = ' AND (m4.meta_value LIKE "%%' . $_POST['ngp_education'] . '%%") ';
            }

            $joins = '
                LEFT JOIN '
. $postmeta . ' m1 ON p.ID = m1.post_id AND m1.meta_key = "ngp_industry"
                LEFT JOIN '
. $postmeta . ' m2 ON p.ID = m2.post_id AND m2.meta_key = "ngp_experience"
                LEFT JOIN '
. $postmeta . ' m3 ON p.ID = m3.post_id AND m3.meta_key = "ngp_country"
                LEFT JOIN '
. $postmeta . ' m4 ON p.ID = m4.post_id AND m4.meta_key = "ngp_education" ';

            $all_user_resumes = $wpdb->get_results($wpdb->prepare("
                SELECT p.ID, p.post_title, m1.meta_value as 'ngp_industry', m2.meta_value as 'ngp_experience', m3.meta_value as 'ngp_country', m4.meta_value as 'ngp_education'
                FROM "
. $posts . ' p ' . $joins . "
                WHERE p.post_type = 'resume' AND p.post_status = 'publish' AND p.post_author = %d "
. $where_name . $where_industry . $where_experience . $where_country . $where_education . "
                ORDER BY p.post_date DESC LIMIT %d, %d"
, $current_user->ID, $start, $per_page ) );


            $count = $wpdb->get_var($wpdb->prepare("
                SELECT COUNT(p.ID)
                FROM "
. $posts . ' p ' . $joins . "
                WHERE p.post_type = 'resume' AND post_status = 'publish' AND post_author = %d "
. $where_name . $where_industry . $where_experience . $where_country . $where_education, $current_user->ID ) );

            $msg .= '
            <br class = "clear" />

            <table class="table table-striped table-hover table-responsive table-resume">
                <tr>
                    <th>Name</th>
                    <th>Experience</th>
                    <th>Education</th>
                    <th>Country</th>
                    <th>Action</th>
                </tr>'
;

            if($all_user_resumes):
                foreach($all_user_resumes as $key => $resume):
                    $msg .= '
                    <tr class = "resume_'
. $resume->ID . '">
                        <td><a href="#" id = "resume-'
.$resume->ID.'" class = "resume_title">' . $resume->post_title . '</a></td>
                        <td>'
. $resume->ngp_experience .'</td>
                        <td>'
. $resume->ngp_education .'</td>
                        <td>'
. $resume->ngp_country .'</td>
                        <td>
                            <a href = "#" title = "Edit" class = "edit_resume" id = "edit-'
. $resume->ID . '"><span class = "glyphicon glyphicon-pencil"></span></a>&nbsp;
                            <a href = "#" title = "Delete" class = "delete_resume" id = "del-'
. $resume->ID . '"><span class = "glyphicon glyphicon-trash"></span></a>
                        </td>
                    </tr>'
;
                endforeach;
            else:
                $msg .= '<tr><td colspan="5">No results found.</td></tr>';
            endif;

            $msg .= '</table>';

            $msg = "<div class='cvf-universal-content'>" . $msg . "</div><br class = 'clear' />";

            $no_of_paginations = ceil($count / $per_page);

            if ($cur_page >= 7) {
                $start_loop = $cur_page - 3;
                if ($no_of_paginations > $cur_page + 3)
                    $end_loop = $cur_page + 3;
                else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
                    $start_loop = $no_of_paginations - 6;
                    $end_loop = $no_of_paginations;
                } else {
                    $end_loop = $no_of_paginations;
                }
            } else {
                $start_loop = 1;
                if ($no_of_paginations > 7)
                    $end_loop = 7;
                else
                    $end_loop = $no_of_paginations;
            }

            $pag_container .= "
            <div class='cvf-universal-pagination'>
                <ul>"
;

            if ($first_btn && $cur_page > 1) {
                $pag_container .= "<li p='1' class='active'>First</li>";
            } else if ($first_btn) {
                $pag_container .= "<li p='1' class='inactive'>First</li>";
            }

            if ($previous_btn && $cur_page > 1) {
                $pre = $cur_page - 1;
                $pag_container .= "<li p='$pre' class='active'>Previous</li>";
            } else if ($previous_btn) {
                $pag_container .= "<li class='inactive'>Previous</li>";
            }
            for ($i = $start_loop; $i <= $end_loop; $i++) {

                if ($cur_page == $i)
                    $pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
                else
                    $pag_container .= "<li p='$i' class='active'>{$i}</li>";
            }

            if ($next_btn && $cur_page < $no_of_paginations) {
                $nex = $cur_page + 1;
                $pag_container .= "<li p='$nex' class='active'>Next</li>";
            } else if ($next_btn) {
                $pag_container .= "<li class='inactive'>Next</li>";
            }

            if ($last_btn && $cur_page < $no_of_paginations) {
                $pag_container .= "<li p='$no_of_paginations' class='active'>Last</li>";
            } else if ($last_btn) {
                $pag_container .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
            }

            $pag_container = $pag_container . "
                </ul>
            </div>"
;

            echo
            '<div class = "cvf-pagination-content">' . $msg . '</div>' .
            '<div class = "cvf-pagination-nav">' . $pag_container . '</div>';

        }
        exit();
    }

    public static function cvf_ngp_preveiw_resume() {

        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'preveiw_resume') {

            $resume_id = $_POST['resume_id'];
            $resume = get_post($resume_id);
           
            $avatar_id = get_post_meta($resume_id, 'ngp_avatar', true);
            $avatar_url = wp_get_attachment_image_src($avatar_id);
           
            if($avatar_url[0]) {
                $avatar = '<img src = "' . $avatar_url[0] . '" class = "img-thumbnail" width = "135" />';
            } else {
                $avatar = '<img src = "' . get_template_directory_uri() . '/images/default_avatar.jpg" class = "img-thumbnail">';
            }
           
            $preview_resume .= '
                <div class = "preview_resume_display">
                    <a href = "#" class = "cvf_goback">Go Back</a>

                    <div class = "col-md-12">
                        <div class = "preview_resume_messages"></div>
                        <br />
                        <div class = "col-sm-2 pads">'
. $avatar . '</div>         
                        <div class = "col-sm-10 pads">
                            <h1>'
. $resume->post_title .'</h1>
                            <hr />
                        </div>             
                    </div>
                   
                    <br class = "clear" /><br />

                    <div class = "col-md-12">
                        <table class = "table table-striped">
                            <tr class="success">
                                <th >Country</th>
                                <td>'
. get_post_meta($resume_id, 'ngp_country', true) . '</td>
                            </tr>
                            <tr class="success">
                                <th>Zip Code</th>
                                <td>'
. get_post_meta($resume_id, 'ngp_zipcode', true) . '</td>
                            </tr>
                            <tr>
                                <th>Education</th>
                                <td>'
. get_post_meta($resume_id, 'ngp_education', true) . '</td>
                            </tr>
                            <tr class="info">
                                <th>Experience</th>
                                <td>'
. get_post_meta($resume_id, 'ngp_experience', true) . '</td>
                            </tr>
                            <tr>
                                <th>Phone</th>
                                <td>'
. get_post_meta($resume_id, 'ngp_phone', true) . '</td>
                            </tr>
                            <tr>
                                <th>Industry</th>
                                <td>'
. get_post_meta($resume_id, 'ngp_industry', true) . '</td>
                            </tr>
                            <tr class="warning">
                                <th>Job Title / Headline</th>
                                <td>'
. get_post_meta($resume_id, 'ngp_headline', true) . '</td>
                            </tr>
                            </tr>
                                <th>Resume</th>'
;
                               
                                $attahcment_id = get_post_meta($resume_id, 'ngp_resume', true);
                                $attachment = wp_get_attachment_url($attahcment_id);
           
                                if ( $attachment != false ) {
                                    $preview_resume .= '<td><a href = "' . $attachment . '" class = "btn btn-primary">Download Resume</td>';
                                } else {
                                    $preview_resume .= '<td>N/A</td>';
                                }
                            $preview_resume .= '
                            </tr>
                        </table>
                    </div>
                </div>'
;

            echo $preview_resume;

        }
        exit();

    }


    public static function cvf_ngp_edit_resume() {

        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'edit_resume') {

            $resume_id = $_POST['resume_id'];
            $resume = get_post($resume_id);

            $ngp_education = get_post_meta(166, 'field_54602724d1943', false);
            $ngp_experience = get_post_meta(166, 'field_546026eb1d61f', false);
            $ngp_industry = get_post_meta(166, 'field_5460268eaf31f', false);
            $ngp_country = get_post_meta(166, 'field_546027490c53b', false);
            $ngp_phone = get_post_meta($resume_id, 'ngp_phone', false);
            $ngp_headline = get_post_meta($resume_id, 'ngp_headline', false);
            $ngp_zipcode = get_post_meta($resume_id, 'ngp_zipcode', false);
            $ngp_resume = get_post_meta($resume_id, 'ngp_resume', false);
            $ngp_avatar = get_post_meta($resume_id, 'ngp_avatar', false);

            $edit_resume .= '

                <a href = "#" class = "cvf_goback">Go Back</a>

                <div class = "ngp_edit_resume_response"></div>

                <br clsss = "clear" />

                <div class = "ngp_edit_resume">
                    <div class = "col-md-6 pads">
                        <div class="form-group">
                            <label>Full Name:</label><br />
                            <input type = "text" value = "'
. $resume->post_title .'" class = "form-control ngp_name" />
                        </div>

                        <div class="form-group">
                            <label>Phone:</label><br />
                            <input type = "text" value = "'
. $ngp_phone[0] .'" class = "form-control ngp_phone" />
                        </div>

                        <div class="form-group">
                            <label>Industry:</label><br />
                            <select class = "ngp-select form-control ngp_industry">'
;
                                foreach ($ngp_industry[0]['choices'] as $val):
                                    if($val == get_post_meta($resume->ID, 'ngp_industry', true)):
                                        $edit_resume .= '<option value="' . $val . '" selected = "selected">' . $val . '</option>';
                                    else:
                                        $edit_resume .= '<option value="' . $val . '">' . $val . '</option>';
                                    endif;
                                endforeach;
                            $edit_resume .= '
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Headline or Job Title:</label><br />
                            <input type = "text" value = "'
. $ngp_headline[0] .'" class = "form-control ngp_headline" />
                        </div>

                        <div class="form-group">
                            <label>Experience:</label><br />
                            <select class = "ngp-select form-control ngp_experience">'
;
                                foreach ($ngp_experience[0]['choices'] as $val):
                                    if($val == get_post_meta($resume->ID, 'ngp_experience', true)):
                                        $edit_resume .= '<option value="' . $val . '" selected = "selected">' . $val . '</option>';
                                    else:
                                        $edit_resume .= '<option value="' . $val . '">' . $val . '</option>';
                                    endif;
                                endforeach;
                            $edit_resume .= '
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Education:</label><br />
                            <select class = "ngp-select form-control ngp_education">'
;
                                foreach ($ngp_education[0]['choices'] as $val):
                                    if($val == get_post_meta($resume->ID, 'ngp_education', true)):
                                        $edit_resume .= '<option value="' . $val . '" selected = "selected">' . $val . '</option>';
                                    else:
                                        $edit_resume .= '<option value="' . $val . '">' . $val . '</option>';
                                    endif;
                                endforeach;
                            $edit_resume .= '
                            </select>
                        </div>
                    </div>

                    <div class = "col-md-6 pads">
                        <div class="form-group">
                            <label>Country:</label><br />
                            <select class = "ngp-select form-control ngp_country">'
;
                                foreach ($ngp_country[0]['choices'] as $val):
                                    if($val == get_post_meta($resume->ID, 'ngp_country', true)):
                                        $edit_resume .= '<option value="' . $val . '" selected = "selected">' . $val . '</option>';
                                    else:
                                        $edit_resume .= '<option value="' . $val . '">' . $val . '</option>';
                                    endif;
                                endforeach;
                            $edit_resume .= '
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Zip Code:</label><br />
                            <input type = "text" value = "'
. $ngp_zipcode[0] .'" class = "form-control ngp_zipcode" />
                        </div>
                       
                        <div class = "attachment_resume_holder form-group col-md-6">'
;

                            $attachment = get_post($ngp_resume[0]);

                            if ( $attachment->ID ) {
                                $edit_resume .= '
                                <ul class = "resume-attachment no-margin">
                                    <li><img src = "'
.get_template_directory_uri().'/images/document.png" /></li>
                                    <li>
                                        <p><a href = "'
.$attachment->guid.'" target = "_blank">'.substr($attachment->post_title, 0, 20).'</a></p>
                                        <p>
                                            <a href = "#" class = "delete_attachment" id = "del-'
.$attachment->ID.'">Delete</a> |
                                            <a href = "#" class = "change_attachment" id = "change-'
.$attachment->ID.'" data-toggle="modal" data-target="#upload_file">Change</a>
                                        </p>
                                    </li>
                                </ul>
                                <br class = "clear" />
                                '
;

                            } else {
                                $edit_resume .= '
                                <a href = "#" data-toggle="modal" data-target="#upload_file" class = "btn btn-success"><span class = "glyphicon glyphicon-plus"></span> Add Resume</a><br class = "clear" /><br />'
;
                            }
                       
                        $edit_resume .= '
                        </div>
                       
                        <div class = "avatar_resume_holder form-group col-md-6">'
;
                       
                            $avatar = get_post($ngp_avatar[0]);

                            if ( $avatar->ID ) {
                                $edit_resume .= '
                                <ul class = "resume-attachment no-margin">
                                    <li>'
.wp_get_attachment_image($avatar->ID, array(60,60), 0, array('class' => "img-thumbnail")) .'</li>
                                    <li>
                                        <p><a href = "'
.$avatar->guid.'" target = "_blank">'.$avatar->post_title.'</a></p>
                                        <p>
                                            <a href = "#" class = "delete_avatar" id = "del-'
.$avatar->ID.'">Delete</a> |
                                            <a href = "#" class = "change_attachment" id = "change-'
.$avatar->ID.'" data-toggle="modal" data-target="#upload_avatar">Change</a>
                                        </p>
                                    </li>
                                </ul>
                                <br class = "clear" />
                                '
;

                            } else {
                                $edit_resume .= '
                                <a href = "#" data-toggle="modal" data-target="#upload_avatar" class = "btn btn-success"><span class = "glyphicon glyphicon-upload"></span> Upload Avatar</a><br class = "clear" /><br />'
;
                            }

                        $edit_resume .= '
                        </div>
                       
                        <br class = "clear" />
                       
                        <input type = "hidden" value = "'
. $resume->ID . '" class = "resume_id" >
                        <input type = "submit" value = "Save Resume" class = "btn btn-primary save_edited_resume" >

                    </div>
                </div>

            '
;

            echo $edit_resume;

        }

        exit();
    }

    public static function cvf_ngp_update_resume() {

        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'update_resume') {

            foreach($_POST as $k => $value) {
                $_POST[$k] = sanitize_text_field($value);
            }

            $resume_data = array(
              'ID'           => $_POST['resume_id'],
              'post_title'   => $_POST['ngp_name'],
              'post_name'    => $_POST['ngp_name']
            );

            $update_status = wp_update_post( $resume_data );

            update_post_meta($_POST['resume_id'], 'ngp_phone', $_POST['ngp_phone']);
            update_post_meta($_POST['resume_id'], 'ngp_industry', $_POST['ngp_industry']);
            update_post_meta($_POST['resume_id'], 'ngp_headline', $_POST['ngp_headline']);
            update_post_meta($_POST['resume_id'], 'ngp_experience', $_POST['ngp_experience']);
            update_post_meta($_POST['resume_id'], 'ngp_education', $_POST['ngp_education']);
            update_post_meta($_POST['resume_id'], 'ngp_country', $_POST['ngp_country']);
            update_post_meta($_POST['resume_id'], 'ngp_zipcode', $_POST['ngp_zipcode']);

            if($update_status > 0) {
                echo '<br /><p class = "bg-success no-margin"><span class = "glyphicon glyphicon-ok"></span>&nbsp; Resume updated successfully.</p>';
            } else {
                echo '<br /><p class = "bg-danger no-margin">An internal error occured</p>';
            }
        }

        exit();
    }

    public static function cvf_ngp_delete_attachment(){

        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'delete_attachment'){

            $attachemnt_id = sanitize_text_field($_POST['attachment_id']);
            $type = sanitize_text_field($_POST['type']);
            $post_id = sanitize_text_field($_COOKIE['ngp_edit_resume']);
   
            if(false === wp_delete_attachment($attachemnt_id, true)) {}

            echo 'success';

        }

        exit();
    }

    public static function cvf_ngp_delete_resume() {

        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'delete_resume'){

            $resume_id = sanitize_text_field($_POST['resume_id']);
            wp_delete_post($resume_id, 1);

            echo 'success';

        }

        exit();
    }

    public static function cvf_ngp_delete_all_resume_attachments($post_id) {

        $attachments = get_posts( array(
            'post_type'      => 'attachment',
            'posts_per_page' => -1,
            'post_status'    => 'any',
            'post_parent'    => $post_id
        ) );

        foreach ( $attachments as $attachment ) {
            if ( false === wp_delete_attachment( $attachment->ID, 1 ) ) { /* Log failure to delete attachements */ }
        }

    }
   
    public static function cvf_ngp_upload_resume_data() {
               
        $user_resumes = self::cvf_ngp_get_all_user_resumes();
        $wp_upload_dir = wp_upload_dir();
        $path = $wp_upload_dir['path'] . '/';

        $count = 0;

        if(isset($_POST['upload_resume_file']) and $_SERVER['REQUEST_METHOD'] == "POST"){
           
            if(!$_FILES['files']['name']) {
                echo "<p class='bg-danger'>Please select a file.</p>";
            }
           
            foreach ($_FILES['files']['name'] as $f => $name) {
           
                if(isset($_POST['resume_avatar'])) {
                    $valid_formats = array("jpg", "jpeg", "gif", "png");
                    $max_file_size = 1024 * 500; # in kb
                    $file_title = 'avatar-'.$_COOKIE['ngp_edit_resume'];
                } else if (isset($_POST['resume_file'])) {
                    $valid_formats = array("doc", "docx", "pdf", "txt");
                    $max_file_size = 1024 * 2000; # in kb
                    $file_title = $name;
                }
               
                $extension = pathinfo($name, PATHINFO_EXTENSION);
                $new_filename = cvf_ngp_generate_random_code(20)  . '.' . $extension;
               
                if ($_FILES['files']['error'][$f] == 4) {}
               
                if ($_FILES['files']['error'][$f] == 0) {
               
                    if ($_FILES['files']['size'][$f] > $max_file_size) {
                        echo "<p class='bg-danger'>$name is too large!.</p>";
                       
                    } elseif( ! in_array($extension, $valid_formats) ){
                        echo "<p class='bg-danger'>$name is not a valid format</p>";
                       
                    } else{
                       
                        if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$new_filename)) {
                           
                            $count++;

                            $filename = $path.$new_filename;
                            $parent_post_id = $_COOKIE['ngp_edit_resume'];
                            $filetype = wp_check_filetype( basename( $filename ), null );
                            $wp_upload_dir = wp_upload_dir();
                            $attachment = array(
                                'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
                                'post_mime_type' => $filetype['type'],
                                'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $file_title ) ),
                                'post_content'   => '',
                                'post_status'    => 'inherit'
                            );

                            $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

                            require_once( ABSPATH . 'wp-admin/includes/image.php' );

                            $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
                            wp_update_attachment_metadata( $attach_id, $attach_data );
                           
                            if(isset($_POST['resume_file'])) {
                                update_post_meta($_COOKIE['ngp_edit_resume'], 'ngp_resume', $attach_id);
                            } elseif(isset($_POST['resume_avatar'])) {
                                update_post_meta($_COOKIE['ngp_edit_resume'], 'ngp_avatar', $attach_id);
                            }
                           
                            echo 'success';
                           
                        }
                    }
                }
            }
           
            exit();
           
        }
    }
   
   
    public static function cvf_ngp_archive_dates() {
   
        global $wpdb;
       
        $table = $wpdb->prefix . 'posts';
        $archive_dates = $wpdb->get_results($wpdb->prepare("
            SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts
            FROM $table  WHERE post_type = 'blog' AND post_status = 'publish'
            GROUP BY YEAR(post_date), MONTH(post_date)
            ORDER BY post_date DESC"
, array()
        ) );
       
        return $archive_dates;
       
    }
   
    public static function cvf_ngp_blog_datearchives_rewrite_rules($wp_rewrite) {

        $rules = self::cvf_ngp_generate_blog_date_archives('blog', $wp_rewrite);
        $wp_rewrite->rules = $rules + $wp_rewrite->rules;
        return $wp_rewrite;
       
    }

    public static function cvf_ngp_generate_blog_date_archives($cpt, $wp_rewrite) {

        $rules = array();

        $post_type = get_post_type_object($cpt);
        $slug_archive = $post_type->has_archive;
        if ($slug_archive === false) return $rules;
        if ($slug_archive === true) {
            $slug_archive = $post_type->name;
        }

        $dates = array(
            array(
                'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
                'vars' => array('year', 'monthnum', 'day')),
            array(
                'rule' => "([0-9]{4})/([0-9]{1,2})",
                'vars' => array('year', 'monthnum')),
            array(
                'rule' => "([0-9]{4})",
                'vars' => array('year'))
        );

        foreach ($dates as $data) {
            $query = 'index.php?post_type='.$cpt;
            $rule = $slug_archive.'/'.$data['rule'];

            $i = 1;
            foreach ($data['vars'] as $var) {
                $query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
                $i++;
            }

            $rules[$rule."/?$"] = $query;
            $rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
            $rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
            $rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
        }

        return $rules;
       
    }

    public static function cvf_ngp_remove_menus(){
   
        remove_menu_page('edit.php?post_type=resume');
        #remove_menu_page('edit.php?post_type=blog');
    }

}

Setting / Getting Sessions Values in PHP

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.

Session:
1. IDU is stored on server (i.e. server-side)
2. Safer (because of 1)
3. Expiration can not be set, session variables will be expired when users close the browser. (nowadays it is stored for 24 minutes as default in php)

Cookies:
1. IDU is stored on web-browser (i.e. client-side)
2. Not very safe, since hackers can reach and get your information (because of 1)
3. Expiration can be set (see setcookies() for more information)

Session is preferred when you need to store short-term information/values, such as variables for calculating, measuring, querying etc.

Cookies is preferred when you need to store long-term information/values, such as user’s account (so that even when they shutdown the computer for 2 days, their account will still be logged in). I can’t think of many examples for cookies since it isn’t adopted in most of the situations.

1. A PHP session is started with the session_start () function. This function has to be written above the html tag in your program:

1
2
3
<?php session_start(); ?>
<html>
</html>

2. Sessions can be accessed using

1
$_SESSION[$variable_name]

3. Storing single session variable:

1
$_SESSION['item_id'] = $post_id;

4. PHP Session Array:
Example A:

1
2
3
4
5
$userinfo = array();
$userinfo['username'] = 'currentusername';
$userinfo['isloggedin'] = false;
$userinfo['UID'] = 1;
$_SESSION['userinfo'] = $userinfo;

Example B:
$_SESSION[‘userinfo’][‘username’] = ‘currentusername’;
$_SESSION[‘userinfo’][‘isloggedin’] = false;
$_SESSION[‘userinfo’][‘UID’] = 1;

5. Sessions are closed using:

1
<?php session_destroy(); ?>

Example of an Ajaxified WordPress Admin using OOP Style

ajaxified-wordpress-admin-using-oop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
class Td_Admin {
   
    public function __construct() {
        add_action('admin_menu', array($this, 'cvf_td_register_site_options') );
        add_action('wp_ajax_cvf_td_update_trade_settings', array($this, 'cvf_td_update_trade_settings') );
        add_action('admin_enqueue_scripts', array($this, 'cvf_td_load_admin_scripts') );
    }
   
    public static function cvf_td_load_admin_scripts() {
   
        wp_enqueue_style( 'admin-css', get_template_directory_uri() . '/css/admin.css', false, "1.1.1", false);
    }

   
    public static function cvf_td_register_site_options() {
        add_submenu_page( 'edit.php?post_type=page', 'Settings', 'Settings', 'administrator', 'trade-settings', 'Td_Admin::cvf_td_trade_settings' );
    }
   
    public static function cvf_td_trade_settings(){
        ?>
        <h2>Wp Trade Settings</h2>
        <span class = "update-trade-settings-response td-response"></span>
        <table class="form-table">
            <tbody>
                <tr>
                    <th><label for="limit_repost">Items can be reposted after:</label></th>
                    <td><input type="text" name="limit_repost" id="limit_repost" value="<?php echo get_option('td_limit_repost'); ?>" placeholder = "" class="regular-text"> <span class="description">Specify in hours, Default is: 24</span></td>
                </tr>
                <tr>
                    <th><label for="max_image_upload">Maximum Image Upload</label></th>
                    <td><input type="text" name="max_image_upload" id="first_name" value="<?php echo get_option('td_max_image_upload'); ?>" class="regular-text"></td>
                </tr>
                <tr>
                    <th><label for="max_image_size">Maximum Image Size</label></th>
                    <td><input type="text" name="max_image_size" id="max_image_size" value="<?php echo get_option('td_max_image_size'); ?>" class="regular-text"><span class="description">Specify in kilobytes, Default is: 500</span></td>
                </tr>
                <tr>
                    <th><label for="currency_symbol">Currency Symbol</label></th>
                    <td>
                        <select name="currency_symbol" class = "currency_symbol">
                            <option value = "dollar">$ Dollar</option>
                            <option value = "euro">&euro; Euro</option>
                            <option value = "pound">&pound; Pound</option>
                            <option value = "yen">&yen; Yen</option>
                            <option value = "peso">&#8369; Peso</option>
                        </select>
                    </td>
                </tr>
                <tr>
                     <th><label for="currency_symbol">Editor</label></th>
                    <td>
                        <?php
                        $content = '';
                        $editor_id = 'mycustomeditor';
                        wp_editor( $content, $editor_id );
                        ?>
                    </td>
                </tr>
            </tbody>
        </table>
       
        <p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary update_wp_trade_settings" value="Update Settings"></p>
               
        <script type="text/javascript">
        jQuery(document).ready(function($) {
           
            var current_currency = '<?php echo get_option('td_currency_symbol'); ?>';
            if(current_currency){
                $(".currency_symbol").val(current_currency);
            }
           
            $('input').on('focus', function(){
                $('input').removeClass('border-red');
            });
           
            $("body").on("click", ".update_wp_trade_settings", function(e) {                        
                e.preventDefault();
               
                if(!$("input[name=limit_repost]").val()) {
                    $("input[name=limit_repost]").addClass('border-red');
                } else if(!$("input[name=max_image_upload]").val()) {
                    $("input[name=max_image_upload]").addClass('border-red');
                } else if(!$("input[name=max_image_size]").val()) {
                    $("input[name=max_image_size]").addClass('border-red');
                } else {
               
                    $(".update-trade-settings-response").html('<p><img src = "<?php bloginfo('template_url'); ?>/images/loading.gif" class = "loader" /></p>');
                    var data = {
                        'action': 'cvf_td_update_trade_settings',
                        'cvf_action': 'update_trade_settings',
                        'limit_repost': $("input[name=limit_repost]").val(),
                        'max_image_upload': $("input[name=max_image_upload]").val(),
                        'max_image_size': $("input[name=max_image_size]").val(),
                        'currency_symbol': $(".currency_symbol").val(),
                        'text_area_text': tinymce.editors.mycustomeditor.getContent()
                    };
                   
                    $.post(ajaxurl, data, function(response) {
                        element = $(".update-trade-settings-response");
                        $('html, body').animate({scrollTop: $(element).offset().top-100}, 150);
                        $(element).html(response);
                    });
                }
            });
        });
        </script>
        <?php
       
    }
   
    public static function cvf_td_update_trade_settings(){
       
        $errors = array();
        $currency_list = array('dollar', 'euro', 'pound', 'yen', 'peso');
       
        if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'update_trade_settings'){
           
            foreach($_POST as $k => $value){
                $_POST[$k] = sanitize_text_field($value);
            }
           
            if (empty($errors) === true) {
           
                if(!is_numeric($_POST['limit_repost'])){
                    $errors[] = 'Only numeric values are allowed in "Items can be reposted after"';
                } elseif ($_POST['limit_repost'] < 0) {
                    $errors[] = 'Repost limit cannot be negative';
                }
               
                if(!is_numeric($_POST['max_image_upload'])){
                    $errors[] = 'Only numeric values are allowed in "Maximum Image Upload"';
                } elseif ($_POST['max_image_upload'] < 0) {
                    $errors[] = 'Maximum Image Upload cannot be negative';
                }
               
                if(!is_numeric($_POST['max_image_size'])){
                    $errors[] = 'Only numeric values are allowed in "Maximum Image Size"';
                } elseif ($_POST['max_image_size'] < 10) {
                    $errors[] = '"Maximum Image Upload" must be greater than 10kb';
                }
               
                if(!in_array($_POST['currency_symbol'], $currency_list)){
                    $errors[] = 'Invalid Currency Symbol.';
                }
            }
           
            if(empty($_POST) === false && empty($errors) === true) {
               
                update_option('td_limit_repost', $_POST['limit_repost']);
                update_option('td_max_image_upload', $_POST['max_image_upload']);
                update_option('td_max_image_size', $_POST['max_image_size']);
                update_option('td_currency_symbol', $_POST['currency_symbol']);
                update_option('td_text_area_text', $_POST['text_area_text']);
               
                echo '
                <div id="message" class="updated">
                    <p><strong>Settings updated.</strong></p>
                </div>'
;
               
            } elseif (empty($errors) === false) {
                echo '
                <div id="message" class="error">
                    <ul>'
;
                    foreach ($errors as $error) {
                        echo '<li><strong>' . $error . '</strong></li>';
                    }
                echo '</ul>
                </div>'
;
               
            }
        }
       
        exit();
    }
   
} new Td_Admin();

Sending HTTP requests using cURL in PHP

First things first, in order to use PHP’s cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that’s 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.

Basic Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$url = 'http://somewhere.com/link-to-your-api/';
// Define all the required fields needed for your API
$params = array(
    'action'    => 'get_all_user_data',
    'key'       => '456F9DS',
    'user_id'   => '16845',
    'user_email'    => 'data405@gmail.com'
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

// Decode the response
$data = json_decode($response);
print_r($data);

The above code will send an HTTP Request to the given URL and will decode the response then print it to the screen of the requesting client.

If you are dealing with too many HTTP Requests, it would be best to put cURL in a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function cvf_curl_with_response($url, $params ) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ps_response = curl_exec($ch);
    curl_close($ch);
   
    return json_decode($ps_response);
   
}

Then use the function like this:

1
2
3
4
5
6
7
$params = array(
    'action'    => 'get_all_user_data',
    'key'       => '456F9DS',
    'user_id'   => '16845',
    'user_email'    => 'data405@gmail.com'
);
echo cvf_curl_with_response('http://somewhere.com/link-to-your-api/', $params );

Convert stdClass Object to Array in PHP

Use this function to convert stdClass Objects into Arrays:

1
2
3
4
5
6
7
8
9
10
11
12
13
function cvf_convert_object_to_array($data) {

    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }
    else {
        return $data;
    }
}

Test Results:

stdClass Object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Converted to Array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array
(
    [foo] => Test data
    [bar] => Array
        (
            [baaz] => Testing
            [fooz] => Array
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

PHP Function to Validate Date Format

1
2
3
4
5
6
7
8
9
10
11
12
function cvf_ps_check_date_format($date) {

    // define your format here
    $format = "m/d/Y";
    $date_format= DateTime::createFromFormat($format, $date);
   
    if(!$date_format) {
        return false;
    } else {
        return true;
    }
}

PHP Function that Generates Random Characters

1
2
3
4
5
6
7
8
9
10
11
12
13
function cvf_ps_generate_random_code($length=10) {
 
   $string = '';
   // You can define your own characters here.
   $characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";
 
   for ($p = 0; $p < $length; $p++) {
       $string .= $characters[mt_rand(0, strlen($characters)-1)];
   }
 
   return $string;
 
}

Create a Sessionless Captcha in PHP

sessionless_captcha

Demo Download

Sometimes you can have session issues on your server, issues such as sessions not being stored on the browser and there is no way to retrieve the data. In some cases, sessions might work on Chrome but not in Firefox or vise versa.

I spent half a day trying to solve session issues with my captcha until I decided to create a sessionless captcha.

The idea of this sessionless captcha is generating a random word(s) on the server side, two-way encrypt it and then put the encrypted string in the form as a hidden variable. In addition, provide the encrypted string in the image url that gets generated dynamically. The image request can decode the string and then render the captcha image. When the user submits the value, the form contains the user’s value and the encrypted value which can be confirmed on the server.

Sample Form with validation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php

$errorsucc = '';

if (isset($_POST["captcha_check"])) {
         
    $code = str_decrypt($_POST["captcha_check"]);  
   
    if (empty($_POST['captcha_code'])) {
        $errorsucc = '<p style="color:red">Please Enter the security code.</p>';
       
    } elseif(!( $code == $_POST['captcha_code'] && !empty($code) )) {
        $errorsucc = '<p style="color:red">Incorrect Code Entered.</p>';
       
    } else {
        $errorsucc = '<p style = "green">Nice, you entered the correct code.</p>'; 
    }
}

$captcha = new CaptchaCode();
$code = str_encrypt($captcha->generateCode(6));
?>

<html>
    <title>Sessionless Captcha</title>
    <div style = "background: #e2e2e2; padding: 20px; width: 20%; box-shadow: 5px 5px #ccc;">
        <?php echo $errorsucc; ?>
        <form name="captchaform" method="post">
            <table border="0" cellpadding="4" cellspacing="0">
                <tr><td valign="middle" align="left">Security Code:</td>
                    <td valign="middle" align="left"><img src="captcha_images.php?width=150&height=50&code=<?php echo $code?>" /></td>
                </tr>
                <tr><td valign="middle" align="left">Enter Code:</td>
                    <td valign="middle" align="left"><input id="captcha_code" name="captcha_code" style="width:150px" type="text" /></td>
                </tr>

                <tr><td valign="top" align="left">
                    </td>
                    <td valign="top" align="left">
                        <input border="0" type="submit" value="Submit" />  
                    </td>
                </tr>
            </table>
            <input type="hidden" name="captcha_check" value="<?php echo $code?>" />
        </form>
    </div>
</html>

Generate images just like any other captcha:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    /* font size will be 75% of the image height */
    $font_size = $height * 0.75;
    $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
    /* set the colours */
    $background_color = imagecolorallocate($image, 255, 255, 255);
    $text_color = imagecolorallocate($image, 0, 26, 26);
    $noise_color = imagecolorallocate($image, 25, 89, 89);
    /* generate random dots in background */
    for( $i=0; $i<($width*$height)/3; $i++ ) {
        imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
    }
    /* generate random lines in background */
    for( $i=0; $i<($width*$height)/150; $i++ ) {
        imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
    }
    /* create textbox and add text */
    $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
    $x = ($width - $textbox[4])/2;
    $y = ($height - $textbox[5])/2;
    imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
    /* output captcha image to browser */
    header('Content-Type: image/jpeg');
    imagejpeg($image);
    imagedestroy($image);

How to Import Large Database Files in XAMPP / Laragon / WAMP

xampp-max-size-error

Make changes in php\php.ini

Look for the following:

1
2
3
4
5
post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M

then replace the lines with the following:

1
2
3
4
5
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

Restart your XAMPP / Laragon / WAMP after making the changes, if you are still seeing the same error – try restarting your computer.

Adding a Simple Math Captcha to your Form in PHP

Math_Captcha

First is we need to create a new session by adding this code:

Second, we generate the numbers that we will be using for the Math Captcha:

1
2
3
$num1=rand(1,9); //Generate First number between 1 and 9  
$num2=rand(1,9); //Generate Second number between 1 and 9  
$captcha_total=$num1+$num2;

Third, we set the Math question into a variable (This his how the question will look like.)

1
$math = "$num1"." + "."$num2"." =";

Fourth, we set the properties of our Match Captcha image.

1
2
3
4
$image = imagecreatetruecolor(120, 30); //Change the numbers to adjust the size of the image
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 0, 100, 90);
$white = imagecolorallocate($image, 0, 26, 26);

Finally, We create the image:

1
2
3
4
5
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 20, 0, 20, 25, $color, $font, $math );//Change the numbers to adjust the font-size

header("Content-type: image/png");
imagepng($image);

Save this as captcha.php, here is the full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
session_start();

$num1=rand(1,9); //Generate First number between 1 and 9  
$num2=rand(1,9); //Generate Second number between 1 and 9  
$captcha_total=$num1+$num2;  

$math = "$num1"." + "."$num2"." =";  

$_SESSION['rand_code'] = $captcha_total;

$font = 'mmobuyit-captcha-fonts/Arial.ttf';

$image = imagecreatetruecolor(120, 30); //Change the numbers to adjust the size of the image
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 0, 100, 90);
$white = imagecolorallocate($image, 0, 26, 26);

imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 20, 0, 20, 25, $color, $font, $math );//Change the numbers to adjust the font-size

header("Content-type: image/png");
imagepng($image);

Next step is to create our form and a some validations.

Validation:

1
2
3
4
5
6
7
8
9
10
11
12
13
$errors = array();

if ($_POST['registerUser']) {

    if (empty($errors) === true) {

        if (empty($_POST['captcha_entered'])) {
            $errors[] = '<p class = "input-error">Please answer the Captcha Question</p>';
        } elseif ($_REQUEST['captcha_entered']!=$_SESSION['rand_code']) {
            $errors[] = '<p class = "input-error">Your answer to the Math Question is incorrect.</p>';
        }
    }  
}

Sample Form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<form method="post" class="register" id = "register-ajax">

<?php
if (empty($_POST) === false && empty($errors) === true) {
       
    echo 'Success';
       //Run some codes here.
           
} else if (empty($errors) === false) {
       
    echo output_errors($errors);
}
?>
    <p>
        <img src="captcha.php" />
        <input name="captcha_entered" style = "width: 100px !important;" type="text" id="captcha_entered" size="5" maxlength="2" placeholder = "Answer" />
        <input type="hidden" name="captcha_total" id="captcha_total" value="<?php echo $_SESSION['rand_code']; ?>" />
    </p>
    <p>
        <input type="submit" class="button" name="registerUser" value="<?php _e( 'Register' ); ?>" />
    </p>
</form>

Checkout my other PHP Tutorials by following this LINK

How to Limit the Number Words to Output in PHP

I recently created a page that contains a list of articles. I wanted to show the title and the excerpt, but the output of the excerpt is too long and breaking my list. So here is what I did to limit the number of words:

Create a function that will accept two parameters (the text to be limited and the desired number of words)

1
2
3
4
function limit_words($text, $limit) {
    $words = explode(" ",$text);
    return implode(" ",array_splice($words,0,$limit));
}

Then we call the function to our page:

1
2
3
$text = "The quick brown fox jumps over the lazy dog";
 
echo limit_words($text,5);

Formatting Dates in PHP

Syntax:

1
2
$date = time();
$date_today = date("Y-m-d H:i:s", $date);

The time(); function will output the current date today in time stamp format.
The date(); function accepts two parameters, the first parameter is how you want to output the date and the 2nd parameter is the date to be formatted. If no parameters are provided, the default will be the value of the time(); function which is the current date.

List of Date Formats that you can use:

1
2
3
4
5
6
7
8
9
10
date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
date("m.d.y");                         // 03.10.01
date("j, n, Y");                       // 10, 3, 2001
date("Ymd");                           // 20010310
date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
date("H:i:s");                         // 17:16:18
date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)

To get the current date in an array format, use:

1
2
$today = getdate();
print_r($today);

The above code will output the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Array
(
    [seconds] => 5
    [minutes] => 50
    [hours] => 5
    [mday] => 3
    [wday] => 6
    [mon] => 5
    [year] => 2014
    [yday] => 122
    [weekday] => Saturday
    [month] => May
    [0] => 1399089005
)

To convert mysql date format (Ex. 2013-10-28 07:57:07) , we should first convert it using “strtotime”

1
2
3
$mysql_date = '2013-10-28 07:57:07';
$php_date = strtotime( $mysql_date );
$result = date( 'Y-m-d H:i:s', $php_date );

Reference: http://php.net/manual/en/function.date.php