Header menu

_________________________________________________________________________________

Thursday, 19 December 2013

Explain difference between array_merge( ) and array_combine( ) in php

ARRAY_MERGE()


array_merge() id used to merge the elements of one or more than one array in such a way  that the value of one array appends at the end of first array. If the any of the arrays have same key ,then the later value overrides the previous value for that key. The output of the function is one resultant array and this function takes two arrays as input.

ARRAY_COMBINE()


array_combine() is used to creates a new array by using the key of one array as keys and using the value of other array as values.One thing to keep in mind while using array_combine() that number of values in both arrays must be same.

Example :

<h2>ARRAY_MERGE()</h2>
<?php
$array1 = array("one" => "java","two" => "sql");

Wednesday, 18 December 2013

Explain Header() function in php in detail

Header function in php :



<?php header("Location: http://www.codesplanet.blogspot.com/"); ?>

Header function in php is used for redirection to some other page. In simplest form it takes one parameter
the destination url . 

Uses of header() function in php

 

1. The header() function use to sends a raw HTTP header to a client.
2. Use for refresh the page on after given time interval.
3. can be used to send email header content like cc, bcc , reply to etc data and lot more .


What is the Limitation of HEADER()?


In PHP the one and most horrible limitation of HEADER() function is that

Monday, 16 December 2013

Create variable at runtime in php

Hey ... Today we are going to create variable at runtime from an array;
I have declared an array named $arr and i am iteration array using foreach loop
and for each element creating a variable using   $$ar .
And at last i am printing the created variables.

<?php
$arr=array("1"=>"abc","2"=>"def");
echo "<pre>";
print_r($arr);
foreach($arr as $ar){
   
    $$ar="success:".$ar;
}
echo $abc;
echo "<br/>";
echo $def;

?>


Run the above example , to understand more ...

Friday, 6 December 2013

Knockout js Tutorial

<html>
<head>
<style>
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }
</style>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”></script>
<script type=’text/javascript’ src=’http://knockoutjs.com/downloads/knockout-3.0.0.js’></script>
</head>
<body>
<div class=’liveExample’>
<p>Data bind to text field</p> 
<p>First Message: <strong data-bind=”text: msg1″></strong></p>
<p>Second Message: <strong data-bind=”text: msg2″></strong></p> 
<hr>
<p>Data bind to input field</p> 
<p>First Box: <input data-bind=”attr: {value: msg1}” /></p> 
<p>Second Box: <input data-bind=’attr: {value: msg2}’ /></p> 
</div>
</body>
<script>
function AppViewModeldashboard() {
// Here’s my data model
this.msg1 = “hello”;
this.msg2 = “world”;
}
</script>
<script type=’text/javascript’ >
$(document).ready(function(){
var dashboard = new AppViewModeldashboard();
ko.applyBindings(dashboard);
});
</script> 
</html>

Wednesday, 30 October 2013

Add shortcode to template file in woocommerce or wordpress

Shortcode API, a simple set of functions for creating macro codes for use in post content. It enables plugin developers to create special kinds of content (e.g. forms, content generators) that users can attach to certain pages. For instance, the following shortcode (in the post/page content) would add a photo gallery into the page:     [gallery]

But this syntax work for only wp-admin post editor. If you want to add shortcode to your template file then you can use

<?php
        echo do_shortcode( '[shortcode_name]' );
 ?>
It will do same work as done by shortcode when it is added to post...

Tuesday, 29 October 2013

Concatenate html tags to string in php

To add html tags to string in php ... You have to concatenate html tags with string using htmlentities()
as shown below
$newstring="<u>".htmlentities("test")."</u>";
Here i have added <u> tag to my string test which is passed to htmlentities() function for concatenation.

For more details see the example
Example:

<?php
$mystring="Hello ... This is my test string . I am testing it for htmlentities()";
echo "This is string before adding html tags"."</br>";
echo "</br>";
echo $mystring;
echo "</br>";
echo "</br>";
$newstring="<u>".htmlentities("test")."</u>";
$finalstring=str_replace("test",$newstring,$mystring);
echo "This is string after add html tags"."</br>";
echo "</br>";
echo $finalstring;
?>


htmlentities

Friday, 25 October 2013

Warning: Cannot modify header information - headers already sent in - wordpress after activating custom plugin

Warning: Cannot modify header information - headers already sent by

If you got error like this after activation a new custom plugin in wordpress then you can use

error_reporting(0);    // Turn off all error reporting
  
Include this statement in every file due to which you are getiing warning . You are done , no more errors now :)

But remember if you are a developer..... you are only hiding errors ... not solving them ...
Try to solve them first ... If unable only then use this :)



Warning: Cannot modify header information - headers already sent in - wordpress after activating custom plugin

Tuesday, 22 October 2013

PHP cURL simple tutorial

CURL is a reflective object-oriented programming language for interactive web applications whose goal is to provide a smoother transition between formatting and programming. It makes it possible to embed complex objects in simple documents without needing to switch between programming languages or development platforms.

The strong point of cURL is the number of data transfer protocols it supports. It supports FTP, FTPS, HTTP, HTTPS, TFTP, SCP, SFTP, Telnet, DICT, FILE and LDAP.

