Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, October 15, 2015

Creating content type tpl file in drupal 7

In Drupal 7, Page.tpl.php will be the default template file for whole site. In top of this, we can customize our template for different content type, individual nodes and front pages. Even we can customize the block template and views templates.

In this blog post, i am going to give you small snippet of code for creating template file depends on content type.

To create a template file for content type, First step we need to define in template.php file on hook_preprocess_page method.


After included in template.php we need to copy the page.tpl.php. Paste in same folder, rename it according to you content type.

For example:- My content type name is reviews. My file name should be page--reviews.tpl.php

In this file, you can customize your design.

Tuesday, September 22, 2015

Get node content using node_view and node_load in drupal 7

Drupal 7 has vast functions to manipulate node and its content. Here i have gave you the piece of code to get node content using node id.

Monday, September 21, 2015

How to use DOMDocument in PHP?

DOMDocument is PHP library, which will be used to read, write and manipulate XML and HTML Documents. DOM (Document Object Model) is kind of API to validate the content of XML/ HTML. DOM support different namespaces as well.
The above code is demonstrating about DOMDocument usage with sample example. The example will fetch all H2 tags from the content and will form as separate list view.

To Discard White Spaces in content

Friday, December 5, 2014

CURL error code 7 in php

Curl is one of most powerful functionality in PHP. It will allow us to communicate with external URL. To use the curl functionality in your code. We must enable PHP curl module in PHP installation.

In this post, i could like to explain about curl error code "7". There are some of the criteria to get this error.
  1. Due to wrong URL.
  2. URL might have some port on postfix.
    For Example: http://xx.xxx.xxx.xx:8080/
    Solution : To solve this issue, we must remove the port on URL.Your URL must be like http://xx.xxx.xxx.xx/

Saturday, March 22, 2014

How to setup virtual host in apache2 on ubuntu OS

Virtual host is one of the beautiful option, which is provided by web servers. I have already shared the snacks about XAMPP virtual host creating process. I believe that snacks was tasty and delightful for your coding life.

Here, i am sharing another tasty snacks about Apache2 server virtual host, which is default server of most of linux OS. In order to create virtual host in your linux machine with apache2 server. First you have to place your project folder under root directory (/var/www/).

Create virtual host file in below location with tags

Step 1 : Go to cd /etc/apache2/sites-available/

Step 2 : cp default yoursitename.com

Step 3 : Open your file with following command

sudo gedit  yoursitename.com

Paste the below code into yoursitename.com file.

<VirtualHost *:80>
    ServerAdmin test@test.com

    DocumentRoot /var/www/project-directory/
    ServerName yoursitename.com    

    ServerAlias www.yoursitename.com    
    ErrorLog /var/log/apache2/yoursitename.com-error_log
    CustomLog /var/log/apache2/yoursitename.com-access_log common
</VirtualHost>


Save and close the file.

Step 4 : Enable the site for local server

sudo a2ensite yoursitename.com

Step 5 : Finally add to hosts file.

sudo gedit /etc/hosts

Add below line into hosts file.

127.0.0.1   yoursitename.com

Now you can go to browser and type http://yoursitename.com.

Thursday, January 9, 2014

Call content type form in custom module with Drupal 7

Here we have realtime syntax to call content type form in drupal 7. It will allow you to call add form of particular content type.

To use this code, please add some custom module with menu hook. For menu hook, Have the callback function with below code. You will get the form to submit your values.

Wednesday, December 25, 2013

Enable default token values in drupal 7

To enable the default token to be display in the drupal site. We have to install separate module to do the same. This module will allow the content type field to enable and replace with particular token.

You download the module here.

Steps to install

  1. Download the module from this location and extract it.
  2. Extract folder should be placed in /sites/all/modules folder.
  3. Then, Login as administrator in site.
  4. In admin menu, Please click on module menu.
  5. In the list modules, You will able to see the "Field default token".
  6. Please check the checkbox, which is row of same module.
  7. Then, scroll down and click "Save Configurations".
Now, you module will start to work on the same. Please give some default token in text field of content type and check.

Thursday, May 9, 2013

Data Encapsulation in PHP

Data Encapsulation is "Encapsulation is a way of storing an object or data as a property within another object, so that the outer object has full control over what how the internal data or object can be accessed."

data_encapsulation.php

Tuesday, May 7, 2013

QR Code generation in php

