PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: 2015

29 Dec 2015

Drupal 7 - Add custom fields to Search API solr index

     This is blog describes about how to add custom field to Search API solr index in Drupal 7.

     Suppose we need a new field, we can add new fields for a content type at /admin/structure/content/types. Then all fields are showed at /admin/config/search/search_api/index/default_node_index/fields. Now you can add desired fields to solr index.

     Suppose you want to show custom field to Search API results but that field is not created for any specific content types. Is it possible in Search API? Yes you can done this with use of hook_entity_property_info_alter().

/**
 * Implement phponwebsites_get_nodecountviews_nid()
 *
 * Return count of views by particular nid
 */
function phponwebsites_get_nodecountviews_nid($nid) {
  $result = db_query("SELECT COUNT(*) as count FROM {nodeviewcount} WHERE nid=:nid", array(':nid' => $nid))->FetchAssoc();
  return $result['count'];
}

/**
 * Implements hook_entity_property_info_alter().
 */
function phponwebsites_entity_property_info_alter(&$info) {
  $info['node']['properties']['is_nodeviewcount'] = array(
    'type' => 'integer',
    'label' => t('Node view count'),
    'description' => t("Number of views."),
    'sanitized' => TRUE,
    'getter callback' => 'phponwebsites_get_is_nodeviewcount_callback',
  );
}

/**
 * Implement phponwebsites_get_is_nodeviewcount_callback()
 */
function phponwebsites_get_is_nodeviewcount_callback($item) {
  $count = phponwebsites_get_nodecountviews_nid($item->nid);
  $total = (int) $count;
  return $total;
}

          After added above code into your custom module, go to /admin/config/search/search_api/index/default_node_index/fields. Now you could see new custom field is displayed as in below images.


Add custom fields to search API solr index in Drupal 7


         Now you can add your custom field into search api solr index and index that field. The custom field is listed in views add field section. Now you can add custom field into search results.

22 Dec 2015

Drupal 7 - Create menu tab programmatically

    This blog describes about how to create menu tab programmatically in drupal 7. We can create menu items using hook_menu().

Create menu tab programmatically

Menu tab creation in Drupal 7:


     Consider below code snippet to create menu tab in drupal 7.

/**
 * Implement hook_menu()
 */