PHP cURL allows you to read websites, upload files, upload data, fetch data and lots of more stuff ... Now its the time to see what we can do we PHP cURL...

PHP cURL example-1 :

<?php
$ch = curl_init ("http://www.alexa.com");             /** Initialise curl with url of alexa.com **/


curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);    /** Tell php curl that we want the data returned to us **/


$data = curl_exec ($ch);                            /** Execution of curl and result will be stored in $data **/

echo "<pre>";
print_r($data); /**preview result**/
?>


To understand more about cURL defination visit : PHP cURL

Monday, 21 October 2013

Runtime Analysis and Time Complexity

One of the most important aspects of an algorithm is how fast it is. It is often easy to come up with an algorithm to solve a problem, but if the algorithm is too slow, its a draw back. Since the exact speed of an algorithm depends on where it run, as well as the exact details of its implementation.
Computer scientists  talk about the runtime relative to the size of the input. For example, if the input consists of N integers, an algorithm might have a runtime proportional to N2, represented as O(N2). This means that if you were to run an implementation of the algorithm on your computer with an input of size N, it would take C*N2 seconds, where C is some constant that doesn't change with the size of the input.

However, the execution time of many complex algorithms can vary due to factors other than the size of the input. For example, a sorting algorithm may run much faster when given a set of integers that are already sorted than it would when given the same set of integers in a random order. As a result, you often hear about  the worst-case runtime, or the average-case runtime. The worst-case runtime is how long it would take for the algorithm to run if it were given the most insidious of all possible inputs. The average-case runtime is the average of how long it would take the algorithm to run if it were given all possible inputs. Of the two, the worst-case is often easier to reason about, and therefore is more frequently used as a benchmark for a given algorithm. The process of determining the worst-case and average-case runtimes for a given algorithm can be tricky, since it is usually impossible to run an algorithm on all possible inputs.

                          Approximate completion time for algorithms, N = 100...

Runtime-Analysis-and-Time-Complexity
For more details visit:  Run time analysis and time complexity

Saturday, 19 October 2013

Assign a php array to a jquery variable

To assign php array to jquery variable use

var jArray= <?php echo json_encode($phpArray ); ?>;

jArray  is the jquery variable which hold array in jquery and
$phpArray contains my php array ...
----------------------------------------------------------------------------------------------
For more details run below example:

<html>
<head>

</head>
<body>

<b> Hello .. Today we are assigning a php array to jquery variable <b>
<?php $phpArray = array(
          0 => "Mon",
          1 => "Tue",
          2 => "Wed",
          3 => "Thu",
          4 => "Fri",
          5 => "Sat",
          6 => "Sun",

    )?>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
     var jArray= <?php echo json_encode($phpArray ); ?>;
     for(var i=0;i<6;i++){
     alert(jArray[i]);
    }
    alert("Refresh again to see Array-Data    ")
});
</script>
</html>


Add custom price to product in woocommerce

Woocommerce saves its product price in a dynamic database table in serialized form which are present on cart..... Hence we cannot edit it directly ...

So , to add your custom price use below code:

function add_custom_price( $cart_object) {

  $custom_price = 1151; // This will be your custome price 

  foreach ( $cart_object->cart_contents as $key => $value ) {
            $value['data']->price = $my_sess['price'];
        }
    } 
 add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' )
;

 If you dont know where to add this code ... Add it at the top of wocommerce-functions.php file present in wocommerce plugin
 Yippe .. Now you got your custom price for the products :)

Thursday, 17 October 2013

Get textarea value in jquery from form

Normally we use val() function with element id to get value of input field of form in jquery ...

But for the case of textarea it doesnt work :(

So to get value of textarea we have to first tell to jquery that we want to access value of textarea.
To do this ..use below code:

var value= $("textarea[id$='textarea-id']").val();

For more detail run below example ::

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
    $( "#b1" ).on("click",function(){
           
            var val=$("textarea[id$='textarea1']").val();
            alert(val);
        });
    $( "#b2" ).on("click",function(){
           
            var val=$("textarea[id$='textarea2']").val();
            alert(val);
        });   
});
</script>
</head>
<body>
Textarea1<textarea id="textarea1"   name="textarea1"></textarea>
<button type="button" id="b1" class="button">Button-1</button></br>
Textarea2<textarea id="textarea2"   name="textarea2"></textarea>

<button type="button" id="b2" class="button">Button-3</button>
</br></br></br>


</body>

</html>

Tuesday, 15 October 2013

How cart details(product_id,prices,quantity etc) are stored by woocommerce ?

Various information about cart are stored by woocmmerce by two ways:
1. In $woocommerce object( About session , cart info, subtotal etc)
2. In database table named persistent_cart which is dynamic ... it will get destroyed as soon as checkout is done.

So , now how to access all this info ...
For the 1st kind just declare global $woocommerce object and use below code to see all details

global $woocommerce;
echo "<pre>";
print_r($woocommerce);
exit;

For the 2nd kind you have to  fetch data from table.. therefore first declare $wpdb wordpress object and write sql query to get result
one thing to note here is... data is stored in serialize manner in woocommerce_persistent_cart table so you have to unserialize it before using it
only then you can use it. Below is code to get cart information from table

