Thursday, December 24, 2015

Wordpress get permalink of post from ID

Permalink of a page or post using ID can be retrieved as follows:

$url = get_permalink($post_id);

Where $post_id  is the ID of the post or page whose permalink is to be get.

Wordpress get acf field value of another post

To get values of ACF field from another page or post use the following method.

$value = get_field('field_name',$post_id);

Here $post_id  is of another post or page whose ACF value you want to fetch in the current page or post.

Wednesday, December 23, 2015

Wordpress site url

To get the website URL use the following inbuilt function of WordPress.

$site_url  = site_url();

You will value of site URL in the above variable and can be used as following:

<?php echo $site_url; ?>

Wordpress home url

As we know WordPress is a very powerful blogging open source CMS, so is development easy and flexible.

To get the home page URL use the following function.

$home_url = home_url();

<?php echo $home_url; ?>

You will get the home URL in the above variable.

Saturday, September 12, 2015

PHP get previous date

The following function gives the previous date of the date entered.

For date format: 2014-02-15

function prevDate($date)
  {
 $dateArray=explode('-',$date);
 $tomorrow = mktime(0,0,0,$dateArray[1],$dateArray[2]-1,$dateArray[0]);
 return date("Y-m-d", $tomorrow);
  }
 
  Usage of the function is as follows:
 
  $date = "2014-02-15";
 
  echo prevDate($date);
 
  Ouput is: 2014-02-14
 
For date format: 2014/02/15

function prevDate($date)
  {
 $dateArray=explode('-',$date);
 $tomorrow = mktime(0,0,0,$dateArray[1],$dateArray[2]-1,$dateArray[0]);
 return date("Y-m-d", $tomorrow);
  }
 
  Usage of the function is as follows:
 
  $date = "2014/02/15";
 
  echo prevDate($date);
 
  Ouput is: 2014/02/14

PHP get next date of the current date

The following function gives the next date of the date entered.

For date format: 2014-02-15

function nextDate($date)
  {
 $dateArray=explode('-',$date);
 $tomorrow = mktime(0,0,0,$dateArray[1],$dateArray[2]+1,$dateArray[0]);
 return date("Y-m-d", $tomorrow);
  }
 
  Usage of the function is as follows:
 
  $date = "2014-06-01";
 
  echo nextDate($date);
 
  Ouput is: 2014-06-02
 
For date format: 2014/02/15

function nextDate($date)
  {
 $dateArray=explode('/',$date);
 $tomorrow = mktime(0,0,0,$dateArray[1],$dateArray[2]+1,$dateArray[0]);
 return date("Y-m-d", $tomorrow);
  }
 
  Usage of the function is as follows:
 
  $date = "2014/06/01";
 
  echo nextDate($date);
 
  Ouput is: 2014/06/02

PHP add number of days into date

PHP supports various date types and its conversion.
The following php example demonstrate to add n number of days in the provided date.

For date format: yyyy-mm-dd

function addDate($date,$n)
  {
 $dateArray=explode('-',$date);
 $addDate = mktime(0,0,0,$dateArray[1],$dateArray[2]+$n,$dateArray[0]);
 return date("Y-m-d", $addDate);
  }
  
  Usage of the function is as follows:
 
  $n = 1;
  $date = "2014-06-01";
 
  echo addDate($date, $n);
 
  Ouput is: 2014-06-02
 
For date format: yyyy/mm/dd

function addDate($date,$n)
  {
 $dateArray=explode('/',$date);
 $addDate = mktime(0,0,0,$dateArray[1],$dateArray[2]+$n,$dateArray[0]);
 return date("Y-m-d", $addDate);
  }
 
  Usage of the function is as follows:
 
  $n = 1;
  $date = "2014/06/01";
 
  echo addDate($date, $n);
 
  Ouput is: 2014/06/02

PHP read Zip XML file

Using PHP we can read, write files. we can also upload and create new files.
But what if you have to read a XML file which is present in an ZIP Archive.
The following function shows how to read data of XML file from an ZIP Archive.

function readZippedXML($archiveFile, $dataFile) {
    // Create new ZIP archive
    $zip = new ZipArchive;

    // Open received archive file
    if (true === $zip->open($archiveFile)) {
        // If done, search for the data file in the archive
        if (($index = $zip->locateName($dataFile)) !== false) {
            // If found, read it to the string
            $data = $zip->getFromIndex($index);
            // Close archive file
            $zip->close();
            // Load XML from a string
            // Skip errors and warnings
            $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            // Return data without XML formatting tags
            return strip_tags($xml->saveXML());
        }
        $zip->close();
    }

    // In case of failure return empty string
    return "";
}

 The usage of the function is as follows:

 readZippedXML("word/document.zip", "word/document.xml");

 This function will get all the data of the XML file from the zip and save in a new file where the zip is present.

PHP convert doc file to text file