function phponwebsites_menu() {

  $items['test'] = array(
    'title' => t('Create Menu Tab'),
    'page callback' => 'testpage_tab1',
    'access callback' => TRUE,
  );

  $items['test/tab1'] = array(
    'title' => t('First Tab'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'testpage_tab1',
    'access callback' => TRUE,
  );

  $items['test/tab2'] = array(
    'title' => t('Second Tab'),
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'testpage_tab2',
    'access callback' => TRUE,
  );

  $items['test/tab3'] = array(
    'title' => t('Third Tab'),
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'testpage_tab3',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Implement testpage_tab1()
 */
function testpage_tab1() {
  $str = t('Hi this is first tab');
  return $str;
}

/**
 * Implement testpage_tab2()
 */
function testpage_tab2() {
  $str = t('Hi this is second tab');
  return $str;
}

/**
 * Implement testpage_tab3()
 */
function testpage_tab3() {
  $str = t('Hi this is third tab');
  return $str;
}


Where,
   In hook_menu,
      Title – page title
      Type – type of menu item,
       MENU_CALLBACK, MENU_DEFAULT_LOCAL_TASK, MENU_LOCAL_TASK, MENU_LOCAL_ACTION, MENU_NORMAL_ITEM, MENU_SUGGESTED_ITEM are types of
menu item in drupal 7.

MENU_CALLBACK – register path for a menu item
MENU_DEFAULT_LOCAL_TASK – default tab for a menu
MENU_LOCAL_TASK – additional tabs for menu
MENU_LOCAL_ACTION – actions for menu items
MENU_NORMAL_ITEM – add menu item into any menus like main_menu, user_menu
MENU_SUGGESTED_ITEM – module may suggest menu items

Page callback – callback for a menu
Access callback – who can access the page

        Now i’ve hope you should know how to create menu tab programmatically in drupal 7.

18 Dec 2015

Drupal 7 – Add class into menu item using hook_menu()

  This blog describes about how to add class into menu item that is created programmatically  using hook_menu() in drupal 7.
        We know how to add custom menu item into already created menu in drupal7. Is it possible to add class to that menu item in durpal 7? Yes you can add custom classes into menu item using hook_menu() in drupal 7.

Add class into menu item in drupal 7:

     
       Consider below program to add class into menu item in drupal 7.

/**
 * Implement hook_menu()
 */
function phponwebsites_menu() {
  $items['sample'] = array(
    'title' => t('Sample page'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'page callback' => 'samplepage',
    'access callback' => TRUE,
    'options' => array(
      'attributes' => array(
        'class' => array('drupal-menu-class')
      )
   ),
  );

  return $items;
}

/**
 * Implement samplepage()
 */
function samplepage() {
  $str = t('Hi this is sample page');
  return $str;
}

Where,
     type – MENU_NORMAL_ITEM
     menu-name – name of the menu to add new link
     options – add any attributes like class, id

You need to clear cache to see created menu items with custom class into main menu.

Add multiple classes into menu item in drupal 7:


     Similarly you can add multiple classes into menu item using hook_menu() in drupal 7. Consider below program to add multiple
classes into menu item.

function phponwebsites_menu() {
  $items['sample'] = array(
    'title' => t('Sample page'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'page callback' => 'samplepage',
    'access callback' => TRUE,
    'options' => array(
      'attributes' => array(
        'class' => array('drupal-menu-class' ,  'drupal-menu-new-class')
      )
   ),
  );

  return $items;
}

       Now i’ve hope you know how to add class programmatically to menu item using hook_menu() in drupal 7.

16 Dec 2015

Drupal 7 - add link into menu programmatically using hook_menu()


     This blog describes about how to add a new menu item into menu like main menu, user menu in drupal 7.


drupal 7 - add link into menu programmatically using hook_menu()

     
We can create a menu item using hook_menu in drupal 7. Can we add menu item into already created menu in drupal7? Yes you can add a link into menu using hook_menu().

Add new menu item into main menu in drupal 7:


       Consider below program to add new menu item into main menu in drupal 7.

/**
 * Implement hook_menu()
 */
function phponwebsites_menu() {
  $items['sample'] = array(
    'title' => t('Sample page'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'page callback' => 'samplepage',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Implement samplepage()
 */
function samplepage() {
  $str = t('Hi this is sample page');
  return $str;
}


Where,
     type – MENU_NORMAL_ITEM
     menu-name – name of the menu to add new link
  
     You need to clear cache to see created new menu item in main menu. Now i’ve hope you know how to add new link programmatically to already created menu in drupal 7.

13 Dec 2015

Get multiple selected values from drop down box using PHP

                           You can get value from selection box using $_POST['selection_box_name'] ( if form method is post) in PHP. Now the doubt is rise. How to select multiple values from drop down box and how to get multiple selected input data from drop down box in PHP. This post describes retrieve multiple selected values from drop down box using PHP.

How to select multiple values from drop down box in HTML


                           You know select single value in drop down box. Then how to select multiple values in drop down box. You have to add attribute "multiple" and set name as array in drop down box in order to select multiple values from drop down box. If you want to select more than one values in drop down box, then press "ctrl" while selecting values in drop down box. Let consider below example to make HTML formwith select multiple values in drop down box.

<!DOCTYPE html>
<html>
<body>
<form action="#" method="post">
<select name="country[]" multiple>
  <option value="USA">USA</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="Russia">Russia</option>
  <option value="Brazil">Brazil</option>
  <option value="India">India</option>
</select>
<input type="submit" name="submit">
</form>
</body>
</html>

Retrieve multiple selected values from drop down box using PHP


                                 You can get value from selection box using $_POST['selection_box_name'] ( if form method is post) in PHP. Then display each selected items through foreach loop in PHP. The PHP script describes how to select multiple selected values from drop down box.

<!DOCTYPE html>
<html>
<body>
<form action="#" method="post">
<select name="country[]" multiple>
  <option value="USA">USA</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="Russia">Russia</option>
  <option value="Brazil">Brazil</option>
  <option value="India">India</option>
</select>
<input type="submit" name="submit">
</form>
<?php
 if(isset($_POST['submit']))
 {
  $country=$_POST['country'];
  foreach($country as $val)
  {
    echo $val.'<br>';
  }
 }
?>
</body>
</html>

               
                                      While submitting form with selected multiple values from drop down box, you can get multiple selected values using PHP.

26 Aug 2015

Find prime numbers between 1 and 100 in PHP

        This blog describes how to find prime numbers between 1 and 100 using PHP. Prime number is a number which is divided by 1 and itself.  Consider the number 5. It is prime number because it can be divided by 1 and 5.

PHP program for prime numbers:


       Consider the below program which is used to find prime numbers from 1 to 100.

<?php
    for($i = 1; $i <= 100; $i++)
      $mm = 0;
      for($j = 2; $j <= $i/2; $j++) {
        //only not prime numbers
                if ($i % $j == 0) {
                  $mm++;
                  break;
                }
      }
      if ($mm == 0) {
                echo"$i is prime number<br/>";
      }
    }
  ?>

       In above program, if a number is divided by any number except 1 and itself, then it is not prime number. Otherwise it is a prime number.


PHP program for find prime numbers from a to 100


        Now you got prime numbers between 1 and 100 using PHP.
Related Post

19 Aug 2015

Find Armstrong Numbers between 1 to 1000 in PHP

            This blog describes how to find Armstrong Numbers between 1 to 1000 using PHP?. Before we are going to program part, we should know what is Armstrong Number?. So only we can write program for find Armstrong Number in any languages like C, C++, PHP.

what is Armstrong Number?


           Armstrong Number is sum of 3 power of each digits equals to given number.
For example: 
           153 is Armstrong Number.
           1^3 + 5^3 + 3 ^3
           1 + 125 + 27
           153

PHP Program to find Armstrong Numbers:


          Consider below example which is find Armstrong Numbers between 1 to 1000.

<?php
for($i = 1; $i <= 1000; $i++) {
  $sum = 0;
  $qu = $i;
  while($qu != 0) {
$remainder = $qu % 10;
$thrice = $remainder * $remainder * $remainder;
$sum += $thrice;
$qu = $qu / 10;
  }
  if ($sum == $i) {
    echo "<p>$i is armstrong number</p>";
  }
}
?>


PHP program for find Armstrong Numbers


              Now you got Armstrong Numbers between 1 to 1000.

Related Post:

13 Aug 2015

Get value from drop down box using PHP

                        The drop down box allows you to select one or more values from it. The HTML tag "select" is also known as "drop down" or "pul down" box.You can get value from drop down box using PHP while form submitting.

HTML form with drop down box


                        The below example describes how to create HTML form with drop down box.

<html>
<body>
<form action="#" method="post">
  <select name="country">
     <option value="USA">USA</option>
     <option value="United Kingdom">United Kingdom</option>
     <option value="France">France</option>
     <option value="Russia">Russia</option>
     <option value="India">India</option>
  </select>
  <input type="submit" name="submit" value="Submit">
 </form>
 </body>
 </html>

Retrieve input data from drop down box using PHP


                       You can retrieve input data from drop down box using following types in PHP.
             $_POST['drop_down_name'] (if method is post)
             $_GET['drop_down_name'] (if method is gett)
             $_REQUEST['drop_down_name'] (if method is either post or get)
                         The following PHP script describes how to retrieve input data from drop down box while form submitting.

<html>
<body>
<form action="#" method="post">
   <select name="country">
      <option value="USA">USA</option>
      <option value="United Kingdom">United Kingdom</option>
      <option value="France">France</option>
      <option value="Russia">Russia</option>
      <option value="India">India</option>
   </select>
   <input type="submit" name="submit" value="Submit">
</form>
<?php
      if(isset($_POST['submit']))
      {
         $country=$_POST['country'];
         echo'You selected '.$country;
       }
?>
</body>
</html>

                             While submitting form with select country from drop down box, you can get selected country as output.

Related Post:

17 Jun 2015

Fibonacci series of given number in PHP

         This blog describes about how to find Fibonacci series of given number in PHP. Fibonacci series is a sequence of number generated by adding previous two numbers. If the given number is 'n', then Factorial of 'n' is defined as 'Fn'. In mathematical terms, Fibonacci series for 'n' number looks like this:

                                            Fn = Fn-1 + Fn-2;

         Where,
              F0 = 0;
              F1 = 1;

         Fibonacci series for 'n' number is calculated recursively by above formula.

Simple PHP program Fibonacci series:


         This is the simple PHP program for find Fibonacci series.


function fibonacci_series($n) {
  $f1 = -1;
  $f2 = 1;

  for ($i = 1; $i <= $n; $i++) {
    $f = $f1 + $f2;
    $f1 = $f2;
    $f2 = $f;
    echo "$f<br />";
  }
}

echo fibonacci_series(5);


         The above PHP program returns 0, 1, 1, 2, 3. As i said, Fibonacci series is a sequence of number generated by adding previous two numbers. In above program, we have generated Fibonacci series for 5.
We have assumed $f1 = -1; and $f2 = 1; We need to run for loop until 5.As per above program,

If $i = 1:
              $f = -1 + 1 = 0;
              $f1 = 1;
              $f2 = 0;

If $i = 2:
              $f = 1 + 0 = 1;
              $f1 = 0;
              $f2 = 1;

If $i = 3:
              $f = 0 + 1 = 1;
              $f1 = 1;
              $f2 = 1;

If $i = 4:
              $f = 1 + 1 = 2;
              $f1 = 1;
              $f2 = 2;

If $i = 5:
              $f = 1 + 2 = 3;
              $f1 = 2;
              $f2 = 3;

Fibonacci series for 'n' number in PHP:


         The below PHP program is used to find Fibonacci series of given number.


<html>
<head>
<style type="text/css">
 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
    width:510px;
 }
 #number {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
    padding: 3px 4px;
}
#submit
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
    box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
    color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;
}
</style>
</head>
<body>
<div class="contact">
  <h1>Fibonacci series in PHP</h1>
  <form action="#" method="POST">
    Enter number : <input type="text" name="number" id="number" /></br>
    <input  type="submit" name="submit" id="submit" value="Submit"></input>
  </form>

  <?php
   if(isset($_POST['submit'])) {
     $n = $_POST['number'];
   
     function fibonacci_series($a) {
       $f1 = -1;
       $f2 = 1;

       for ($i = 1; $i <= $a; $i++) {
        $f = $f1 + $f2;
        $f1 = $f2;
        $f2 = $f;
        echo "$f<br />";
       }
     }
 
    echo "Fibonacci series of $n is:<br />";
    echo fibonacci_series($n);

   }


  ?>
</div>
</body>  
</html>


          When you open above PHP file in browser, it looks like below image:


Find Fibonacci series for Given number in PHP


        If you type number 6 in textbox, it returns 0, 1, 1, 2, 3, 5. It looks like below image:


Simple Fibonacci series program in PHP


        Now you can find Fibonacci series for any number in PHP. I've hope, you got an idea for generate Fibonacci series of given number.


16 Jun 2015

Factorial of given number in PHP

        This blog describes about how to find factorial of given number in PHP. The factorial is one of the maths concept. It is multiplication of numbers from 1 to given number. If the given number defined as 'n', then 'n' factorial represented as 'n!'. The factorial formula for 'n' number looks like:

                                             n! = 1 * 2 * 3 ... n;

For example, the factorial of 5 looks like this:

                                             5! = 1 * 2 * 3 * 4* 5  = 120;

Simple PHP program for Factorial:


      Consider the below example which is the sample PHP program for find factorial of number:

function factorial($a) {
  $fact = 1;
   for($i = 1; $i <= $a; $i++) {
     $fact = $fact * $i;
   }
   return $fact;
 }
 $f = factorial(4);
 echo $f;

     Where,
           'n' is 4.
           n! = 4! = 1 * 2 * 3 * 4 = 24.

Factorial for 'n' number in PHP:


      Consider the below example which is the PHP program for find factorial of given number. For example, if you enter 4, it will return factorial of 4. Like if you enter 'n' number, it will return factorial of 'n'.


<html>
<head>
<style type="text/css">
 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
 width:520px;
 }
 #number {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
    padding: 3px 4px;
}
#submit
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
    box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
 color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;
}
</style>
</head>
<body> 
<div class="contact">
  <h1>Factorial in PHP</h1>
  <form action="#" method="POST">
    Enter number : <input type="text" name="number" id="number" /></br>
    <input  type="submit" name="submit" id="submit" value="Submit"></input>
  </form>

  <?php
   if(isset($_POST['submit'])) {
     $n = $_POST['number'];
     
     function factorial($a) {
       $fact = 1;
       for($i = 1; $i <= $a; $i++) {
         $fact = $fact * $i;
       }
       return $fact;
     }
     $f = factorial($n);
     echo "<div class=''>Factorial of $n is $f</div>";
   }
  ?>
</div>
</body>     
</html>


           When you open above program in browser, it looks like this:

Simple PHP program for Factorials


         Whatever you enter number in the textbox, it returns factorial of given number.


4 Jun 2015

Ajax upload file or image in PHP using jQuery

     You can upload files and images using PHP. Basically it can be uploaded by form submitting. For more details visit how to upload file or image using PHP. When i tried to upload images using Ajax with jQuery, i can't get it work. All of you may be face this problem. This blog describes how to upload file or image in PHP using jQuery with Ajax.

     Consider the following example for upload files using Ajax and PHP.

Html form for upload image:

   
      To upload file or image, your html form should be like below form:

<form name="multiform" id="multiform" action="#" method="POST" enctype="multipart/form-data">
    Image : <input type="file" name="file" id="file" /></br>
    <input  type="button" id="multi-post" value="Upload"></input>
</form>

      where,
          enctype="multpart/form-data  -  must be present in form. Otherwise file does not upload.
          type="file" in <input>  tag is used to take input as a file.

Ajax and jQuery for upload image:

   
     Before add Ajax code to your html file, you need to add jquery-1.7.2.min.js library file. To upload image, you have to write Ajax code like below:

$(document).ready(function(){
  $("#multiform").submit(function(e) {
    var formObj = $(this);
   
    if(window.FormData !== undefined) {
      var formData = new FormData(this);
      $.ajax({
        url: 'upload.php', //url to process the sent data
        type: 'POST',     //form type
        data:  formData, //form data to send
        mimeType:"multipart/form-data",  //type of form data
        contentType: false,  //content type of form
        cache: false,  //disable cache the request page
        processData: false,  //to send DOMDcoument or non processed data file
        success: function(data, textStatus, jqXHR) {
          $("#er").html(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          $("#er").html('textStatus=' + textStatus + ', errorThrown=' + errorThrown);
        }          
      });
   
      //reset file field after form submitted
      $('#file').val('')
      //prevent the page is refreshed
      e.preventDefault();
      //e.unbind();
    }
  });

  $("#multi-post").click(function() {
    //submit the form and send data
    $("#multiform").submit();
  });

});


      When user click the upload button, the form is submitted, ajax is called and send form data as well.

Html file with Ajax for upload image:


      We need to combine html form and ajax code to make a full html file for upload file or image. You may add some styles to html file in order to give attractive presence to users. After combined above all things, your html code should be like below one:

upload-ajax.html:

<html>
<head>
<style type="text/css">
 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
 width:520px;
 }
 #file {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
    padding: 3px 4px;
}
#multi-post
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
    box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
 color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;
}
</style>
</head>
<body> 
<script type="text/javascript" src="../test/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#multiform").submit(function(e) {
    var formObj = $(this);
   
    if(window.FormData !== undefined) {
      var formData = new FormData(this);
      $.ajax({
        url: 'upload.php',
        type: 'POST',
        data:  formData,
        mimeType:"multipart/form-data",
        contentType: false,
        cache: false,
        processData:false,
        success: function(data, textStatus, jqXHR) {
          $("#er").html('<pre><code>'+data+'</code></pre>');
        },
        error: function(jqXHR, textStatus, errorThrown) {
          $("#er").html('textStatus=' + textStatus + ', errorThrown=' + errorThrown);
        }          
      });

      $('#file').val('')
      e.preventDefault();
      //e.unbind();
    }
  });

  $("#multi-post").click(function() {
    //sending form from here
    $("#multiform").submit();
    console.log();
  });

});

