Wednesday, 7 May 2014

PHP SENDING MAIL WITH ATTACHEMENTS

----------------------------------------------------------------------------------------------------------------------------------

We can send mails with attachements using 3 ways

1.     PHP MAILER
2.     PEAR
3.     SWIFT MAILER

Here we are using PHP MAILER functions to send a mail with attchment.

Step 1:

We need to download PHP mailer .


Place it in your project folder

Step 2:

Creating a form with file upload input type(index.php)


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <form name="career_form" action="upload_file.php" method="post" enctype="multipart/form-data">
            First Name<br/>
            <input type="text" name="txt_first_name" id="txt_first_name"><br/>
            Last Name<br/>
            <input type="text" name="txt_last_name" id="txt_last_name"><br/>
            Contact Number<br/>
            <input type="text" name="txt_number" id="txt_number"><br/>
            Email<br/>
            <input type="text" name="txt_email" id="txt_email"><br/>
            Cover letter<br/>
            <textarea name="txt_cover_letter" rows="10" cols="30"></textarea><br/>
            Upload resume
            <input type="file" name="txt_resume" id="txt_resume"><br/><br/>
            <input type="submit" name="btn_send_resume" value="Submit">
        </form>
    </body>
</html>


Step 3:

Submit action page(upload_file.php)


<?php

// Including the class.phpmailer.php in phpmailer folder to our action page
require_once './mail/class.phpmailer.php';   


if(isset($_REQUEST['btn_send_resume']))
{
    
    $txt_first_name     =   $_REQUEST['txt_first_name'];
    $txt_last_name      =   $_REQUEST['txt_last_name'];
    $name = $txt_first_name." " .$txt_last_name;
    $txt_number         =   $_REQUEST['txt_number'];
    $txt_email          =   $_REQUEST['txt_email'];
    $txt_cover_letter   =   $_REQUEST['txt_cover_letter'];
    $txt_job_title      =   "Career openings in mublesolutions";


    // HTML message in the mail
    $message           =   '<html>
                    <head>
                    </head>
                    <body>
                        <div style="margin:auto;width:90%;padding:30px 10px">
                            <div style="border: 1px solid #E9E9E9; min-height: 600px;width:100%;padding:10px">

                                <hr style="border: 1px solid #E9E9E9; padding:0px 10px ">
                                <br/>
                                <h4 style="color:51A8B;">Dear Recruiter,</h4>
                                <p>One candidate is applied for the job <b>'.$txt_job_title.'</b>,Candidate details are listed below </p>

                                <table style="text-align: left;border-bottom:1px solid #20629C;width:100%">
                                    <tr style="line-height: 40px;background-color:#20629C;color:white;">
                                        <th width="300" colspan="2">Candidate details</th>
                                    </tr>
                                    <tr style="line-height:30px;    ">
                                        <th>First name </th>
                                        <td>&nbsp;&nbsp;'.$txt_first_name.'</td>
                                    </tr>
                                    <tr style="line-height:30px;">
                                        <th>Last name</th>
                                        <td>&nbsp;&nbsp;'.$txt_last_name.'</td>
                                    </tr>
                                    <tr style="line-height:30px;">
                                        <th>Email ID</th>
                                        <td>&nbsp;&nbsp;'.$txt_email.'</td>
                                    </tr>
                                    <tr style="line-height:30px;">
                                        <th>Contact Number</th>
                                        <td>&nbsp;&nbsp;'.$txt_number.'</td>
                                    </tr>

                                </table>
                                <h4>Cover letter</h4>
                                <p>'.$txt_cover_letter.'</p>
                                <h4>Candidate resume is attached along with this mail</h4>
                                <hr style="border: 1px solid #E9E9E9; padding:0px 10px "><br/>

                            </div>
                        </div>
                    </body>
                </html>';


       // Checking file is uploaded and sending mail 
        if(isset($_FILES['txt_resume']))
        {
            $file_name                         =       $_FILES['txt_resume']['name'];
            $temp_name                      =       $_FILES['txt_resume']['tmp_name'];
            $details                              =       pathinfo($file_name);
            $file                                   =       $details["filename"];
            $extension                         =       $details['extension'];

            $rand_digit                        =       rand(0000, 9999);
            $allowed_extension          =       array("pdf", "doc", "docx","odt","txt");
            if (($_FILES["file_employee_resume"]["size"] < 20000000) && in_array($extension, $allowed_extension))
            {
                if ($_FILES["file_employee_resume"]["error"] > 0)
                {
                    $response           =       "error";
                }
                else
                {
                    $target_path        =       "uploads/";
                    $new_file_name      =       $file.$rand_digit.".".$extension;
                    if(move_uploaded_file($temp_name,$target_path.$new_file_name))
                    {

                            //Sending mail using php mailer
                            $mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

                            try
                            {

                                  $mail->AddAddress('aryapramesan@gmail.com', 'John Doe'); // To address
                                  $mail->SetFrom($txt_email,$name ); // From address
                                  $mail->Subject = 'Application received against your Job Offer:'.$txt_job_title;
                                  $mail->MsgHTML($message); // Html messages if any can added using this method can read a file also
                                  $mail->AddAttachment("uploads/".$new_file_name); // attachment
                                  $mail->Send();
                                  $response  =   "success";
                                  unlink($target_path.$new_file_name); //Removing file uploaded to uploads folder
                            }
                            catch (phpmailerException $e)
                            {
                              $response  = $e->errorMessage(); //Pretty error messages from PHPMailer
                            }
                            catch (Exception $e)
                            {
                              $response  = $e->getMessage(); //Boring error messages from anything else!
                            }
                    }
                    else
                    {
                         $response      =      "move";
                    }

                }


            }
            else
            {
                $response = "extension";
            }
            echo $_SESSION['msg']       =   $response;
        }

}