PHP allows file uploads, file write, copy, move, delete and also it supports conversion of one file format to another.
In this example we will see how a doc file is converted to a text file.

function doc2text($file)
{
$file     = $directory.'/'.$filename;
$fileinfo = pathinfo($filename);
$content  = "";
// doc to text
$content = shell_exec("antiword -m UTF-8.txt -t $file");
return $content;
}

 The usage of the function is as follows:

  $file = "documents/files/doc/test.doc";
  doc2text($file);

PHP Send html email

PHP has an inbuilt functionality to send email.
We can send email in php using the mail function.
The following function uses the inbuilt mail function to php to send email but in HTML format.
HTML emails are popular nowadays and almost 90% of the websites uses this features to send HTML emails to their customers.

function sendHTMLemail($HTML,$from,$to,$subject,$cc='')
{
// First we have to build our email headers
// Set out "from" address
$headers = "From: $from\r\n";
if($cc!='')
$headers.= "CC: $cc\r\n";
// Now we specify our MIME version
$headers .= "MIME-Version: 1.0\r\n";
// Create a boundary so we know where to look for
// the start of the data
$boundary = uniqid("HTMLEMAIL");
// First we be nice and send a non-html version of our email
$headers .= "Content-Type: multipart/alternative;".
"boundary = $boundary\r\n\r\n";
$headers .= "This is a MIME encoded message.\r\n\r\n";
$headers .= "--$boundary\r\n".
"Content-Type: text/plain; charset=ISO-8859-1\r\n".
"Content-Transfer-Encoding: base64\r\n\r\n";
$headers .= chunk_split(base64_encode(strip_tags($HTML)));

// Now we attach the HTML version

$headers .= "--$boundary\r\n".
"Content-Type: text/html; charset=ISO-8859-1\r\n".
"Content-Transfer-Encoding: base64\r\n\r\n";
$headers .= chunk_split(base64_encode($HTML));

// And then send the email ....
mail($to,$subject,"",$headers);
}

 The function can be used as follows:

$HTML = "Hello John, <br /> How are you Today? <br /> Thanks!";
$from= = "Your email id here";
$to = "Email address of the person to whom you want to send the email";
$subject = "Test Email";
$cc = 'Email of the person to whom you want to keep in CC';

sendHTMLemail($HTML,$from,$to,$subject,$cc);

PHP create random password

There are many functions to create password like MDS, hash etc.
we can create a function to create our encryption method to create a password.
The following function create a random password using its own method and will not be easily identified the method of creating the password.

function STEM_Key()
{
// Create the meta-password
$sMetaPassword = "";
$ahPasswordGenerator = array(
"C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => 10, 'maximum' => 10),
"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 1, 'maximum' => 2),
"N" => array('characters' => '1234567890', 'minimum' => 10, 'maximum' => 10)
);
foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed){
$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
$sMetaPassword = str_shuffle($sMetaPassword);
}

// Create the real password
$arBuffer = array();
for ($i = 0; $i < strlen($sMetaPassword); $i ++){
$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];
}

return implode("", $arBuffer);
}

 You can view the output of the function in the following way.

echo STEM_Key();

PHP get extension of a file

PHP supports file uploads. user can design a system where he can allow users to upload files with specific extension type.
In many website we have the provision to upload files with specific file extension.
For example facebook we can upload file with extension jpeg, jpg,png etc for the profile picture.

Similarly it can be achieved in PHP. Following function returns you the extension of the given file type.

function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

$filename = "images/image01.jpeg" ;
$extension=getExtension($filename);
echo "Extension of the file is: ".$extension;

The output of the above function call will be:

Extension of the file is: jpeg

php connect to ftp server

FTP Stands for File Transfer Protocol. It is used to transfer and download files from server.
The available tools are FileZilla, SFTP, FTPZilla etc..
The ftp_connect function is supported by php 4, 5.


If you want to connect to the server using FTP and using PHP programming language then you can do it in the following way.

$ftp_server = "ftp.yousite.com";
//trying to connect to the server using PHP
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

if($conn_id){
echo "Your connection ID is: ".$conn_id;
}

Check Disk space in Linux

To check disk space in linux operating system through command line use the following command.

df -h //show all the media and the total amount of space available and total space used.

du -h --max-depth=1 //foldername (for eg var, html, data)

This command shows you the space occupied by the folder till level 1.
If you want to see more deep than you can replace the depth=1 by any number for nth level.

Destroy a session in PHP

Suppose a session have started and you want to destroy the whole all data of session.
You can use the following inbuilt function of php.

session_start();
session_destroy();

This will destroy all the session and all the data associated with it.

Session ID in PHP

If a session is already started or if you want to check if a session have started or is active/valid then you can check in the following way.

session_start();
$session_id = session_id();

if($session_id){
echo "Session is Vaild and ID is: ".$session_id;
}
else{
echo "No Session have started";
}

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...