article

Tuesday, July 30, 2013

Delete Confirmation using Javascript

Delete Confirmation using Javascript 
 
<script>
function confirmDelete()
{
    return confirm("Are you sure you wish to delete this entry?");
}
</script>
<a href="?action=delete&id=3" onclick="return confirmDelete();"> Delete this entry</a>

PHP Tutorial: Classes and OOP

PHP Tutorial: Classes and OOP 

 
<?php
//PHP Tutorial: Classes and OOP
//The first thing you do is to define the class:
class cow
{
}
//Next, we'll create our first function - this is defined exactly the same as if you were not using classes:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
//create the new class object 'in' a variable
// Create new cow object
$daisy = new cow;
//then call the moo() function
echo $daisy->moo();

//If you put this code together then, you will get something like this:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
// Create new cow object
$daisy = new cow;
echo $daisy->moo();

//Ex. more functions
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

//call these functions and try out the new class
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced

//final version
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();

echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
?>

Saturday, July 27, 2013

Style a Select Box Using CSS

Style a Select Box Using CSS
 
<style>
.styled-select select {
   background: transparent;
   width: 268px;
   padding: 5px;
   font-size: 16px;
   line-height: 1;
   border: 0;
   border-radius: 0;
   height: 34px;
   -webkit-appearance: none;
   }
   .styled-select {
   width: 240px;
   height: 34px;
   overflow: hidden;
   background: url(down_arrow_select.jpg) no-repeat right #ddd;
  
   display:block;font-size:16px;outline:0 none;padding:.4em;text-shadow:0 1px 0 #fff;-moz-border-radius:.6em;-webkit-border-radius:.6em;border-radius:.6em;border:1px solid #aaa;color:#333;text-shadow:0 1px 0 #fff;
   }
</style>
<div class="styled-select">
   <select>
      <option>Male</option>
      <option>Female</option>
   </select>
</div>

Friday, July 26, 2013

PHP, jQuery and MySQL Search