</script>
<div class="contact">
  <h1>Upload files using Ajax and PHP</h1>
  <div id="er"></div>
  <form name="multiform" id="multiform" action="#" method="POST" enctype="multipart/form-data">
    Image : <input type="file" name="file" id="file" /></br>
    <input  type="button" id="multi-post" value="Upload"></input>
  </form>
</div>
</body>     
</html>

     
      When you view the upload-ajax.html in browser, it should be like below image:

How to upload images using PHP, and Ajax with jQuery

 

PHP snippet for upload file:


      When ajax is called, url which is in ajax call received form data. Then the file or image is to be uploaded using following PHP code.

upload.php:

<?php
 $file=$_FILES['file']['name'];
 if($file!='')
 {
  //upload file
  move_uploaded_file($_FILES['file']['tmp_name'],$_SERVER['DOCUMENT_ROOT'].'/test/uploaded_img/'.$file);
  //check whether file is exists or not in a folder
  if(file_exists($_SERVER['DOCUMENT_ROOT'].'/test/uploaded_img/'.$file)) {
   echo'Uploaded successfully';
  }
  else {
   echo'File is not uploaded';
  }
 }


     Where,
        move_uploaded_file() - used to upload the file
        file_exists() - used to check whether the file is already exists in a folder or not after upload the file
        $_SERVER['DOCUMENT_ROOT'] - used to represent the directory 

        Now you can add either file or image using PHP and jQuery with Ajax.