QR code generating in PHP, that can be used to generate QR Code images using Google Chart API. It was build using Google Chart API Web server to request the generation of a PNG image that represents the QR code graphic for a given information snippet. Currently the class can request the generation of QR codes for information snippets of the following types: bookmark, text, SMS message, phone number, contact information, e-mail message, geo-location, WIFI access, i-appli metadata, or abitrary content-type. The generated QR code image can be returned as a string, served for download, or returned as a URL string.

QRCodeClass.php


Test.php

Tuesday, April 23, 2013

Soap using PHP CURL

SOAP Stands SIMPLE OBJECT ACCESS PROTOCOL. Soap is most powerful and secure web service architecture. Soap will have two way communication between different request and responses.
It is more secure compare with REST. It has own set of properties to implement the structure of protocol.

The below code is for SOAP connection using PHP CURL.

soap_client.php



soap_request.php


Tuesday, April 9, 2013

Image resizing in PHP

The post is about image resize using php methods. This will help us to make the image as thumb size on run time. For this method, we need to pass six parameters file, photo_dir (Image directory), thumbs_dir (New image directory), square_size (Optional, by default we mentioned 140px), img_height (Optional, by default we mentioned 140px), img_width (Optional, by default we mentioned 128px).

Monday, April 8, 2013

Create a block using custom module in drupal 7

In this post, we will discuss about creating block using custom module in drupal 7. The main benefit of build a block using custom module is connectable module. This code will act as separate connectable component.

In Drupal 6, there is only one hook used for all block operations but now in Drupal 7 there are different functions for different operations of the blocks. This are the hook method provided by drupal 7 for build a block.

hook_block_info()
hook_block_configure()
hook_block_save()
hook_block_view()
hook_block_list_alter()
hook_block_view_alter()
hook_block_info_alter()
hook_block_view_MODULE_DELTA_alter()

Here we will discuss through different steps.

Step : 1
We need to create a directory in this path "sites/all/modules". i.e you need to create a new module folder inside drupal directory. Directory name must under-stable and meaningful related to your module purpose. I will named as "customblockmodule" for module directory.

We should have this two files inside directory.
1. customblockmodule.info
2. customblockmodule.module

Step : 2
Now we have to write a content for customblockmodule.info file.
Here we have mentioned name,description,core and package. Core  will have the drupal version for this module and package will define the area of module to be placed in module section.

Step : 3
In this module file, First we have to mention about info method

hook_block_info()  : This is used to tell Drupal about the new block or blocks that we will create. Drupal will display the block in the block list in the admin.

An implementation of hook_block_info() takes no arguments and is expected to return an associative array.
This defines a block named “custom_bk_module” that has two properties:

Info: This provides a description about the block. The text is used on block list in admin.
Cache: This tells Drupal how to cache the data from this block. In above example, I mentioned DRUPAL_NO_CACHE which tells Drupal not to cache the block.


hook_block_view() : Will demonstrate about view of the block. It will hold the content of the block. When page requesting to view a block, this method will get called.

Sunday, October 28, 2012

Android Push notification using php


Android push notification using php script. This code will act as web service for the android developers make the app to send push notifications. Before using this code, You have to create a project in google console and get the API key for authentication. Also you have send the Device Token of each mobile.
You can also get device token in with your mobile client side function. So, we you trying to execute the push notification through web service. Should be pass two parameters API Key and Device Token.

Thursday, October 11, 2012

Image editing and saving using canvas in HTML5 with PHP

This document will demonstrate use of canvas for editing image and also we can get as download.
Index.html


Script.js


Save.php


Download.php

Thursday, June 7, 2012

Export HTML to .CSV in PHP

This script will help you to export HTML content to *.CSV. PHP is one of most powerfull scripting language in Open source. This script was build through PHP script.

We split across three files to achieve this functionality.
  1. CSS file [To make desgin of HTML table].
  2. PHP file which will list out the DB data from Mysql to PHP.
  3. Another PHP file. Which will help you generate *.CSV file.
style.css



table.php



export.php



Monday, May 14, 2012

Import .CSV file in PHP

This code will help you to import the .CSV file data into Database. This code was build in PHP. It is generic class which can use into different purpose.

Db.php
$con = mysql_connect("hostname","username","password");
mysql_select_db("dbname",$con);

Import.php
include('db.php');
class ImportComponent
{
    