?>


We need to create an upload folder to upload file to our server after sending the mail we can unlink the file from our upload folder

  $mail->MsgHTML(file_get_contents('content.html'));

We can red content from an html file and set it as our html message




Thursday, 27 March 2014

Ajax multi checkbox filter search PHP Mysql

Ajax multi checkbox filter search
Lekhulal
lekhulal@gmail.com
---------------------------------------------------------------------------

1) Let’s create a database called "db_name"

-----------------------------------------------

2) create a table

CREATE TABLE IF NOT EXISTS `workers` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) DEFAULT NULL,
 `age` int(11) DEFAULT NULL,
 `address` varchar(255) DEFAULT NULL,
 `hasCar` tinyint(1) DEFAULT NULL,
 `speaksForeignLanguage` tinyint(1) DEFAULT NULL,
 `canWorkNights` tinyint(1) DEFAULT NULL,
 `isStudent` tinyint(1) DEFAULT NULL,
 PRIMARY KEY (`id`)
 );
 
-----------------------------------------------
 
3) Insert some data
 
INSERT INTO `workers` (`id`, `name`, `age`, `address`, `hasCar`, 
`speaksForeignLanguage`, `canWorkNights`, `isStudent`) VALUES
(1, 'Jim', 39, '12 High Street, London', 1, 1, 1, 1),
(2, 'Fred', 29, '13 High Street, London', 1, 1, 1, 0),
(3, 'Bill', 19, '14 High Street, London', 1, 1, 0, 0),
(4, 'Tom', 39, '15 High Street, London', 1, 0, 0, 0),
(5, 'Cathy', 29, '16 High Street, London', 1, 0, 0, 1),
(6, 'Petra', 19, '17 High Street, London', 1, 0, 1, 0),
(7, 'Heide', 39, '18 High Street, London', 1, 1, 0, 0),
(8, 'William', 29, '19 High Street, London', 1, 1, 0, 1),
(9, 'Ted', 19, '20 High Street, London', 0, 0, 0, 1),
(10, 'Mike', 19, '21 High Street, London', 1, 0, 0, 1),
(11, 'Jo', 19, '22 High Street, London', 0, 1, 0, 1);
 
-----------------------------------------------
 