global $wpdb;
$array = $wpdb->get_results("select meta_value from ".$wpdb->prefix."usermeta where meta_key='_woocommerce_persistent_cart'");
//print_r($array);
$data =$array[0]->meta_value;
$de=unserialize($data);

Redirect to a url after login in wordpress/woocommerce


By default you are redirected to my account page in  wordpress/woocommerce after login.
If you want to redirect to some other url use the code below:

add_filter('woocommerce_login_redirect', 'ras_login_redirect');

function ras_login_redirect( $redirect_to ) {
     $redirect_to = "www.google.com";    

     return $redirect_to;
}


If you provide some value to $redirect_to you will be redirected to that url otherwise
you will be redirected to my account as due to default settings in wordpress.

Sunday, 13 October 2013

Update value of $wp_session['session_name'] in woocommerce/wordpress

$wp_session = WP_Session::get_instance();
 is method to create your own  session in woocommerce/wordpress.
You can use $wp_session['session_name'] on any file in woocommerce/wordpress
after creating but if you want to change its value you need to first convert this object to array.

For creating array use
$temp = current((array)$wp_session['session_name']);

$temp return you the array / value assigned to $wp_session['session_name']...
Now use or edit $temp as your need and after use assign this array again to $wp_session['session_name']
using

unset ($wp_session['session_name']);
$wp_session['session_name']=$temp;

Example :
$wp_session = WP_Session::get_instance();
$temp = current((array)$wp_session['session_name']);

/***

Work with the array

***/
unset ($wp_session['session_name']);
$wp_session['session_name']=$temp;

Convert $wp_session object to array

$wp_session = WP_Session::get_instance();
 is method to create your own  session in woocommerce/wordpress.
You can use $wp_session['session_name'] on any file in woocommerce/wordpress
after creating but if you want to change its value you need to first convert this object to array.

For creating array use
$temp = current((array)$wp_session['session_name']);

$temp return you the array / value assigned to $wp_session['session_name']...
Now use or edit $temp as your need and after use assign this array again to $wp_session['session_name']
using

unset ($wp_session['session_name']);
$wp_session['session_name']=$temp;

Example :
$wp_session = WP_Session::get_instance();
$temp = current((array)$wp_session['session_name']);

/***

Work with the array

***/
unset ($wp_session['session_name']);
$wp_session['session_name']=$temp;

Use $_SESSION in WordPress/Woocommerce

By default you cannot create your $_SESSION in WordPress/Woocommerce.
The information in $_SESSION remain in only those files on which it is created.
You cant access $_SESSION on  other file.

So, for creating your own session variable you need to install
WP Session Manager plugin.To download you can visit

http://wordpress.org/plugins/wp-session-manager/

And to use the $_SESSION you need to first create session object.
To create object use below line.

$wp_session = WP_Session::get_instance();

and to set value use

$wp_session['session_name']=array('one'=>'1','two'=>'2');
or
$wp_session['session_name']="Your value";


Note: You have to first create session object on every file where you wish to use $wp_session object.

Tuesday, 8 October 2013

Add span tag( or any html tag) to link in cakephp

To add <span> tag to cakephp link add span to label

"<span>Label name</span>"

and add

"array('escape' => false)"

to link as shown in below example.

Example:
<?php echo $this->Html->link(
    '<span>My Label</span>',
    array('action' => 'add'),
    array('escape' => false)
// This line will parse rather then output HTML
); ?>
One thing to note here 'escape' => false' must be added to 3rd parameter of link.
You can see the structure of cakephp link for more information at

http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html

Monday, 7 October 2013

Upload and save image with thumbnail in php

upload - This is the directory where i will save my image
upload/thumbs - This is the directory where i will save my thumbnails


<?php
if($_POST){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0 && $_FILES["file"]["name"]!=' ')
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    $dir="upload";
    if (!is_dir($dir)) {
            mkdir($dir);        
        }
   if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      echo"</br>";
      thumbs("upload");
      }
    }
  }
else
  {
  echo "Invalid file";
  }
 }
?>
<html>
<body>

Create thumbnails for complete directory in php

Create thumbnails for complete directory

If you wish to create thumbnails of large number of images then use the below php code
to create thumbnails .To create thumbnails, just give the path to images directory to
$orig_directory variable and run the script and your work is done ..!!


<?php

    $orig_directory = "img";     //Full path to image folder /* change this path */
    $thumb_directory =  $orig_directory;    //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
    $dir_handle = @opendir($orig_directory); //Open Full image dirrectory
    if ($dir_handle > 1){ //Check to make sure the folder opened
   
    $allowed_types=array('jpg','jpeg','gif','png');
    $file_parts=array();
    $ext='';
    $title='';
    $i=0;

FUNCTION.PHP file versus PLUGIN in wordpress

FUNCTION.PHP file versus PLUGIN in wordpress

If you have ever played  with a theme, you will know it has a functions.php file, which enables you to build plugin-like functionality into your theme.If we have this functions.php file,what is  the point of a use of plugin ?
 
Where should we use plugin and where should we use function.php file ?

Basically it all depends on your need.
Both do the same work , but the main difference is that a plugin’s functionality persists regardless of what theme you have enabled, whereas any changes you have made in functions.php will stop working once you switch themes.
Also, grouping related functionality into a plugin is often more convenient than leaving a mass of code in functions.php.
So it will be a good idea to use plugin if you want to use same code with different themes and different projects.

Thursday, 3 October 2013

Media upload error in wordpress after installation of customized plugin

Media upload error in wordpress after installation of customized plugin
 
After installation of custom plugin in wordpress sometimes error occurs while media upload.

The reason is you have may be you have included '$' in js of plugin(replace $ with jQuery)  or might be you have added js in plugin_name.php file. 

      



Media upload error in wordpress after installation of customized plugin



To correct the error include your js of plugin in separate js file and put this file in plugin_name folder with plugin_name.php file.

And to use this js in plugin add the below function in plugin file.

function my_scripts_method() {
    wp_enqueue_script(
        'plugin_name',
        plugins_url() . '/plugin_name/plugin_name.js',
        array( 'jquery' )
    );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );




Hope this will solve your problem :)