    function array_remove_empty($arr){
 $narr = array();
 while(list($key, $val) = each($arr)){
     if (is_array($val)){
  $val = array_remove_empty($val);
  // does the result array contain anything?
  if (count($val)!=0){
      // yes :-)
      $narr[$key] = $val;
  }
     }
     else {
  if (trim($val) != ""){
      $narr[$key] = $val;
  }
     }
 }
 unset($arr);
 return $narr;
    }

   
    function import($file,$uid,$table){
 $row = 1;
 $status = "";
 if (($handle = fopen($file, "r")) !== FALSE) {
 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
     if($row == 1){
  foreach ($data as &$datavalue) {
  $result=$result.$datavalue.",";
  }
  $result = substr($result, 0, -1);
  
  if(strpos($result,'"') == true){
      $splitdata = split('"',$result);
      $splitdata = str_ireplace("'",'',$splitdata);
  }
  else{
      $splitdata = split("'",$splitdata);
  $splitdata = str_ireplace('"','',$splitdata);
  $dataval = $this->array_remove_empty($splitdata);
  $result = "";
  foreach ($dataval as &$datavalue) {
  $result=$result.$datavalue.",";
  }
  $result = substr($result, 0, -1);
  }
  $num = count($data);
  $row++;
  $valueresult = "";
  $datavalue = "";
  for ($c=0; $c < $num; $c++) {
     if($row > 2){
      $datavalue = $data[$c];
      $valueresult=$valueresult."'".$datavalue;
      $datavalueofsecrec = split('"',$valueresult);
      $datavalueofsecrec = str_ireplace("'",'',$datavalueofsecrec);
      $datavalueofsecrec = $this->array_remove_empty($datavalueofsecrec);
      $valueresult = "";
      foreach ($datavalueofsecrec as $finalval) {
   $valueresult=$valueresult."'".$finalval."',";
      }
      }
  }
  if($row > 2){     
      $query = "insert into $table($result) values($valueresult)";
      $status =  mysql_query($query);
  }
     }
 fclose($handle);
 }
 if($status)
 {
     return "Success";
 }
 else
 {
     echo "failed";
 }
    }
}

Form.php
include('import.php')
$obj = new Import();
 if($_FILES){
    $uploaddir = 'Directory path';
    $filename = $_FILES['file']['name'];
    $filesize = $_FILES['file']['size'];
    $tmpname_file = $_FILES['file']['tmp_name'];
    if($filesize > '1000000') {
    echo "Way too big!!";
    } else {
    move_uploaded_file($tmpname_file, "$uploaddir$filename");
         $status = $obj->import("$uploaddir$filename",$userid(Optional),$tablename);        
    }
 }

Tuesday, January 31, 2012

Load different image on page refresh in PHP

In PHP, We can have multiple image can be show on page refresh. ALL the images should have same format.

Thursday, January 5, 2012

Creating Dynamic PDF files using HTML and PHP


There always arise a need for converting content from one file format to another one. Some may need to convert some text into HTML and some may need to convert some HTML content to an image format. The main reason for the need to convert from one file format to another is because the target file format is best suited for targeted medium where the content need to be displayed. The targeted medium may be an email, a printed hard copy or a web browser. The text format is best suited for sending emails, as the possibility of the email contents getting corrupted in the transition is much lesser, when compared to the HTML formatted emails. PDF document or a word document would be the best choice for taking a printed hard copy and obviously HTML is best for showing contents in web browsers.

Here, we are going to study on converting HTML 2 PDF using PHP. This article is not going to explain on the main logic of how to convert a HTML file to PDF file. That would be a separate subject and it could not be covered in this short article. But we would be seeing how to use some free open source PHP scripts to accomplish this file conversion.

The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.

require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();


 To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:

$pdf=new FPDF('P','mm','A4');

It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).
Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().
To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:

$pdf->SetFont('Arial','B',16);

We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:

$pdf->Cell(40,10,'Hello World !',1);

Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.
There are lot more functions in FPDF and we cannot cover all those in this article.
To learn FPDF, please browse http://www.fpdf.org.

Tuesday, January 3, 2012

Autocompletion with Scriptaculous and Ajax


This tutorial supercedes my previous turtorial on autocompletion by adding further tips and tricks to make your autocompletion a much better experience for your site users The tutorial is structured in the following way:
  1. Introduction: What is autocompletion and why use it?
  2. How it works.
  3. Getting scriptaculous and building the form.
  4. Building the autocomplete server.
  5. Passing back an id to our form.

1. What is autocompletion and why use it?