PHP, jQuery and MySQL Search
//index.html
<style>
body{ font-family:Arial, Helvetica, sans-serif; }
*{ margin:0;padding:0; }
#container { margin: 0 auto; width: 600px; }
a { color:#DF3D82; text-decoration:none }
a:hover { color:#DF3D82; text-decoration:underline; }
ul.update { list-style:none;font-size:1.1em; margin-top:10px }
ul.update li{ height:30px; border-bottom:#dedede solid 1px; text-align:left;}
ul.update li:first-child{ border-top:#dedede solid 1px; height:30px; text-align:left; }
#flash { margin-top:20px; text-align:left; }
#searchresults { text-align:left; margin-top:20px; display:none; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#000; }
.word { font-weight:bold; color:#000000; }
#search_box { padding:4px; border:solid 1px #666666; width:300px; height:30px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
.search_button { border:#000000 solid 1px; padding: 6px; color:#000; font-weight:bold; font-size:16px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
.found { font-weight: bold; font-style: italic; color: #ff0000; }
h2 { margin-right: 70px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $(".search_button").click(function() {
        // getting the value that user typed
        var searchString    = $("#search_box").val();
        // forming the queryString
        var data            = 'search='+ searchString;
         
        // if searchString is not empty
        if(searchString) {
            // ajax call
            $.ajax({
                type: "POST",
                url: "do_search.php",
                data: data,
                beforeSend: function(html) { // this happens before actual call
                    $("#results").html('');
                    $("#searchresults").show();
                    $(".word").html(searchString);
               },
               success: function(html){ // this happens after we get results
                    $("#results").show();
                    $("#results").append(html);
              }
            });   
        }
        return false;
    });
});
</script>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" /><br />
</form>
</div>     
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
//do_search.php
<?php
//if we got something through $_POST
if (isset($_POST['search'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $word = mysql_real_escape_string($_POST['search']);
    $word = htmlentities($word);
    // build your search query to the database
    $sql = "SELECT title, url FROM pages WHERE content LIKE '%" . $word . "%' ORDER BY title LIMIT 10";
    // get results
    $row = $db->select_list($sql);
    if(count($row)) {
        $end_result = '';
        foreach($row as $r) {
            $result         = $r['title'];
            // we will use this to bold the search word in result
            $bold           = '<span class="found">' . $word . '</span>';   
            $end_result     .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';           
        }
        echo $end_result;
    } else {
        echo '<li>No results found</li>';
    }
}
?>

Username availability check using PHP and jQuery

Username availability check using PHP and jQuery
 
<?php

/* CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`username` varchar(150) NOT NULL,
`email` varchar(100) NOT NULL',
`pass` varchar(100)  NOT NULL',
PRIMARY KEY (`id`)
) */
//Username availability check using PHP and jQuery
//if we got something through $_POST
if (isset($_POST['user'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $username = mysql_real_escape_string($_POST['user']);
    // build your query to the database
    $sql = "SELECT count(*) as num FROM users WHERE username = " . $username;
    // get results
    $row = $db->select_single($sql);
    if($row['num'] == 0) {
        echo 'Username <em>'.$username.'</em> is available!';
    } else {
        echo 'Username <em>'.$username.'</em> is already taken!';
    }
}
?>
<script>
$(function() {
$("#sub").click(function() {
    // getting the value that user typed
    var checkString    = $("#username_box").val();
    // forming the queryString
    var data            = 'user='+ checkString;
 
    // if checkString is not empty
    if(checkString) {
        // ajax call
        $.ajax({
            type: "POST",
            url: "do_check.php",
            data: data,
            beforeSend: function(html) { // this happen before actual call
                $("#results").html('');
            },
            success: function(html){ // this happen after we get result
                $("#results").show();
                $("#results").append(html);
            }
        });
}
return false;
});
});
</script>
<form action="do_check.php" method="post">
    <input id="username_box" class="search_box" name="username" type="text" />
    <input id="sub" type="submit" value="Check" />
</form>

Thursday, July 25, 2013

Using Sessions in WordPress Plugins

Using Sessions in WordPress Plugins 

In your theme/plugin

Add the next piece of code to your functions.php or plugin file to enable sessions:

/**
 * init_sessions()
 *
 * @uses session_id()
 * @uses session_start()
 */
function init_sessions() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');

PHP Multiple Atachment Send

PHP Multiple Atachment Send 


E-mail with Attachment
 <?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

   // we'll begin by assigning the To address and message subject
   $to="somebody@example.com";
   $subject="E-mail with attachment";

   // get the sender's name and email address
   // we'll just plug them a variable to be used later
   $from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";

   // generate a random string to be used as the boundary marker
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   // now we'll build the message headers
   $headers = "From: $from\r\n" .
   "MIME-Version: 1.0\r\n" .
      "Content-Type: multipart/mixed;\r\n" .
      " boundary=\"{$mime_boundary}\"";

   // here, we'll start the message body.
   // this is the text that will be displayed
   // in the e-mail
   $message="This is an example";

   // next, we'll build the invisible portion of the message body
   // note that we insert two dashes in front of the MIME boundary 
   // when we use it
   $message = "This is a multi-part message in MIME format.\n\n" .
      "--{$mime_boundary}\n" .
      "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
      "Content-Transfer-Encoding: 7bit\n\n" .
   $message . "\n\n";

   // now we'll process our uploaded files
   foreach($_FILES as $userfile){
      // store the file information to variables for easier access
      $tmp_name = $userfile['tmp_name'];
      $type = $userfile['type'];
      $name = $userfile['name'];
      $size = $userfile['size'];

      // if the upload succeded, the file will exist
      if (file_exists($tmp_name)){

         // check to make sure that it is an uploaded file and not a system file
         if(is_uploaded_file($tmp_name)){
  
            // open the file for a binary read
            $file = fopen($tmp_name,'rb');
  
            // read the file content into a variable
            $data = fread($file,filesize($tmp_name));

            // close the file
            fclose($file);
  
            // now we encode it and split it into acceptable length lines
            $data = chunk_split(base64_encode($data));
         }
  
         // now we'll insert a boundary to indicate we're starting the attachment
         // we have to specify the content type, file name, and disposition as
         // an attachment, then add the file content.
         // NOTE: we don't set another boundary to indicate that the end of the 
         // file has been reached here. we only want one boundary between each file
         // we'll add the final one after the loop finishes.
         $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }
   // here's our closing mime boundary that indicates the last of the message
   $message.="--{$mime_boundary}--\n";
   // now we just send the message
   if (@mail($to, $subject, $message, $headers))
      echo "Message Sent";
   else
      echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" 
   enctype="multipart/form-data" name="form1">
   <p>From name: <input type="text" name="fromname"></p>
   <p>From e-mail: <input type="text" name="fromemail"></p>
   <p>File: <input type="file" name="file1"></p>
   <p>File: <input type="file" name="file2"></p>
   <p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>

Sanitize Input Form

Sanitize Input Form

 
<?php
include('connect.php');
$conn = db_connect();
 
 function cleanInput($input) {
  $search = array(
   '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
   '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
   '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
   '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
 );
  $output = preg_replace($search, '', $input);
  return $output;
 }

?>
<?
if(isset($_POST["submit"]))
{
 $_username = cleanInput($_POST["_username"]);
 $_password = md5($_POST["_password"]);  
 $sql_insert = "INSERT INTO tbl_admin(_username, _password) VALUES ('$_username', '$_password')";
 $result = mysql_query($sql_insert);
 echo "records save"; 
 //echo "<script>
 //   window.location='index.php';
 //    </script>";
 //
}
?>
<div style="padding-left:50px; font-weight:bold; font-size:18px; margin-bottom:20px; color:#ffffff">
 ADD NEW Users
</div>
<form name="subjadd" action="" method="post">
 <table width="96%" border="0" cellspacing="3" cellpadding="4">
  <tr>
   <th>User name:</th>
   <td><input name="_username" type="text" size="40"></td>
  </tr>
  <tr>
   <th>Password</th>
   <td><input name="_password" type="text" size="40"></td>
  </tr>
  <tr>
   <th></th>
   <td>
    <input type="submit" name="submit" value="Add New!">
</td>
  </tr>
 </table>
</form>

Public, Private and Protected - PHP OOP

Public, Private and Protected - PHP OOP 

Example 
 
<?php
//Public Visibility in PHP Classes
//Public methods or variables can be accessible from anywhere. It can be accessible from using object(outside the class), or inside the class, or in child class.
class test
{
public $abc;
public $xyz;
public function xyz()
{
}
}

$objA = new test();
echo $objA->abc;//accessible from outside
$objA->xyz();//public method of the class test
?>

<?php
//Private Visibility in PHP Classes
//only be accessible withing the class. Private visibility in php classes is used when you do not want your property or function to be exposed outside the class.
Class test
{
public $abc;
private $xyz;
public function pubDo($a)
{
echo $a;
}
private function privDo($b)
{
echo $b;
}
public function pubPrivDo()
{
$this->xyz = 1;
$this->privDo(1);
}
}
$objT = new test();
$objT->abc = 3;//Works fine
$objT->xyz = 1;//Throw fatal error of visibility
$objT->pubDo("test");//Print "test"
$objT->privDo(1);//Fatal error of visibility
$objT->pubPrivDo();//Within this method private function privDo and variable xyz is called using $this variable.
?>


<?php
//Protected Visibility in PHP Classes
//useful in case of inheritance and interface. Protected method or variable can be accessible either within class or child class.
class parent
{
protected $pr;
public $a
protected function testParent()
{
echo this is test;
}
}
class child extends parent
{
public function testChild()
{
$this->testParent(); //will work because it
}
}
$objParent = new parent();
$objParent->testParent();//Throw error
$objChild = new Child();
$objChild->setChild();//work because test child will call test parent.
?>

Saturday, July 13, 2013

Clearing File Input Values

Clearing File Input Values


 
<script type="text/javascript">
        function clearFileInput( id )
        {
            var elem = document.getElementById( id );
            elem.parentNode.innerHTML = elem.parentNode.innerHTML;
        }
    </script>

    <form method="post" enctype="multipart/form-data">
        <input type="file" name="myFile" id="fileInput1" />
        <input type="submit" name="s" value="Upload" />
    </form>
    <a href="javascript:clearFileInput( 'fileInput1' );">Clear File Input Value</a>

Get URL Parameters Using Javascript

Get URL Parameters Using Javascript

 
function getparamurl( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

var get_param = getparamurl('getid');
alert(get_param);
http://tutorial101.blogspot.com/index.html?getid=123

Related Post