Category Archives: PHP

Arduino – Communicate With Server – Part 3 – Web Based Panel

This is the code for the web based panel (web based UI) that will display the data received from arduino or can send some command to the Arduino

All communications are done through a server (web server)

The frontend code

<?php
date_default_timezone_set("Asia/Kolkata");
$conn = mysql_connect("localhost","root","xxxxxxxxxx");
if(!$conn)
{
    echo "Error: failed to connect DB";
    die();
}

if(!mysql_select_db("xxxxxxxx",$conn))
{
    echo "Error: failed to connect DB";
    die();
}
$jsonArray1 = array();
$jsonArray2 = array();
$i=0;

$result = mysql_query("select * from weather");
while($rows = mysql_fetch_array($result))
{
    $jsonArray1[$i] = array(date("Y,m,d,H,i",$rows['time']), floatval($rows['temperature']));
    $jsonArray2[$i++] = array(date("Y,m,d,H,i",$rows['time']), floatval($rows['paM']));
}
?>
<html>
  <head>
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript">
      var chart, chart2;
      window.onload = function () {
        chart = new CanvasJS.Chart("chartContainer",
        {
          title:{
          text: "Temperature"
          },
          axisY:{
            minimum: 0,
            maximum: 50      
          },
           data: [
          {
            type: "line",
    
            dataPoints: [
            <?php
                for($j=0;$j<$i;$j++)
                {
           ?>
                       { x: new Date(<?php echo $jsonArray1[$j][0] ?>), y: <?php echo $jsonArray1[$j][1] ?> } <?php echo $j<$i-1?"," :"" ?>
           <?php         
                }
            ?>            
            ]
          }
          ]
        });
    
        chart.render();
        
        
        chart2 = new CanvasJS.Chart("chartContainer2",
        {
          title:{
          text: "paM"
          },
          axisY:{
            minimum: 1000,
            maximum: 1040      
          },
           data: [
          {
            type: "line",
    
            dataPoints: [
            <?php
                for($j=0;$j<$i;$j++)
                {
           ?>
                       { x: new Date(<?php echo $jsonArray2[$j][0] ?>), y: <?php echo $jsonArray2[$j][1] ?> } <?php echo $j<$i-1?"," :"" ?>
           <?php         
                }
            ?>            
            ]
          }
          ]
        });
    
        chart2.render();
      }
      
    function updateTemp() 
    {
        var str = JSON.parse(updateData("t"));
        var date = str[1].split(",");
        chart.options.data[0].dataPoints.push({x : new Date(date[0],date[1],date[2],date[3],date[4]),  y : parseFloat(str[0]) });
          
        chart.render();         
    };
    
    function updatePressure() 
    {
          var str = JSON.parse(updateData("p"));
          var date = str[1].split(",");
        chart2.options.data[0].dataPoints.push({ x : new Date(date[0],date[1],date[2],date[3],date[4]), y : parseFloat(str[0]) });
        chart2.render();
    };
    
    function updateData(type)
    {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "dataPlotter.php?q=" + type, false);
        xmlhttp.send();
        return xmlhttp.responseText;
    }
    
    setInterval("updateTemp()",360000);
    setInterval("updatePressure()",480000);
    
  </script>
  </head>

  <body>
<?php
$result = mysql_query("select * from led_status");
$rows = mysql_fetch_array($result);
?>  
      LED 1 <input type="checkbox" value="<?php echo $rows['led_1']==1 ? 1 : 0 ?>" <?php echo $rows['led_1']==1 ? "checked="checked"" : "" ?> id="led_1" name="led_1" onclick="changeLEd('led_1')" />
      LED 2 <input type="checkbox" value="<?php echo $rows['led_2']==1 ? 1 : 0 ?>" <?php echo $rows['led_2']==1 ? "checked="checked"" : "" ?> id="led_2" name="led_2" onclick="changeLEd('led_2')" />
    <!--Div that will hold the column chart-->
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    
    <div id="chartContainer2" style="height: 300px; width: 100%;"></div>
    
    <script src="canvasjs.min.js"></script>
    <script src="jquery.canvasjs.min.js"></script>
    
    <script type="text/javascript">
        function changeLEd(whichLed)
        {
            var state;
            
            if(document.getElementById(whichLed).checked == true)
            {
                state = 1;
            }
            else
            {
                state = 0;
            }
            
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", "change-led.php?which="+whichLed+"&state="+state, false);
            xmlhttp.send();
            return xmlhttp.responseText;
        }
    </script>
  </body>