I predict that most people will want to skip this section and get straight to the action, so I will keep it brief. Autocompletion is a means of helping your users when filling in forms. The most common application of autocomplete is found in your web browser’s address bar; as you type the bar makes suggestions of URLs based on previous pages visited. In our example we will query a database of musical artists and give our users suggestions as they type in an artist name field.

2. How it works.

As a user types in a specific input field on a form, on each key up event, we use JavaScript to call a script in the background using Ajax (XMLHttpRequest) features built into the Scriptaculous library. Our form will pass the currently typed text to this script and the script will return a list of suggestions which will be dynamically placed in our page. The important thing is that our user can select one of these items by mouse-click or key-stroke to populate the form field instantly.

3. Getting scriptaculous and building the form.

This implementation of autocomplete requires 3 components:
  1. The Scriptculous libraries;
  2. An HTML form with a single field;
  3. An autocomplete server script
I use PHP as my language of choice for the autocomplete server script, but I have tried to keep this tutorial abstract enough to allow you to use your language of choice. The server script is the only thing that changes for different server-side scripting languages. Download the latest version of the Scriptaculous JavaScript Libraries and include them in the head of a new HTML document as below.

Don’t forget to change the paths to match your directory structure:

<script type="text/javascript" src="lib/prototype.js"></script>
<script type="text/javascript" src="src/scriptaculous.js"></script>


Now add a form to your HTML page’s body. In this form we are going to add a field that will take our search term (with both id and name attributes as “searchterm”) and an empty div with an id of “hint”. This empty div acts as a holder for our hints when they are generated. You should have some HTML looking like this:

<input type="text" name="searchterm" id="searchterm" />
<div id="hint"></div>


All we need now is to initiate a new call to Scriptaculous’ built in Ajax.Autocomplete method below our HTML code for the autocompleter – like this:

<script type="text/javascript">
new Ajax.Autocompleter(”searchterm”,”hint”,”server.php”);
</script>


The Ajax.Autocompleter takes 3 arguments: The element supplying the search string, the element to show suggestions in and the server script that will generate our suggestions. With that in place we can write the server script.

4. Building the autocomplete server.

The following server is written in PHP connecting to a MySQL database but you can your language of choice and even a flat text file or XML file for the suggestion database. My database table, “Artists”, is simple – it comprises a unique id field and an artist “name”.
As the Autocompleter sends the value of a form field as a POST variable, we can use this in our server script’s query againstthe database. All we need to do is output an unordered list for the autocompleter. Scriptaculous does the leg work of inserting the latest list into our hint box everytime the user makes a keystroke. Here is my server code in PHP

<?
// don't forget your database connection here.
echo "<ul>";
$sql = "SELECT * FROM artists WHERE name LIKE '%" . $_POST['searchterm'] . "%'";
$rs = mysql_query($sql);
while($data = mysql_fetch_assoc($rs)) {
echo "<li id=\"" . $data['id'] . "\">" . $data['name'] . "</li>";
}
echo "</ul>";
?>


Note that I have given each list item an id that is the same as that of the record. We will use this shortly for a more advanced technique. But for now we have all we need for a basic autocompleter.

5. Passing back an id to our form

Once a user has selected an item from the autocompleter, the string is entered into the textfield. Often, for the sake of efficiency and accuracy it is better to deal with the id of the item than the string name when it is passed on to the next page. To do this we can use some extra functionality of Ajax.Autocompleter along with some JavaScript that will pass the id to a hidden field in our form.

The first thing we need to add to our form is a hidden field with an id that we can reference:

<input type="hidden" id="artist_id" name="artist_id" />

Now we can use an extra piece of functionality built into Ajax.Autocompleter that allows us to pick up the id that we included in our list item from the server script. This is an extra option on our autocompleter call:

new Ajax.Autocompleter(”searchterm”,”hint”,”server.php”, {afterUpdateElement : getSelectedId});

We are telling our autocompleter to run a function called getSelectedId when an item is selected. All we need to do now is write this function to get the id and inject it into our hidden field. Insert the function below the

function getSelectedId(text, li) {
$('searchterm').value=li.id;
}


And that’s all there is to it. Of course you can be as clever as you want with your autocomplete server script. Try using the LIMIT clause in your SQL to make it run faster. Make your queries more advanced to bring back more specific results. And don’t forget the fun you can have with CSS on your hint div and the list of suggestions that it displays. If you have any implementations of autocompletion using this tutorial, please post them in the comments here.