Tuesday, 24 September 2013

Could not create directory. /opt/lampp/htdocs/wordpress-test/wp-content/upgrade(Theme installation problem in wordpress)

Could not create directory. /opt/lampp/htdocs/wordpress-test/wp-content/upgrade

 Could not create directory. /opt/lampp/htdocs/wordpress-test/wp-content/upgrade

This error occur when you try to install some new theme on wordpress .
And your wp-content is not writable.





To correct this error

Change permissions on the /wp-content directory to 0775
 

if not work Change permissions on the /wp-content directory to 0777.

And dont forget to restore your permission after work is done as security measure.

Monday, 23 September 2013

Fatal error : Call to undefined function add_menu_page()

Fatal error : Call to undefined function add_menu_page()

If you want to add menu to admin section of wordpress through custom plugin and you got
"Fatal error : Call to undefined function add_menu_page() " error.

Then reason for error might be there is no add_action function found in plugin

Try this code to solve this error in your plugin file.

<?php

/*
Plugin Name: Myplugin

Description:
Version: 2.5.324
Author: Amit kumar


*/
add_action('admin_menu', 'test');

function test(){
    add_menu_page(__('My Menu Page'), __('My Menu'), 'edit_themes', 'my_new_menu', 'my_test_function', '', 7);
}

function my_test_function(){
    echo "hello world .. !!";
}

Saturday, 21 September 2013

Upload file in cakephp using move_uploaded_file function

move_uploaded_file()

Easiest way to upload file in cakephp is by using move_uploded_file function.
But it beneficial when you have to put file uploader at few place. If you need
to place large number of form which upload file then use component method otherwise
this is easier and much faster way.

I need one multipart form which can select file to upload i have  created one in
index.ctp and rest of the work will be done by index function in controller.



This is my controller file

<?php
class ContactsController extends ContactManagerAppController {
    public $uses = array('ContactManager.Contact');

    public function index() {
        if($this->request->is('post')){
            pr($this->request->data);
            $filePath = "./img/".$this->request->data['Contact']['image_file']['name']; 
            if(move_uploaded_file($this->request->data['Contact']['image_file']['tmp_name'], $filePath)){
            echo "File uploaded Successfully";
            }
       }
     } 
}








This is view for my Controller


index.ctp
<?php
    echo $this->Form->create('Contact', array('enctype' => 'multipart/form-data', 'class'=>'form-horizontal'));
?>
    <label class="control-label" for="inputError">Image</label>
<?php
    echo $this->Form->file('image_file');
    echo $this->Form->submit(__('Submit') , array('class'=>'btn btn-primary'));
?>




Thursday, 19 September 2013

Implode and Explode function of Php

Implode and Explode function of Php


<?php
// function 1:  implode()
echo "<h1>IMPLODE</h1>";
$arr=array("test1","test2","test3","test4","test5","test6","test7","test7");
echo "<pre>";  print_r($arr); echo "</pre>";

//implode(glue, pieces)

echo "Array with glue=none";
echo "</br>";echo "</br>";
$str=implode('', $arr);
echo $str;

echo "</br>";echo "</br>";
echo "Array with  ',' as glue to get comma separarted value from array ";
echo "</br>";echo "</br>";
$str=implode(',', $arr);
echo $str;
echo "</br>";echo "</br>";
// implode() function is used to join array elements and return string

// function 2:  explode(delimiter, string)
echo "<h1>EXPLODE</h1>";
echo $str="This is my string i am going to explode";
echo "</br>";echo "</br>";
echo "First using space as delimiter";
echo "<pre>";  print_r($arr); echo "</pre>";
$arr=explode(' ',$str);

echo "</br>";echo "</br>";
echo "Now using t as delimiter";
$arr=explode('t',$str);
echo "<pre>";  print_r($arr); echo "</pre>";
// explode breaks string into array where delimiter comes

?>

Array() / Array_fill() / Array_Keys() in php

Array() / Array_fill() / Array_Keys() in php

<?php
// function 1:  array()
$arr=array();
echo "Empty array created";
echo "<pre>";  print_r($arr); echo "</pre>";
// array() create an empty array