</html>

The backend codes

dataplotter.php

<?php
date_default_timezone_set("Asia/Kolkata");
$conn = mysql_connect("localhost","root","xxxxxxxxxx");
if(!$conn)
{
    echo "Error: failed to connect DB";
    die();
}

if(!mysql_select_db("xxxxxxxx",$conn))
{
    echo "Error: failed to connect DB";
    die();
}
$jsonArray = array();
$i=0;

if(isset($_GET['q']) && strlen(strip_tags($_GET['q'])))
{
    $type = strip_tags($_GET['q']);
}
else
{
    $type = "t";
}

if($type == "t")
{
    $type = "temperature";
}
else
    if($type == "p")
    {
        $type = "paM";
    }

$result = mysql_query("select ".$type.",time from weather order by time desc limit 0,1");
$rows = mysql_fetch_array($result);

header('Content-Type: application/json');
echo json_encode(array($rows[$type],date("Y,m,d,H,i",$rows['time'])));
?>

change-led.php

<?php
$conn = mysql_connect("localhost","root","xxxxxxxxxx");
if(!$conn)
{
    echo "Error: failed to connect DB";
    die();
}

if(!mysql_select_db("xxxxxxx",$conn))
{
    echo "Error: failed to connect DB";
    die();
}

$whichLed = strip_tags($_GET['which']);
$state = strip_tags($_GET['state']);
mysql_query("update led_status set ".$whichLed." = ".intval($state));
?>

Arduino – Communicate With Server – Part 2 – Server Code for Saving Data

This article shows the server side code for a server which is gathering or sending data by polling method to an Arduino device.

This method or code is putting less load on the server (compared to socket) but data transmission is slower than socket.

<?php
date_default_timezone_set("Asia/Kolkata");
$conn = mysql_connect("localhost","root","**********");
if(!$conn)
{
    echo "Error: failed to connect DB Server";
    die();
}

if(!mysql_select_db("database_name",$conn))
{
    echo "Error: failed to connect DB";
    die();
}
$action = intval(strip_tags($_GET['action']));

if($action == 1)
{
    $temp = floatval(strip_tags($_GET['temp']));
    $paH = floatval(strip_tags($_GET['paH']));
    $paM = floatval(strip_tags($_GET['paM']));
    
    mysql_query("insert into weather (temperature, paH, paM, time) values(".$temp.",".$paH.",".$paM.",".time().")");
    //mysql_query("update led_status set led_1 = ".$led_1.", led_2 = ".$led_2);
    
    echo "success";
}
else
    if($action == 2)
    {
        $output = "";
        $result = mysql_query("select * from led_status");
        $rows = mysql_fetch_array($result);
        if($rows['led_1'] == 1)
        {
           $output = "led_1=1|";    
        }
        else
        {
           $output = "led_1=0|";    
        }
        
        if($rows['led_2'] == 1)
        {
           $output .= "led_2=1";    
        }
        else
        {
           $output .= "led_2=0";    
        }
        echo $output;
    }
    mysql_close($conn);
?>

 

The else part ( if($action == 2) ) output from the above will be

HTTP/1.1 200 OK
Date: Sun, 14 Feb 2016 20:33:16 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Content-Length: 15
Connection: close
Content-Type: text/html

led_1=0|led_2=1

PHP Socket Client

This is a simple client that is running two different requests. One at every 2 seconds and another every 5 minutes. The 2 second one retrieved data from server and the 5 minute one sends data to server.

<?php
set_time_limit(0);
ob_implicit_flush();