1 Jun 2015

Upload multiple files/images using PHP

                        You can upload single file and image easily in PHP. Now we are going to know how to upload multiple files and images using PHP. You can upload more than one images or files at the time using PHP. It can done using by array concepts.

Form for upload multiple images:

               
                     First you need to make form for upload more images. Your form should be like following:

<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" id="file" multiple="multiple">
<input type="file" name="file[]" id="file" multiple="multiple">
 <input type="submit" id="submit" name="submit" value="submit">
 </form>

                  You should add enctype="multipart/form-data" for upload files. You can see above where the name of file tag should be array like name="file[]" for store multiple values.

Upload multiple images using PHP:


                       Similarly upload single image, you will get image values by $_FILES['file']['name'] in PHP while submitting a form. You need temporary name of image to pass one of the parameter in move_uploaded_file() in order to upload files. If you've a single image, then you can upload easily by move_uploaded_file($_FILES['file']['tmp_name'],$name). But you need to upload multiple images. So you've to get values as an array. Then upload each image using loop. Consider the following example. Here it describes how to get temporary name of each image one by one using loop in PHP.


<?php
if(isset($_POST['submit']))
{
 $name=$_FILES['file']['name'];
 foreach($name as $val => $name1)
 {
   $file_name=$name1;
   $tmp=$_FILES['file']['tmp_name'][$val];
  move_uploaded_file($tmp,$_SERVER['DOCUMENT_ROOT'].'img/'.$file_name);
 }
}