// function 2:  array_fill(start_index, num, value)
$arr=array_fill(0, 5, "test");
echo "Array filled with value";
echo "<pre>";  print_r($arr); echo "</pre>";
$arr[1]="failed";
$arr[3]="failed";
echo "Array after changes";
echo "<pre>";  print_r($arr); echo "</pre>";
// array_fill() fill the array with value given in parameter

// function 3:  arrays_keys(array,value)
echo "Keys where value is test in array";
$keyz=array_keys($arr,"test");
echo "<pre>";  print_r($keyz); echo "</pre>";
// arrays_keys() return the array of keys where value is same as parameter

?>

Monday, 16 September 2013

Send and receive data in ajax/jquery

How to send and receive data in ajax/jquery 

Sample Ajax tutorial in php



We will need two file for this tutorial ...
1. which send request and receive responce (test.php)
2. which receive request and send response (page.php)

On click of button ..the id of button will be send to page.php

And the response which we will get will replace html content of span id "val" .

test.php

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
    $( ".button" ).on("click",function(){

        $.ajax({
        type:"post",
url: "page.php",
data: {id:$(this).attr('id')},
success: function( data ) {
$( "#val" ).html( "<strong>" + data + "</strong> " );
}
});
        });
});
</script>
</head>
<body>
<button type="button" id="b1" class="button">Button-1</button>
<button type="button" id="b2" class="button">Button-2</button>
<button type="button" id="b3" class="button">Button-3</button>
</br></br></br>
<span id="val" style="background-color:#454282;">Which button is clicked ?<span>

</body>

</html>

---------------------------------------------------------------------------------------------------------------------------
page.php

<?php
$id=$_POST['id'];
if($id=="b1"){
echo "Button 1 is clicked ";
}
if($id=="b2"){
echo "Button 2 is clicked ";
}
if($id=="b3"){
echo "Button 3 is clicked ";
}

?>

Friday, 13 September 2013

Append some (text/img) after some html element using jquery

How to append some (text/img) after some html element using jquery 

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" >
        $(document).ready(function(){
var i=0;
        $("#sub").on("click",function(){
     $( "#1" ).append("Test "+i+" ... ");
         i++;
         });      
         });
</script>
</head>
<body>
<div id="1">This is my test...</div>
<button type="button"  id="sub">Append</button>
</form>
</body>
</html>

Prepend some (text/img) before some html element using jquery

How to prepend some (text/img) before some html element using jquery 

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" >
        $(document).ready(function(){
var i=0;
            $("#sub").on("click",function(){
$( "#1" ).prepend("Test "+i+" ... ");
                 i++;
                 });      
            });
 
        </script>
        </head>
    <body>
<div id="1">This is my test...</div>
<button type="button"  id="sub">Prepend</button>
</form>
</body>

</html>

Thursday, 12 September 2013

Write sql queries in cakephp controller

How to write sql queries in cakephp controller 

public function index(){
    $result= $this->User->query("SELECT * FROM users ;");  
}

User :- It is the name of my Model
users:- Table name in database

$result:- contain array of result of sql query

Get session information in cakephp

How to get session information in cakephp 

In the controller you can use

$this->Session->read();

to get all details of session variable . And you can use

$this->set('session',$this->Session->read());


to use these values in corresponding view page.

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

If you wish to use session variable in each page then use set method in appcontroller to set its value

public function beforefilter(){
$this->set('session',$this->Session->read());
}

Now this session variable is accessible in every page of view.

Note: this should be placed in Appcontroller...

Using some other file as index file when no index file is in the directory using .htaccess

Alternative index file using .htaccess

When there is no index file in php directory and you want that some other file act as index file then this code can be helpful
search is done from left to right ... whichever file is found first will be shown as index file


DirectoryIndex index.php index1.php index2.php index3.php

# u can use any name you want in place of index1.php

Commenting in the .htaccess file

Commenting in the .htaccess file

#Commenting in the .htaccess file is done by adding a # at the beginning of the line that you wish to comment.
#This instructs the server to ignore that line in the .htaccess file.

Hide directory information in php when index file is not present using .htaccess.

When no index file is present in directory and you want to hide listing on other files in php then .htaccess can be used to hide directory information.
Just copy the below lines in .htaccess file and put .htaccess file in directory for which you want to hide files list.

Options -Indexes

Wednesday, 11 September 2013

Cakephp 1.2 - include problem of css and js , and improper functioning

Changes to made to be made cake php version 1.2 properly :

1. uncomment the statement in file apache2/conf/httpd.config on wamp server

LoadModule rewrite_module modules/mod_rewrite.so

2. In the same file make sure

 AllowOverride all (if there is none in place of all .. change it to all for your "C:/wamp/www" directory)

3. Make sure that all three .htaccess files have default configuration .. there must not me any change ..

Tuesday, 10 September 2013

Create backup of database using php script


<?php
define('BACKUP_DIR', './Backups' ) ;
// Define  Database Credentials
define('HOST', 'localhost' ) ;
define('USER', 'amit' ) ;
define('PASSWORD', '' ) ;
define('DB_NAME', 'databse' ) ;
/*
Define the filename for the sql file
*/
$fileName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ;
// Set execution time limit
if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 )     set_time_limit(0) ;
}

// Check if directory is already created and has the proper permissions
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ;
// Create an ".htaccess" file , it will restrict direct accss to the backup-directory .
$content = 'deny from all' ;
$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ;
$file->fwrite($content) ;

$mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ;
if (mysqli_connect_errno())
{
   printf("Connect failed: %s", mysqli_connect_error());
   exit();
}
 // Introduction information
$return = "--\n";
$return .= "--  Mysql Backup \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return = "--\n";
$return .= "-- Database : " . DB_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ;
// Exploring what tables this database has
$result = $mysqli->query('SHOW TABLES' ) ;
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row())
{
$tables[] = $row[0] ;
}
// Cycle through each  table
 foreach($tables as $table)
 {
// Get content of each table
$result = $mysqli->query('SELECT * FROM '. $table) ;
// Get number of fields (columns) of each table
$num_fields = $mysqli->field_count  ;
// Add table information
$return .= "--\n" ;
$return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
$return .= "--\n" ;
$return.= 'DROP TABLE  IF EXISTS `'.$table.'`;' . "\n" ;
// Get the table-shema
$shema = $mysqli->query('SHOW CREATE TABLE '.$table) ;
// Extract table shema
$tableshema = $shema->fetch_row() ;
// Append table-shema into code
$return.= $tableshema[1].";" . "\n\n" ;
// Cycle through each table-row
while($rowdata = $result->fetch_row())
{
// Prepare code that will insert data into table
$return .= 'INSERT INTO `'.$table .'`  VALUES ( '  ;
// Extract data of each row
for($i=0; $i<$num_fields; $i++)
{
$return .= '"'.$rowdata[$i] . "\"," ;
 }
 // Let's remove the last comma
 $return = substr("$return", 0, -1) ;
 $return .= ");" ."\n" ;
 }
 $return .= "\n\n" ;
}
// Close the connection
$mysqli->close() ;
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; '  . "\n" ;
$return .= 'COMMIT ; '  . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n"  ;
$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ;
if( $resOpen ){
$zip->addFromString( $fileName , "$return" ) ;
    }
$zip->close() ;
$fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ;
$message = "BACKUP  completed ";
echo $message ;


function get_file_size_unit($file_size){
switch (true) {
    case ($file_size/1024 < 1) :
        return intval($file_size ) ." Bytes" ;
        break;
    case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1)  :
        return intval($file_size/1024) ." KB" ;
        break;
    default:
    return intval($file_size/(1024*1024)) ." MB" ;
}
}

?>

Monday, 9 September 2013

Session variable in cakephp

PHP session  allows you to store user information on the server for later use (i.e. username, time,visited urls etc), this information is temporary and
will be deleted after the user has left the website.

To access session variable in cakephp... Go to controller in which you want to see session variable and add following two lines in code..

$session=$this->Session->read();
pr($session);

Join us ...

Design form in cakephp

Note:Input name should be same as field name in database

Form to be written in .ctp in view

<?php
echo $this->Form->create('Model_name');
echo $this->Form->input('field1');
echo $this->Form->input('field2', array('rows' => '3'));
echo $this->Form->end('submit');
?>

Friday, 6 September 2013

Create two different url for admin and front site in cakephp

Most easy way to do this is by the use of scaffold variable.

Open the controller for which you want to make different admin page
and add the following statement:

public $scaffold='admin';

Now to go to app /config/core.php
and add the following statement:

Configure::write('Routing.prefixes', array('admin'));

Now create function for admin in controller like
public function admin_index(){
   
}


Now you access your admin using http://www.domain.com/admin/controller_name
and site using http://www.domain.com/controller_name

Thursday, 5 September 2013

Find position of string in a given string

Strpos Function


<html>
<body>
    <?php
        $str1="test";
        $str2="This is a testing string ";
        $pos=strpos($str2,$str1);
        echo "Given String : ".$str2."</br>";
        echo "String to be matched : ".$str1."</br>";
        echo "Match found at position : ".$pos;
        ?>
    </body>
</html>

Tuesday, 3 September 2013

How to block an ip address from visiting your website using .htaccess ?

1. Make a .htaccess file and save it in your root directory.
2. copy the code below:

order allow,deny
deny from 255.0.0.0   (blocked address)
deny from 192.168.1.96  (blocked address)
allow from all




3.  Paste in file and change the ip address to which you want to block.

4.  save the file


How to send Email with Attachment in PHP ?


Follow the link below and you will get the best tutorial for sending email with file attachment ...


Download Link:

Tutorial to send email with attachment

Monday, 2 September 2013

Access html form field using their name in jquery

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" >
        $(document).ready(function(){
            $("#sub").on("click",function(){
                $('input[name="bio[]"]').each(function() {
                    console.log($(this).val());
            });return false;
        });
    });
        </script>
        </head>
    <body>
<form action="#">
First name: <input type="text" name="bio[]"><br>
Last name : <input type="text" name="bio[]"><br>
Phone     : <input type="text" name="bio[]"><br>
Address   : <input type="text" name="bio[]">
<input type="submit" value="submit" id="sub"><br>
</form>
</body>
</html>

Friday, 30 August 2013

Send value of checked checkboxes on next page

<html>
    <body>
<?php
if($_POST){

    echo "<pre>";
    print_r($_POST['test']);
    echo "</pre>";
    }