4) Create a page called index.php
 
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>AJAX filter demo</title>
    <style>
      body {
        padding: 10px;
      }

      h1 {
          margin: 0 0 0.5em 0;
          color: #343434;
          font-weight: normal;
          font-family: 'Ultra', sans-serif;   
          font-size: 36px;
          line-height: 42px;
          text-transform: uppercase;
          text-shadow: 0 2px white, 0 3px #777;
      }
 
      h2 {
          margin: 1em 0 0.3em 0;
          color: #343434;
          font-weight: normal;
          font-size: 30px;
          line-height: 40px;
          font-family: 'Orienta', sans-serif;
      }

      #employees {
        font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
        font-size: 12px;
        background: #fff;
        margin: 15px 25px 0 0;
        border-collapse: collapse;
        text-align: center;
        float: left;
        width: 700px;
      }

      #employees th {
        font-size: 14px;
        font-weight: normal;
        color: #039;
        padding: 10px 8px;
        border-bottom: 2px solid #6678b1;
      }

      #employees td {
        border-bottom: 1px solid #ccc;
        color: #669;
        padding: 8px 10px;
      }

      #employees tbody tr:hover td {
        color: #009;
      }

      #filter {
        float:left;
      }
    </style>
  </head>
  <body> 
    <h1>Ajax filter search using PHP Mysql</h1>

    <table id="employees">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Age</th>
          <th>Address</th>
          <th>Car</th>
          <th>Language</th>
          <th>Nights</th>
          <th>Student</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

    <div id="filter">
      <h2>Filter options</h2>
      <div>
        <input type="checkbox" id="car" name="hasCar">
        <label for="car">Has own car</label>
      </div>
      <div>
        <input type="checkbox" id="language" name="speaksForeignLanguage">
        <label for="language">Can speak foreign language</label>
      </div>
      <div>
        <input type="checkbox" id="nights" name="canWorkNights">
        <label for="nights">Can work nights</label>
      </div>
      <div>
        <input type="checkbox" id="student" name="isStudent">
        <label for="student">Is a student</label>
      </div>
    </div>

    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script>
      function makeTable(data){
       var tbl_body = "";
          $.each(data, function() {
            var tbl_row = "";
            $.each(this, function(k , v) {
              tbl_row += "<td>"+v+"</td>";
            })
            tbl_body += "<tr>"+tbl_row+"</tr>";                 
          })

        return tbl_body;
      }

      function getEmployeeFilterOptions(){
        var opts = [];
        $checkboxes.each(function(){
          if(this.checked){
            opts.push(this.name);
          }
        });

        return opts;
      }

      function updateEmployees(opts){
  //alert(opts);
        $.ajax({
          type: "POST",
          url: "submit.php",
          dataType : 'json',
          cache: false,
          data: {filterOpts: opts},
          success: function(records){
  alert("records"+records);
            $('#employees tbody').html(makeTable(records));
          }
        });
      }

      var $checkboxes = $("input:checkbox");
      $checkboxes.on("change", function(){
        var opts = getEmployeeFilterOptions();
        updateEmployees(opts);
      });

      updateEmployees();
    </script> 
  </body> 
</html> 

-----------------------------------------------

4)create a action page called submit.php :
  set database configuration(database username and password) 
 

<?php
  $pdo = new PDO('mysql:host=localhost;dbname=db_name', 'root', 'password'); 
  $select = 'SELECT *'; 
  $from = ' FROM workers'; 
  $where = ' WHERE TRUE'; 
   $opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
  
  if (in_array("hasCar", $opts)){
    $where .= " AND hasCar = 1";
  }

  if (in_array("speaksForeignLanguage", $opts)){
    $where .= " AND speaksForeignLanguage = 1";
  }

  if (in_array("canWorkNights", $opts)){
    $where .= " AND canWorkNights = 1";
  }

  if (in_array("isStudent", $opts)){
    $where .= " AND isStudent = 1";
  }

  $sql = $select . $from . $where; 
  $statement = $pdo->prepare($sql);
  $statement->execute();
  $results=$statement->fetchAll(PDO::FETCH_ASSOC);
  $json=json_encode($results);
  echo($json);
?>

-----------------------------------------------

Wednesday, 26 March 2014

Full text Search



Full-Text Searches PHP - Mysql

Lekhulal 

lekhulal@gmail.com

---------------------------------------------------------------------------------------------

--
--
-Create a table called articles
-That table type must support FULLTEXT indexes.
-Set of one or more columns included in a FULLTEXT index.
--
--

CREATE TABLE articles
(
title VARCHAR(200),
body TEXT,
FULLTEXT (title,body)
);


--
--
Insert values into table called articles
--
--