?>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
<table>
<tr><td><input type="file" name="file[]" id="file" multiple="multiple"></td></tr>
<tr><td><input type="file" name="file[]" id="file" multiple="multiple"></td></tr>
<tr><td><input type="submit" id="submit" name="submit" value="submit"></td></tr>
</table>
</form>
</body>
</html>

             
     
     Where,
                move_uploaded_file() - to upload files to desired location.
                $_SERVER['DOCUMENT_ROOT'] gives the root directory of current script executing.
You can upload multiple files as well as images using this PHP script.

Related Posts:


13 May 2015

Get multiple values from checked checkboxes using PHP

                      Normally you can get single value from textbox, checkbox and radio buttons. Can you retrieve multiple values from selected checkbox.? Yes you can get multiple values from checked checkbox using PHP.

Get value from checked checkbox using PHP:


                         You can retrieve value from single checkbox using php and html. The following php code is used for get values from checked checkbox.

<html>
<body>
<?php
if(isset($_POST['submit']))
{
echo'You checked following value:<br>';
echo $_POST['check'];
}
else
{
?>
<form action="#" method="post">
<input type="checkbox" name="check" value="apple">apple <br>
<input type="submit" name="submit" value="submit"> <br>
</form>
<?php
}
?>
</body>
</html>


Retrieve values from multiple checked checkboxes using php:


                       If you want to get multiple values from checked checkbox, then you use name as an array for your checkbox. It should be like following.