$host    = "xxx.xxx.xxx.xxx";
$port    = 1250;

$lastUpdate = time();

while(1)
{
    if(time() - $lastUpdate > 300) //if 5 minutes elapsed
    {
        $message = "action=4512|temp=29.67|paM=10025.69|paH=125.69|led1=1|led2=0\r\n"; // the data to be sent separated by | The \r\n is important - it will tell the server that the string/data ends there
        // create socket
        $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
        // connect to server
        $result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
        
        // send command/query to server
        socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
        // get server response
        $result = socket_read ($socket, 1024, PHP_NORMAL_READ) or die("Could not read server response\n"); // 1024 is the max bytes that the socket will read if no \r\n is encountered. For the \n\r terminator PHP_NORMAL_READ is needed.
        echo "Reply From Server: ".$result."\n";
        
        // close socket
        socket_close($socket);
        
        $lastUpdate = time();
    }
    else
    {
        $message = "action=1223\r\n";
        // create socket
        $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
        // connect to server
        $result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
        
        // send command/query to server
        socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
        // get server response
        $result = socket_read ($socket, 1024, PHP_NORMAL_READ) or die("Could not read server response\n");
        echo "Reply From Server: ".$result."\n";
        
            // close socket
        socket_close($socket);
    }
    
    flush(); //may be this can be removed
    sleep(2);
    flush();
}
?>

 

PHP Socket Server – Running as Daemon and Multiple Connections

Code Courtesy: lars at opdenkamp dot eu

A socket server written in PHP. This can accept multiple connections and runs as a daemon.

pcntl_fork() is thing here that is making this all possible.

<?php
/**
  * Listens for requests and forks on each connection
  */

$__server_listening = true;

//error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
declare(ticks = 1);

become_daemon();

/* nobody/nogroup, change to your host's uid/gid of the non-priv user */
change_identity(1000, 1000);

/* handle signals */
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
pcntl_signal(SIGCHLD, 'sig_handler');

/* change this to your own host / port */
server_loop("192.168.0.1", 1250);

/**
  * Change the identity to a non-priv user
  */
function change_identity( $uid, $gid )
{
    if( !posix_setgid( $gid ) )
    {
        print "Unable to setgid to " . $gid . "!\n";
        exit;
    }

    if( !posix_setuid( $uid ) )
    {
        print "Unable to setuid to " . $uid . "!\n";
        exit;
    }
}

/**
  * Creates a server socket and listens for incoming client connections
  * @param string $address The address to listen on
  * @param int $port The port to listen on
  */
function server_loop($address, $port)
{
    GLOBAL $__server_listening;

    if(($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        echo "failed to create socket: ".socket_strerror($sock)."\n";
        exit();
    }

    if(($ret = socket_bind($sock, $address, $port)) < 0)
    {
        echo "failed to bind socket: ".socket_strerror($ret)."\n";
        exit();
    }

    if( ( $ret = socket_listen( $sock, 0 ) ) < 0 )
    {
        echo "failed to listen to socket: ".socket_strerror($ret)."\n";
        exit();
    }

    socket_set_nonblock($sock);
   
    echo "waiting for clients to connect\n";

    while ($__server_listening)
    {
        $connection = @socket_accept($sock);
        if ($connection === false)
        {
            usleep(100);
        }elseif ($connection > 0)
        {
            handle_client($sock, $connection);
        }else
        {
            echo "error: ".socket_strerror($connection);
            die;
        }
    }
}

/**
  * Signal handler
  */
function sig_handler($sig)
{
    switch($sig)
    {
        case SIGTERM:
        case SIGINT:
            exit();
        break;

        case SIGCHLD:
            pcntl_waitpid(-1, $status);
        break;
    }
}

/**
  * Handle a new client connection
  */
function handle_client($ssock, $csock)
{
    GLOBAL $__server_listening;

    $pid = pcntl_fork();

    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        die;
    }elseif ($pid == 0)
    {
        /* child process */
        $__server_listening = false;
        socket_close($ssock);
        interact($csock);
        socket_close($csock);
    }else
    {
        socket_close($csock);
    }
}