INSERT INTO articles (title,body)
VALUES
('MySQL Tutorial','DBMS stands for DataBase ...'),
('How To Use MySQL Well','After you went through a ...'),
('Optimizing MySQL','In this tutorial we will show ...'),
('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
('MySQL vs. YourSQL','In the following database comparison ...'),
('MySQL Security','When configured properly, MySQL ...');


--
--
-Write query for full text search.
-The search string is given as the argument to AGAINST().
-For each row in the table, MATCH() returns a relevance value.
-The search is performed in case-insensitive.
--
--

SELECT * FROM articles
WHERE MATCH (title,body) AGAINST ('database');


--
--
-The number of unique words in that row.
--
--

SELECT
COUNT(IF(MATCH (title,body) AGAINST ('database'), 1, NULL))
AS count
FROM articles;


--------------------------------------- Thank You -------------------------------------

Friday, 7 March 2014

 

HOW TO VIEW AN UPLOADED  FILE IN PHP ?

                   
                                                                                                  Rahul R 
                                                                                                                        rahul9629@gmail.com
------------------------------------------------------------------------------------------------------------------------------------




We can use google document viewer to view an uploded file.


Step 1:Go to google document viewer  https://docs.google.com/viewer

Step 2:Enter your filename(http://yoursite.com/uploads/resumename.doc)  in to the google document viewer textbox.Then click generate link

Step 3: Copy the needed link(iframe or href) from google document viewer.

Step 4:Then paste in to your page.  
            
----------------------------------------------------------------------------------------------------------------------------------
1.index.php
----------------------------------------------------------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <h1>VIEW FILE</h1>


        <h3>Direct redirection to the google document viewer</h3>
       

       <!-- It will redirect to the google document viewer -->
       <a href="https://docs.google.com/viewer?url=http://yoursitename.com/uploadfoldername/filename.doc">View File</a>

       <br/><br/>
       <h3>Integrating Gogle viewer to Our Project</h3>
       

       <!-- Redirect to our own next page there we will view the document -->
       <a href="resume_view.php?doc=filename.doc">File view in our page</a>
    </body>
</html>




----------------------------------------------------------------------------------------------------------------------------------
2.resume_view.php (Integrating Google document viewer to our page)
----------------------------------------------------------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Document Viewer/Downloads</title>

    </head>
    <body style="margin:auto;">
        <div id="container">
            <div class="header1">
                <h1>DOCUMENT VIEWER AND DOWNLOADS</h1>
            </div>


            <?php
                    // Getting the file name
                    if(isset($_REQUEST['doc']))
                    {
                       $filename    =   $_REQUEST['doc'];
                    }

            ?>
            <div class="content">

             <!--Generate the iframe from google document viewer and copy iframe to our page-->
             <iframe src="http://docs.google.com/viewer?url=http%3A%2F%2Fyoursitename.com%2Ffoldername%2F<?php echo  $filename ?>&embedded=true" width="75%" height="1000" style="border: none;"></iframe>
            </div>
       </div>
    </body>
</html>

 

HOW TO DOWNLOAD FILE IN PHP?

                   
                                                                                                  Rahul R 
                                                                                                                        rahul9629@gmail.com
------------------------------------------------------------------------------------------------------------------------------------

HTML SECTION WITH LINK FOR DOWNLOAD FILE

<html>
    <head>
        <title>Download File</title>
    </head>
    <body>
        <!--Link For Downloading Resume -->
        <a href="download.php?doc=coding stds in brief.doc">Download</a> 
    </body>
</html>

 

PHP SECTION FOR DOWNLOAD

<?php


if(isset($_REQUEST['doc']))
   
     // change the path to fit your websites document structure 
     $path = "uploads/";
   
    //Getting filename and seeting the path like uploads/coding stds in brief.doc
    $fullPath = $path.$_GET['doc'];  


    if ($fd = fopen ($fullPath, "r"))
    {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);
        $ext = strtolower($path_parts["extension"]);
        switch ($ext)
        {
            case "pdf":
            header("Content-type: application/pdf"); // add here more headers for diff. extensions
            header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
            break;
            default;
            header("Content-type: application/octet-stream");
            header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        }
        header("Content-length: $fsize");
        header("Cache-control: private"); //use this to open files directly
        while(!feof($fd))
        {
        $buffer = fread($fd, 2048);
        echo $buffer;
        }
    }
    fclose ($fd);
    exit;
}
?>

Tuesday, 28 January 2014

Call to undefined method DateTime::diff

Call to undefined method DateTime::diff

Lekhulal

lekhulal@gmail.com

----------------------------------------

Problem:-

$date1=new DateTime($row[0]); 

$date2=new DateTime(date("Y-m-d"));

$interval=$date1->diff($date2);

$a=$interval->days;

Fatal error: Call to undefined method DateTime::diff()

 

Solution:-

$date1 = strtotime($row[0]);

$date2 =strtotime(date("Y-m-d"));

$diff = $date2 - $date1;

$a = round($diff / 86400);

 

 

Friday, 24 January 2014

Delete all proceudres in a single query

 

 Delete all procedures in a single query

Lekhulal

lekhulal@gmail.com

----------------------------------------------------------------------------------------------------------------------------------------


DELETE FROM mysql.proc WHERE db = 'db_sample' AND type = 'PROCEDURE';