<input type="checkbox" name="check[]" value="apple">apple
<input type="checkbox" name="check[]" value="orange">orange
<input type="checkbox" name="check[]" value="mango">mango

The following php code is used to get values from multiple checked checkbox.


<html>
<body>
<?php
if(isset($_POST['submit']))
{
echo'You checked following value(s):<br>';
 foreach($_POST['check'] as $val)
 {
 echo $val.'<br>';
 }
}
else
{
?>
<form action="#" method="post">
<input type="checkbox" name="check[]" value="apple">apple <br>
<input type="checkbox" name="check[]" value="orange">orange <br>
<input type="checkbox" name="check[]" value="mango">mango <br>
<input type="submit" name="submit" value="submit"> <br>
</form>
<?php
}
?>
</body>
</html>


     where ,
                  $_POST['check'] is used to get values from checkbox using php.
                  foreach() is used to get array values from checkbox and display them

When you run this php file, your output like as below:

get values from multiple check box

Suppose, you select check boxes like below:

get values from checked checkbox using php

You'll get output like as below

                        You checked following value(s):
                         apple
                         mango


18 Apr 2015

Create Search API like itunes Search API using PHP and MySQL

                      The Apple itunes provided a search API for retrieve app information from it. The Apple search API display result as JSON format. Do you want to know more information about Apple itunes search API, then visit iTunes Search API.

                      You can also create search API like Apple itunes search API if you know how to create JSON file using PHP. Due to this, you can provide search API for your websites. If you didn't know create JSON file using PHP and MySQL, then visit How to get output as JSON format using PHP and Mysql.

Generate Search API using PHP and MySQL


                       Lets see how to create search API using PHP.  Follow below steps to generate search API for your websites using PHP.

Step1: Connect MySQL database using PHP


                     Connect your MySQL database to get stored values from it using PHP. The PHP code for connect MySQL database is below:

 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('fitness') or die(mysql_error());


Step2: Get value from url using PHP


                     While user search something on your search API, you need to get those values for search from url. So only you can provide particular results from your MySQL database. This is done by below PHP code.

 $field=$_REQUEST['field'];
 $limit=$_REQUEST['limit'];

Step3: Make MySQL select query


                     After got values from url, you've to make MySQL query to select corresponding results from database. You can get zero or more than one values from urls for search. You should make MySQL query like below using PHP.

 if($field!='' && $limit!='')
 {
   $cond="where name='".$field."' order by id desc limit 0, $limit";
 }
 if($field=='' && $limit!='')
 {
   $cond="order by id desc limit 0, $limit";
 }
 if($field!='' && $limit=='')
 {
   $cond="where name='".$field."' order by id desc limit 0, 50";
 }
 if($field=='' && $limit=='')
 {
   $cond="order by id desc limit 0, 50";
 }
 $q=mysql_query("select * from f_img $cond") or die(mysql_error());

Step4: Add header for get output as JSON format


              You must add header type ato your PHP script for get output as JSON format. This is like below

 header('Content-Type: Application/json');

Step5: Add content to JSON file using PHP


               You need to create 2 array for create output as multidimensional array. Retrieve values from query result using mysql_fetch_arrayThen you push values to array using array_push() in PHP. Finally encode the results to display output as JSON format using json_encode().

               The full PHP code for create search API is represented below,


<?php
 error_reporting('E_ALL ^ E_NOTICE');
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('fitness') or die(mysql_error());
 $field=$_REQUEST['field'];
 $limit=$_REQUEST['limit'];
 if($field!='' && $limit!='')
 {
   $cond="where name='".$field."' order by id desc limit 0, $limit";
 }
 if($field=='' && $limit!='')
 {
   $cond="order by id desc limit 0, $limit";
 }
 if($field!='' && $limit=='')
 {
   $cond="where name='".$field."' order by id desc limit 0, 50";
 }
 if($field=='' && $limit=='')
 {
   $cond="order by id desc limit 0, 50";
 }
 $q=mysql_query("select * from user $cond") or die(mysql_error());
 header('Content-Type: Application/json');
 $details=array();
 $user=array();
 while($res=mysql_fetch_array($q))
 {
  $user['name']=$res['name'];
  $user['state']=$res['state'];
  $user['country']=$res['country'];
  array_push($details,$user);
 }
 //print_R($details);
 echo json_encode($details);

?>


           Your JSON output should be like below,