?>
<form action="#" method="post">
<input type="checkbox" name="test[]"  value="Test1">Test1<br>
<input type="checkbox" name="test[]"  value="Test2">Test2 <br>
<input type="checkbox" name="test[]"  value="Test3">Test3<br>
<input type="checkbox" name="test[]"  value="Test4">Test4 <br>
<input type="submit" name="submit">
</form>
<body>
 <html>

Thursday, 29 August 2013

Paging in php

To implement paging we need 3 things :
1. php code
2. css file
3. database

So first create a database with name paging (you can take any name but this is the name i am taking ).
Then create a table with name tb_page with 3 fields (id , title , description).


Then go to link below and download 3 files and save them with same name in your root directory ..
Download link :  https://gist.github.com/codesplanet/6386348

Note : Dont forget to change your host name , user name and password of database in pagination.php file ..


Tuesday, 27 August 2013

Add link in an image in html

<html>
<body>
<div style="border:1px solid; background-color:#EDEDED; height:auto ;width:320px;">
    <div style="background-color:#666683; height:30px ;width:320px;">
        <b><p style=" text-color:#ffffff;align=:center; margin: 0 70;">Web Coding Source </p></b>
        </div>
<a href="http://codesplanet.blogspot.com/"><img border="1px" width="318px" height="250px" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheeCSPKa0IhwYuwA15R6DUhGrpWjnJnITxsfvE6MJcfxLNaJ369tsA8Cp7mdYxbc4Qi_LPDCHt8IKqp0aO_am8w_PimO75QvhKET-ENYCUbOuNkeeGzOaXlsqjzKWkxQBuXICwWNd9vig/s1600/apache-mysql-php-phpmyadmin-300x187.jpg"/></a>
</div>
</body>
</html>

How to convert a string to array in jquery ?

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
    $( document ).on("click",function(){
        var data="hello bro ..  how are you ??";
        alert('This is string : '+ data);
        var array_data=data.split(" ");
        alert("This is converted array : "+jQuery.each(array_data, function(index, value) {}));
});
});
</script>
</head>
<body>
converting  string to array in jquery ... on mouse click ..
</body>
</html>

Monday, 26 August 2013

How to design a basic joomla template ?

File Structure : (to be saved in template directory of joomla)

-------------------------------------------------------------------------------------------------
mytemplate(Folder)
                  -->index.php
                  -->template.xml
                  -->css(Folder)
                                ---> style.css
-------------------------------------------------------------------------------------------------

index.php

<html>
    <head>
        <jdoc:include type="head" />
        <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template; ?>/css/style.css" type="text/css" />
    </head>
    <body>
        Hello !!.. This is a testing template
        <jdoc:include type="modules" name="top" />
        <jdoc:include type="component" />
        <jdoc:include type="modules" name="bottom" />
    </body>
</html> 

template.xml 

<?xml version="1.0" encoding="utf-8"?>
<extension version="2.5" type="template">
        <name>mynewtemplate</name>
        <creationDate>2013-08-27</creationDate>
        <author>Amit kumar</author>
        <authorEmail>ak221189@gmail.com</authorEmail>
        <authorUrl>http://codesplanet.blogspot.com</authorUrl>
        <description>My New Template</description>
        <files>
                <filename>index.php</filename>
                <filename>template.xml</filename>
                <folder>images</folder>
                <folder>css</folder>
        </files>
        <positions>
                <position>breadcrumb</position>
                <position>left</position>
                <position>right</position>
                <position>footer</position>
        </positions>
</extension>

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


Now for joomla version 2.5 ,
1. go to extension(in admin panel)
2. click on extension manager
3. click on discover tab
4. click on discover button
5. now select your template and click install.

:) Happy coding

 







 

How to disable checkbox set using jquery ?

If you got two set of checkboxes and you have to use one at a time ... then using this code when you click on either of checkbox set .. the other will get disabled..



<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
    $( document ).on("click",function(){
        if($("input[name='test[]']:checked").val()){
        $('input:checkbox[name="test_2\[\]"]').attr('disabled', true);
        }
        if($("input[name='test_2[]']:checked").val()){
        $('input:checkbox[name="test\[\]"]').attr('disabled', true);
        }
        });
});
</script>
</head>
<body>


<form id="test_form">
    <b> Checkboxes1</b><br>
<input type="checkbox" name="test[]"   value="Test1">Test1<br>
<input type="checkbox" name="test[]"  value="Test2">Test2 <br>
<input type="checkbox" name="test[]"   value="Test3">Test3<br>
<input type="checkbox" name="test[]"  value="Test4">Test4 <br>
<b> Checkboxes2</b><br>
<input type="checkbox" name="test_2[]"   value="Test1">Test1<br>
<input type="checkbox" name="test_2[]"  value="Test2">Test2 <br>
<input type="checkbox" name="test_2[]"   value="Test3">Test3<br>
<input type="checkbox" name="test_2[]"  value="Test4">Test4 <br>
</form>

</body>
</html>

Sunday, 25 August 2013

How to get value of clicked checkbox using name in jquery ?

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
    $( document ).on("click",function(){
        if($("input[name='test[]']:checked").val()){
        alert($("input[name='test[]']:checked").val());}
        });
});
</script>
</head>
<body>
<b> Checkboxes</b><br>