function interact($socket)
{
    $conn = mysql_connect("localhost","xxxxxxxx","xxxxxxxxxxx");
    if(!$conn)
    {
        echo "Error: failed to connect DB";
        die();
    }
    
    if(!mysql_select_db("xxxxxxxx",$conn))
    {
        echo "Error: failed to connect DB";
        die();
    }
    
    // read client input
    $input = socket_read($socket, 1024, PHP_NORMAL_READ);
    
    $buff = explode("|",$input);
    $len = count($buff);
    $temp = explode("=",$buff[0]);
    $temp[1] = intval($temp[1]);
    if($temp[0]!="action" && ($temp[1]!=1 || $temp[1]!=2 ))  //1=read 2=write -- these are just random numbers and has no other significance.
    {
        $output = "Error\r\n";
    } 

    
    if($temp[1] == 1)
    {
        $result = mysql_query("select * from led_status");
        $rows = mysql_fetch_array($result);
        $output = "led_1=".$rows['led_1']."|led_2=".$rows['led_2']."\r\n";
    }

    if($temp[1] == 2)
    {
        $queryW = "insert into weather set ";
        $queryL = "update led_status set ";

        for($i=1; $i<$len; $i++)
        {
            $temp = explode("=",$buff[$i]);
            switch($temp[0])
            {
                   case 'temp':
                    $queryW .= "temperature=" . floatval($temp[1]).", ";
                break;
                
                case 'paH':
                    $queryW .= "paH=" . floatval($temp[1]) .", ";    
                break;
                
                case 'paM':
                    $queryW .= "paM=" . floatval($temp[1]).", ";
                break;
                
                case 'led_1':
                    $queryL .= "led_1" . floatval($temp[1]) .", ";    
                break;
                
                case 'led_2':
                    $queryL .= "led_2=" . float_val($temp[1]).", ";        
            }
        }        
        
        $queryW .= " time=".time();
        $queryL .= " time=".time();
        
        mysql_query($queryL);
        mysql_query($queryW);
        
        $output = "Update Success\r\n";
    }
            
    /* TALK TO YOUR CLIENT */ 
    socket_write($socket,$output, strlen($output));    
    mysql_close();
}

/**
  * Become a daemon by forking and closing the parent
  */
function become_daemon()
{
    $pid = pcntl_fork();
   
    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        exit();
    }elseif ($pid)
    {
        /* close the parent */
        exit();
    }else
    {
        /* child becomes our daemon */
        posix_setsid();
        chdir('/');
        umask(0);
        return posix_getpid();

    }
}
?>

Realtime Charts / Graphs

CanvasJS  provides a very developer friendly chat or graph library. The library is based on HTML 5 and JS. And can also be used for displaying realtime charts or graphs also.

There are various types of charts/graphs available.

Below are some useful codes

Frontend code:
<?php
$conn = mysql_connect("localhost","xxxxxxxxx","xxxxxxxxx");
if(!$conn)
{
    echo "Error: failed to connect DB Server";
    die();
}

if(!mysql_select_db("xxxxxxxxx",$conn))
{
    echo "Error: failed to connect DB";
    die();
}