[
 {"name":"Clark","state":"California","country":"USA"},
 {"name":"Anderson","state":"Los Angeles","country":"USA"},
 {"name":"Smith","state":"London","country":"United Kingdom"},
 {"name":"Jones","state":"Cambridge","country":"United Kingdom"},
 {"name":"Nathan","state":"Franche Comte","country":"France"},
 {"name":"Marie","state":"Paris","country":"France"},
 {"name":"Nastya","state":"St Petersburg ","country":"Russia"},
 {"name":"Dima","state":"Moscow","country":"Russia"},
 {"name":"Linh","state":"Hanoi","country":"vietnam"},
 {"name":"Hoang","state":"Hai Phong","country":"vietnam"},
]

Step6 : .htaccess


                   Add following lines to your .htaccess file


RewriteRule ^search search.php [L]

                  Now you entered search on address bar, the .htaccess redirects you to search.php file. You can get search API using below url types.

                http://www.phponwebsites.com/search?field=nathan&limit=10
                http://www.phponwebsites.com/search?field=nathan
                http://www.phponwebsites.com/search?limit=10
                http://www.phponwebsites.com/search

21 Mar 2015

Get app details from Apple itunes using php

                       You can store games, music album in Apple itunes. If you want to display information of some games or music album, then you can retrieve information about apps from itunes. For retrieve app information from itunes, Apple itunes provided a search API. Do you want to know more information about Apple itunes search API, then visit iTunes Search API.
     
                       On Apple itunes search API, they show some examples for search link like https://itunes.apple.com/search?term=jack+johnson. You can see the result of search API while visiting that page.

                       The Apple Search API return results as JSON format. You need to get app data from JSON file. It is like how you retrieve data from JSON files. You can retrieve required app information from JSON file using PHP.


Retrieve app information from Apple itunes search API using PHP


                       Suppose you have games on Apple itunes storage. Then you can get app details from itunes using PHP. Due to search API, you can Game name, Game description, seller of game, game image, screenshots, game category, released date, price, version, compatibility, rating for game, game category, game url , currency and also language.

Search url in search API


                       You can't get values from search API using only "term" field in your search url.
ie,
        https://itunes.apple.com/search?term=fabsys

      where, you used only term filed to retrieve data from search API. But it didn't give any results. Just view that page on browser.

                      Instead, you have to use add field "country and entity"  . Now your search url look like this
https://itunes.apple.com/search?term=fabsys&country=us&entity=software .

                     Now view this page on your browser. You can get 50 results. This is the default limit. This is the maximum value that you can retrieved. You can also limit the values using "limit" field.

<?php
       $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2");
      $json = json_decode($content, true);
      print_R($json);
?>


Now you will get output on screen like this,


Array ( [resultCount] => 2
           [results] => Array (
   [0] => Array (
    [kind] => software
             [features] => Array ( [0] => iosUniversal )
 [supportedDevices] => Array (
                 [0] => iPhone5s
[1] => iPhone5c
[2] => iPadThirdGen4G
[3] => iPadFourthGen4G
[4] => iPhone-3GS
[5] => iPhone4
[6] => iPadMini4G
[7] => iPadWifi
[8] => iPadThirdGen
[9] => iPhone5
[10] => iPodTouchThirdGen
[11] => iPhone4S
[12] => iPadFourthGen
[13] => iPad23G
[14] => iPad3G
[15] => iPad2Wifi
[16] => iPodTouchFifthGen
[17] => iPodTouchourthGen
[18] => iPadMini
  )
[isGameCenterEnabled] => [artistViewUrl] => https://itunes.apple.com/us/artist/fabsys-technologies-private/id734671920?uo=4
[artworkUrl60] => http://a74.phobos.apple.com/us/r30/Purple4/v4/95/3b/c9/953bc9ac-a10c-1e9e-843d-87dcceb0d07a/Icon.png
[screenshotUrls] => Array (
                  [0] => http://a2.mzstatic.com/us/r30/Purple2/v4/8e/94/e2/8e94e26a-6ac1-3fb1-a4f5-0445e18d3b50/screen1136x1136.jpeg
  [1] => http://a3.mzstatic.com/us/r30/Purple/v4/c4/82/c1/c482c10f-2afd-eb68-c87f-ad2452fc1723/screen1136x1136.jpeg
  )
                 [ipadScreenshotUrls] => Array (
                  [0] => http://a1.mzstatic.com/us/r30/Purple4/v4/46/4d/eb/464deb4e-a26c-2ee8-2484-ad9743d27531/screen480x480.jpeg
  [1] => http://a3.mzstatic.com/us/r30/Purple4/v4/72/01/dd/7201dd31-ee4e-c1f0-8061-4d033d9b427b/screen480x480.jpeg
  )
[artworkUrl512] => http://a1367.phobos.apple.com/us/r30/Purple2/v4/05/73/db/0573db7e-967a-08af-5804-0ecbb38bac77/mzl.tbuwotsy.png
[artistId] => 734671920
[artistName] => Fabsys Technologies Private Limited
[price] => 0
[version] => 42.0
[description] => The worst case scenario is that you are trapped in the room full of disgusting and smelly clothes that is giving you nausea. Find a way to escape from this room before you kill yourself
[currency] => USD
[genres] => Array ( [0] => Games [1] => Puzzle )
[genreIds] => Array ( [0] => 6014 [1] => 7012 )
[releaseDate] => 2014-06-11T12:53:03Z
[sellerName] => Fabsys Technologies Private Limited
[bundleId] => com.quicksailor.EscapeUtilityRoom
[trackId] => 885565970
[trackName] => Escape Utility Room
[primaryGenreName] => Games
[primaryGenreId] => 6014
[minimumOsVersion] => 4.3
[formattedPrice] => Free
[wrapperType] => software
[trackCensoredName] => Escape Utility Room
[trackViewUrl] => https://itunes.apple.com/us/app/escape-utility-room/id885565970?mt=8&uo=4
[contentAdvisoryRating] => 4+
[artworkUrl100] => http://a1367.phobos.apple.com/us/r30/Purple2/v4/05/73/db/0573db7e-967a-08af-5804-0ecbb38bac77/mzl.tbuwotsy.png
[languageCodesISO2A] => Array ( [0] => EN )
[fileSizeBytes] => 11570404
[sellerUrl] => http://www.quicksailor.com
[averageUserRatingForCurrentVersion] => 3
[userRatingCountForCurrentVersion] => 2
[trackContentRating] => 4+
)
       [1] => Array (  )
)
)