<form id="test_form">
<input type="checkbox" name="test[]"   value="Test1">Test1<br>
<input type="checkbox" name="test[]"  value="Test2">Test2 <br>
<input type="checkbox" name="test[]"   value="Test3">Test3<br>
<input type="checkbox" name="test[]"  value="Test4">Test4 <br>
</form>

</body>
</html>

Friday, 23 August 2013

How to sort an array in php ?


<html>
<head>
<title>
Sorting an array in php
</title>
</head>
<body>
<?php
$arr=array("Rahul","George","tina","Angel");
echo "Array before sorting"."</br>";
echo "<pre>";
print_r($arr);
echo "</pre>";
sort($arr);
echo "Array After sorting"."</br>";
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
</body>
</html>

Thursday, 22 August 2013

How to add border in html div ?

Notice : solid in border

<html>
    <head>
        <title>
        Form
        </title>
    </head>
    <body>
        <div   align="center" style="border:1px solid ; background-color:#EA2343; height:400; width:700px;margin:0 auto;">
            Test
        </div>
    </body>
</html>

Align html div to center of page

<html>
    <head>
        <title>
        Form
        </title>
    </head>
    <body>
        <div   align="center" style="background-color:#EA2343; height:400; width:700px;margin:0 auto;">
            Test
        </div>
    </body>
</html>

How to convert a string into array in php ?

<?php
$str="Example";
$arr=array();
$arr=str_split($str);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

Wednesday, 21 August 2013

How to send an array in url in php ?

File.php  (This file contain array )

<?php

$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'script');

$arr=http_build_query($data);

?>
<a href="nextpage.php?<?php echo $arr; ?>">Sendarray</a>


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

nextpage.php (This file will receive array and print it)


<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
?>

How to read a file character by character in php ?

<?php

$file=fopen("filename.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);

?>

Use linkedin api to fetch contact information in php ..

First Register your domain for linkedin api .

Then get your API_KEY, API_SECRET REDIRECT_URI , SCOPE ...

Run the script .. Njoy :)
------------------------------------------------------------------------------------------------------------------------
<?php

// Change these
define('API_KEY',      ' '          );  /*put API_KEY between '  ' */
define('API_SECRET',   ' '      ); /*put between API_SECRET '  '*/
define('REDIRECT_URI', ' '); /*put REDIRECT_URI between '  '*/
define('SCOPE',        ' '     ); /*put Scope between '  '*/


session_name('linkedin');
session_start();
$_SESSION['state']="India" // Name the country you live in
;
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
    // LinkedIn returned an error
    print $_GET['error'] . ': ' . $_GET['error_description'];
    exit;
} elseif (isset($_GET['code'])) {
    // User authorized your application
    if ($_SESSION['state'] == "India") {
        // Get token so you can make API calls
        getAccessToken();
    } else {
        // CSRF attack? Or did you mix up your states?
        exit;
    }
} else {
    if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
        $_SESSION = array();
    }
    if (empty($_SESSION['access_token'])) {
        // Start authorization process
        getAuthorizationCode();
    }
}

// Congratulations! You have a valid token. Now fetch your profile by defining field you wanted

$user = fetch('GET', '/v1/people/~:(id,firstName,lastName,skills,location,industry,network)');
echo "<pre>";
print_r($user);
echo "<pre>";
exit;

function getAuthorizationCode() {
    $params = array('response_type' => 'code',
                    'client_id' => API_KEY,
                    'scope' => SCOPE,
                    'state' => uniqid('', true), // unique long string
                    'redirect_uri' => REDIRECT_URI,
              );

    // Authentication request
    $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
   
    // Needed to identify request when it returns to us
    $_SESSION['state'] = $params['state'];

    // Redirect user to authenticate
    header("Location: $url");
    exit;
}
   
function getAccessToken() {
    $params = array('grant_type' => 'authorization_code',
                    'client_id' => API_KEY,
                    'client_secret' => API_SECRET,
                    'code' => $_GET['code'],
                    'redirect_uri' => REDIRECT_URI,
              );
   
    // Access Token request
    $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
   
    // Tell streams to make a POST request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => 'POST',
                        )
                    )
                );

    // Retrieve access token information
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    $token = json_decode($response);

    // Store access token and expiration time
    $_SESSION['access_token'] = $token->access_token; // guard this!
    $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
    $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time
   
    return true;
}

function fetch($method, $resource, $body = '') {
    $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
              );
   
    // Need to use HTTPS
    $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
    // Tell streams to make a (GET, POST, PUT, or DELETE) request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => $method,
                        )
                    )
                );


    // Hocus Pocus
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    return json_decode($response);
}

Tuesday, 20 August 2013

Recursion in php

<?php

function recursion($int){
    if($int>0){
        echo $int."</br>";
        recursion($int-1);
        echo $int."</br>"; /*values from stack*/
        }
    }
   
recursion(5);

?>

How to preview array in Php ?

Array

<?php

$arr=array(1,2,3,4,5);
echo "<pre>";
print_r($arr);
echo "</pre>";

?>

How to write your first php script ?

What you need ?

1. A server
2. A php file to be put in your www. or htdocs directory..

Phpfile

<?php

echo "My first PHP script!";
 

?>