$jsonArray1 = array();
$i=0;
$result = mysql_query("select * from weather_log");
while($rows = mysql_fetch_array($result))
{
    $jsonArray1[$i] = array(date("Y,m,d,H,i",$rows['timestamp']), floatval($rows['temperature']));
}
?>
<html>
  <head>
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript">
      var chart;
      window.onload = function () {
        chart = new CanvasJS.Chart("chartContainer",
        {
          title:{
          text: "Temperature"
          },
           data: [
          {
            type: "line",
    
            dataPoints: [
            <?php
                for($j=0;$j<$i;$j++)
                {
           ?>
                       { x: new Date(<?php echo $jsonArray1[$j][0] ?>), y: <?php echo $jsonArray1[$j][1] ?> } <?php echo $j<$i-1?"," :"" ?>
           <?php         
                }
            ?>            
            ]
          }
          ]
        });
    
        chart.render();
      }
      
    function updateTemp() 
    {
        var str = JSON.parse(updateData("t"));
        var date = str[1].split(",");
        chart.options.data[0].dataPoints.push({x : new Date(date[0],date[1],date[2],date[3],date[4]),  y : parseFloat(str[0]) });
          
        chart.render();         
    };
        
    function updateData(type)
    {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "dataPlotter.php?q=" + type, false);
        xmlhttp.send();
        return xmlhttp.responseText;
    }
    
    setInterval("updateTemp()",360000);    
  </script>
  </head>

  <body>

    <!--Div that will hold the chart-->
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    
    
    <script src="canvasjs.min.js"></script>
    <script src="jquery.canvasjs.min.js"></script>
    
  </body>
</html>
Backend code (dataPlotter.php in above snippet)
$result = mysql_query("select temperature,timestamp from weather_log order by timestamp desc limit 0,1");
$rows = mysql_fetch_array($result);

header('Content-Type: application/json');
echo json_encode(array($rows['temperature'],date("Y,m,d,H,i",$rows['timestamp'])));

 

Woocommerce Change “Read More” Button

This code is useful for removing the “Read More” button (in woocommerce) for items that are out of stock.

/*
 * replace read more buttons for out of stock items
 **/
 if (!function_exists('woocommerce_template_loop_add_to_cart'))
 {
    function woocommerce_template_loop_add_to_cart()
    {
      global $product;
      if (!$product->is_in_stock()) 
      {
         echo '<a href="'.get_permalink().'" rel="nofollow" class="outstock_button">Sold Out</a>';
      }
      else
      {
         woocommerce_get_template('loop/add-to-cart.php');
      }
   }
 }

Prestahop Installation error 500

Problem:
Trying to install a new prestashop but getting error 500, the installation doesn’t even start

Solution:
Check file and folder permissions. Folder permission should be 755 and file should be 644.

 

Commands for changing file / folder permissions in linux through (ssh) console:

This is for changing folder permissions

find /public_html/prestashop -type d -exec chmod 755 {} \; 

This is for changing file permissions

find /public_html/prestashop -type f -exec chmod 644 {} \

Upload Files through AJAX (using Jquery and PHP)

This post demonstrates how to upload files to the server through AJAX. For the javascript  part JQuery has been used.

Besides the file upload thing there are few other useful codes here:

  • A generalised mail function. The function is capable of sending mails with attachments also.
  • Ajax call using JQuery.
  • Some server side validation codes.

Things might look a little jumbled up here, suggested to copy and paste the code to some IDE or editor first.

Form HTML
<span id="statusMessage"></span>

<form action="" method="post" name="" id="form1" enctype="multipart/form-data" onsubmit="return sendCareerData()">
    <input type="text" id="formName" name="formName" placeholder="Name" />
    <input type="text" id="formEmail" name="formEmail" placeholder="Email" />
    <input type="text" id="formPhone" name="formPhone" placeholder="Phone No." />
    <input type="file" id="formFile" name="formFile" placeholder="Upload File" />
    <input type="submit" id="button4" name="formSubmit" value="Submit" />
</form>
The Javascript part
<script type="text/javascript">
function sendCareerData()
{
    var data = new FormData(document.getElementById("form1"));
   
    // make the AJAX request
    jQuery.ajax({
        type: "POST",
        url: 'form-backend.php',
        data: data,
        mimeType:"multipart/form-data",
        contentType: false,
        cache: false,
        processData:false,
        dataType: 'json',
        success: function (data) {
            if (data.success == 0) //error on server side
            {
              /* error messages from server side validation */  
                var errors = '<ul>';
                if (data.name_msg != '')
                    errors += '<li>' + data.name_msg + '</li>';
                if (data.email_msg != '')
                    errors += '<li>' + data.email_msg + '</li>';
                if (data.phone_msg != '')
                    errors += '<li>' + data.phone_msg + '</li>';

                jQuery("#statusMessage").html(errors);
                jQuery("#statusMessage").css("display","block");
            }
            else if (data.success == 1) 
            {
                jQuery("#statusMessage").html("Thank you! We will get in touch.");
                jQuery("#statusMessage").css("display","block");
            }

        },
        error: function (error) 
        {
            jQuery("#statusMessage").html(error);
            jQuery("#statusMessage").css("display","block");
        }
    });
    
    return false;
}
</script>
The backend part using PHP
/******* form-backend.php *********/
<?php
ob_start(); //to suppress any newlines being sent before the header call

/********* a general mail sending function with or without attachment ***********/
function _mail($to, $from='', $subject = " ", $body = " ", $attachment = "" , $fileatt_type = "", $fileatt_name = "")
{
    $headers = "MIME-Version: 1.0" . "\r\n";
    if(strlen($from))
        $headers .= 'From: ' . $from . "\r\n";
    $headers .= 'Bcc: [email protected]' . "\r\n";
    
    if(strlen($attachment)) //if attachment is there
    {
        $fp = fopen($attachment, "rb");
        if(! $fp)
        {
            echo "Cannot attach file";
            return false;
        }
        $buffer = fread($fp, filesize($attachment));
        $attach_this=chunk_split(base64_encode($buffer));
        fclose($fp);
        $semi_rand = md5(time());
         $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
            /*'From: ' . $from . "\r\n" .
            'Reply-To: ' . $from . "\r\n" .*/
        $headers .= 'Content-Type: multipart/mixed; ' . " boundary="PHP-mixed-{$mime_boundary}"". "\r\n" . /* THIS BOUNDARY LINE AFTER CONTENT TYPE IS IMPORTANT */
        //$headers .= 'X-Mailer: PHP/' . phpversion() ; -- causing problems        
        $msg =     "--PHP-mixed-{$mime_boundary}\r\n" .
                "Content-Type: text/html; charset="iso-8859-1"\r\n" .
                "Content-Transfer-Encoding: 7bit\r\n\r\n". $body . "\r\n";
        $msg =     "--PHP-mixed-{$mime_boundary}\r\n";
        $msg .=  "--PHP-mixed-{$mime_boundary}\r\n" .
                "Content-Type: {$fileatt_type}; " . " name="{$fileatt_name}"\r\n" .
                "Content-Disposition: attachment; " . " filename="{$fileatt_name}"\r\n" .
                "Content-Transfer-Encoding: base64\r\n\r\n" .
                $attach_this . "\r\n" . /* DON'T PUT TWO NEWLINES AFTER THE ATTACHMENT */
                "--PHP-mixed-{$mime_boundary}--\r\n"; 
        $body = $msg;
    }
    else //no attachment - send simple html mail
    {
        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
        $headers .= 'X-Mailer: PHP/' . phpversion();
    }
    $mail_sent = mail($to, $subject, $body, $headers);
    $status = $mail_sent ? "1" : "0"; //1 - no error / success . 0 - error / failed
    return $status;
}

/**** a function for validating the user inputs **********/
function validate($name,$email,$phone)
{
  $return_array = array();
  $return_array['success'] = '1';
  $return_array['name_msg'] = '';
  $return_array['email_msg'] = '';
  $return_array['phone_msg'] = '';

  if($email == '')
  {
    $return_array['success'] = '0';
    $return_array['email_msg'] = 'email is required';
  }
  else
  {
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    if(!preg_match($email_exp,$email)) 
    {
      $return_array['success'] = '0';
      $return_array['email_msg'] = 'enter valid email.';  
    }
  }

  if($name == '')
  {
    $return_array['success'] = '0';
    $return_array['name_msg'] = 'Name is required';
  }
  else
  {
    $string_exp = "/^[A-Za-z .'-]+$/";
    if (!preg_match($string_exp, $name)) 
    {
      $return_array['success'] = '0';
      $return_array['name_msg'] = 'enter valid Name.';
    }
  }
  
  if($phone == '')
  {
    $return_array['success'] = '0';
    $return_array['phone_msg'] = 'Phone is required';
  }
  else
  {
     $string_exp = "/^[0-9 -]+$/";
     if (!preg_match($string_exp, $phone)) 
     {
        $return_array['success'] = '0';
        $return_array['name_msg'] = 'enter valid Phone.';
     }
  }

  return $return_array;
}

/****** assigning the values to some variables for easy handling ********/
$name = $_POST['formName'];
$email = $_POST['formEmail'];
$phone = $_POST['formPhone'];
$subject = $_POST['formSubject'];
$file = $_FILES['formFile']['tmp_name'];

$type = $_FILES['formFile']['type'];

$return_array = validate($name,$email,$phone); // validate the user input and get the result in $return_array

if($return_array['success'] == '1') //if input is okay then send the mail (with attachment)
{
  $body = "<strong>Email = </strong>".$email."<br>";
  $body .= "<strong>Name = </strong>".$name."<br>";
  $body .= "<strong>Phone = </strong>".$phone."<br>";
  
    
   if(strlen($_FILES['formFile']['tmp_name'])) //if attachment is there
   {
        _mail("[email protected]",$email,$subject,$body,$file,$type,$_FILES['formFile']['name']);
   }
   else
   {
        _mail("[email protected]",$email,$subject,$body);
   } 
  
}

ob_end_clean();//discard any output thrown above
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>

 

Twitter Feeds widget

//USAGE - set the keys and token here and then just include this file into your code. Change the <li> to whatever needed. 

if(!isset($tweetAuthen) && $tweetAuthen != "awre4rwrwfe") //random string to prevent this file being run directly
{
    echo "<li>Unauthorized use of widget</li>!";
}
else
{
        //Files needed for the Twitter authentification
    //Check if TwitterOAuth doesn't already existe
    if( ! class_exists( 'TwitterOAuth' )){
    
        require_once 'twitteroauth/twitteroauth.php';
    
    }
    
    
    
   function twitter_feeds(){

    $return_value = false;
    
    $twitter_oauth_var = array('consumer_key'=>"YOUR CONSUMER KEY", 'consumer_secret'=>"YOUR CONSUMER SECRET", "token_key"=>"YOUR TOKEN KEY", 'token_secret'=>"YOUR TOKEN SECRET");
    //Check if wee use the authentification methode. We need to have all the key and secret.
    if( is_array( $twitter_oauth_var ) && count($twitter_oauth_var) == 4 ){
       
        $connection = new TwitterOAuth($twitter_oauth_var['consumer_key'], $twitter_oauth_var['consumer_secret'], $twitter_oauth_var['token_key'],$twitter_oauth_var['token_secret']);
        $last_tweet = $connection->get('https://api.twitter.com/1.1/statuses/user_timeline.json', array("count"=>"5") );  // change 5 to the number of tweets to retrieve
                
        $return_value = $last_tweet;
        
        foreach ($last_tweet as $tweet) 
        {

            $id = $tweet->id_str;

            //$options['id'] = $id;
            //$last_tweet_html = $connection->get('https://api.twitter.com/1.1/statuses/oembed.json', $options);
            
            //$tweet_id = $id;
            //$tweet_html .= $last_tweet_html->html;
            
            $temp =  $tweet->text;
            if(strlen($tweet->entities->urls[0]->url))
            {
                $temp = str_ireplace($tweet->entities->urls[0]->url,"<a href='".$tweet->entities->urls[0]->url."' target='_blank'>".$tweet->entities->urls[0]->url."</a>",$temp);
                $tweet_html .= "<li>".$temp."</li>";
            }
            else
                $tweet_html .= "<li>".$temp."</li>";
        }

    }
        return $tweet_html;
    }
    
    echo twitter_feeds();
}

Need to include twitteroauth library. Can be downloaded from here https://github.com/abraham/twitteroauth

The whole code including the twitteroauth library can be downloaded from here.