PHP code for retrieve data from Apple itunes


<?php $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2"); $json = json_decode($content, true); //print_R($json); $count=count($json); echo'<table><th>Name</th><th>Link</th><th>Image</th><th>Description</th>'; for($i=0;$i<$count;$i++) { echo'<tr><td>'.$json['results'][$i]['trackName'].'</td>'; echo'<td>'.$json['results'][$i]['trackViewUrl'].'</td>'; $ur=$json['results'][$i]['artworkUrl512']; echo '<td><img src="'.$ur.'" width="150px"></td>'; echo'<td>'.$json['results'][$i]['description'].'</td>'; echo'</tr>'; } echo'</table>'; ?>


             Now you can get all details of app in your table. You can get any details as you want as from this PHP codes using array index represented above.

Get screenshot urls from Apple itunes using PHP


             You can get all details from itunes. You have 4 screenshot urls are avaiable in itunes for each game, 2 for screenshotUrls and another 2 for ipadScreenshotUrls. It is in array. So you want to know how to get those urls from json using PHP. The PHP script is below for that:

<?php
   $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2");
       $json = json_decode($content, true);
//print_R($json);
$count=count($json);
for($i=0;$i<$count;$i++)
{
echo $json['results'][$i]['trackName'].'<br>';
echo $json['results'][$i]['screenshotUrls'][0].'<br>';
echo $json['results'][$i]['screenshotUrls'][1].'<br>';
echo $json['results'][$i]['ipadScreenshotUrls'][0].'<br>';
echo $json['results'][$i]['ipadScreenshotUrls'][1].'<br>';
}
?>

              You display this reults on html img tag. Then you can get screenshot urls for a game. Just like below,

<img src="<?php $json['results'][$i]['screenshotUrls'][1]; ?>">


             Now you can get image from itunes,


Get app details from itunes using php

Get App rating from itunes using PHP

      
                   You can also get rating of each app from Apple itunes using PHP.


<?php
   $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2");
   $json = json_decode($content, true);
   //print_R($json);
  $count=count($json);
  echo'<table><th>Name</th><th>Rating</th>';
  for($i=0;$i<$count;$i++)
 {
    echo'<tr><td>'.$json['results'][$i]['trackName'].'</td>';
    echo'<td>'.$json['results'][$i]['trackContentRating'].'</td>';
    echo'</tr>';
 }
 echo'</table>';
?>

Retrieve images from mysql database using php

                       Already you know  how to upload images to mysql database using php. Otherwise, visit upload images to mysql database using php.

Retrieve images from database:

                        Normally you can retrieve data from mysql table using php. Then you print the result. Similarly you retrieve image name from mysql database and print image name with located folder in '<img>' tag.

Consider following mysql table.


Retrieve images from mysql database

 The php script for retrieve images from mysql database is:


<?php
        mysql_connect('localhost','root','') or die(mysql_error());
        mysql_select_db('new')  or die(mysql_error());
        $q=mysql_query("select * from image where no=1 ")  or die(mysql_error());
        $res=mysql_fetch_array($q);
?>
    <img src="<?php echo 'http://localhost/upload/image/'.$res['img_name'];?>">

   
      where,
                 mysql_query() select the row which is no '1' from mysql database.
                 mysql_fetch_array() return the result an associated array. You want to know about  mysql fetch array().
                 In your img src print image name with location of image. Now you''ll get output like this:


phponwebsites

Related Post: