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

Friday, November 30, 2012

Number of Users Online script in PHP

Sometime our clients demand for showing how many visitors are online currently on their website. This can be done by many ways. I am going to illustrate two methods of doing this. One is file based and other one is database based. Let us see how to achieve this by both methods one by one.

1) File Based Method:

In this method PHP script writes online visitors information in a text file. That text file is updated after a specific interval of time and script reads that file and show a counter of online visitors where required. Let us see the details of this method step by step,

Step 1) First of all you have to create a .txt file and place it on any folder in your server. In my case I am creating this file on root folder of my website and naming it ip.txt. After updating this file by code, it looks something like this,

127.0.0.1****1354262381++++
127.0.0.1****1354262381++++
127.0.0.1****1354262381++++

Step 2):Then copy and paste the code below where you want to show that counter,

<php
    $url = $_SERVER['SCRIPT_FILENAME'];
    $pp = strrpos($url,"/");
    $url = substr($url,0,$pp);
    $ura = $_SERVER['SCRIPT_NAME'];
    $host = $_SERVER['SERVER_NAME'];
    $ser = "http://$host";
    $ura= $ser.$ura; 
    $pp1 = strrpos($ura,"/");
    $ura = substr($ura,0,$pp1);
    $url1=explode('/', $url);
    $url=array_pop($url1);
    $url1=implode('/', $url1);
    $ura1=explode('/', $ura);
    $ura=array_pop($ura1);
    $ura1=implode('/', $ura1);

    $hm = "$url1"; 
    $hm2 = "$ura1"; 
    include "onlinevisitors.php";
?>


Step 3):  Next step is to create a file named onlinevisitors.php file and place in the folder where you included it in above code. In our case root folder,


<?php
$rip = $_SERVER['REMOTE_ADDR'];
$sd  = time();
$count = 1;

$file1 = "ip.txt";
$lines = file($file1);
$line2 = "";

foreach ($lines as $line_num => $line)
{
 //echo $line."";
 $fp = strpos($line,'****');
 $nam = substr($line,0,$fp);
 $sp = strpos($line,'++++');
 $val = substr($line,$fp+4,$sp-($fp+4));
 $diff = $sd-$val;
 if($diff < 300 && $nam != $rip)
 {
  $count = $count+1;
  $line2 = $line2.$line;
  //echo $line2;
 }
}

$my = $rip."****".$sd."++++\n";
$open1 = fopen($file1, "w");
fwrite($open1,"$line2");
fwrite($open1,"$my");
fclose($open1);

echo "<table width=180 height=30 bgcolor=#fdfdfd style=\"border: 1px green solid;\"><tr><td align=left valign=top>";
echo "</td><td align=center>";
echo "<span style=\"font-family: verdana,arial,helvetica; font-size: 11px; font-weight: bold; color: #aaccaa;\">";
echo "Total users online - <font color=red>$count</font></span><br>";
echo "</td></tr></table>";
?>

2) Database Driven Method:

comming soon...

Wednesday, November 14, 2012

Which Web Programming language to learn to keep you employed?

There are thousands of programming languages out there and have their own value over one and other. But there are a few programming languages which can keep you employed and you don't have to worry about earnings. Learning a right programming language on right time and right place is very necessary for your carrier. There are many examples out there who are not happy with their field and struggling in the market due to this fact. That's why I am going to share with my blog readers about the best programming languages and their scope in different areas of the world.
  • PHP
  • MySQL
  • Javascript
  • Perl
  • Ruby
  • Python
  • ASP.net

Thursday, June 14, 2012

Email validation using PHP and REGULAR EXPRESSION

Form validation is a very important part of web programming. This is to avoid any mistakenly adding data in database. Validating emails can be done in many ways. But the most faster and efficient way to validate emails is using regular expression.

Here is the code of this validation in PHP.

if(isset($todo) and $todo=="test")
{  
    if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){  
      echo "<center>Invalid email</center>";  
    }else{  
     echo "<center>Valid Email</center>";
    }  
}   

Friday, May 25, 2012

How to download and unzip a .ZIP file using php

Today I was working on a website which will be an affiliate member of another big company with already running a very good website ( i don't want to mention the name of that affiliate program because with this my idea is some how disclosed to the public and i don't want to do so :) ). In that affiliate program I have to download the feeds in .zip form and then importing that in my database. So I needed a script to automatically download, unzip and then import that data in my database. By using my experience and skills and also with the help of Google, I have successfully written a script for this purpose. In this post I am going to share the same,

First part of my script checks that php zip extension is loaded or not.
 if (!extension_loaded('zip')) {  
                dl('zip.so');  
           }  
After that, mention the path of download file and destination folder and rest of the script is as follows,
 $target_url = "http://www.example.com/test.zip";  
 $userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';  
 $file_zip = "downloads/new.zip";  
 $file_txt = "downloads/".md5(time())."new.txt";  
 echo "<br>Starting<br>Target_url: $target_url";  
 echo "<br>Headers stripped out";  
 // make the cURL request to $target_url  
 $ch = curl_init();  
 $fp = fopen("$file_zip", "w");  
 curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);  
 curl_setopt($ch, CURLOPT_URL,$target_url);  
 curl_setopt($ch, CURLOPT_FAILONERROR, true);  
 curl_setopt($ch, CURLOPT_HEADER,0);  
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  
 curl_setopt($ch, CURLOPT_AUTOREFERER, true);  
 curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);  
 curl_setopt($ch, CURLOPT_TIMEOUT, 10);  
 curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
 curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);   
 curl_setopt($ch, CURLOPT_FILE, $fp);  
 $page = curl_exec($ch);  
 if (!$page) {  
   echo "<br />cURL error number:" .curl_errno($ch);  
   echo "<br />cURL error:" . curl_error($ch);  
   exit;  
 }  
 curl_close($ch);  
 echo "<br>Downloaded file: $target_url";  
 echo "<br>Saved as file: $file_zip";  
 echo "<br>About to unzip ...";  
 // Un zip the file  
 $zip = new ZipArchive;  
   if (! $zip) {  
     echo "<br>Could not make ZipArchive object.";  
     exit;  
   }  
   if($zip->open("$file_zip") != "true") {  
       echo "<br>Could not open $file_zip";  
         }  
   $zip->extractTo("$file_txt");  
   $zip->close();  
 echo "<br>Unzipped file to: $file_txt<br><br>";  
If you like this script, so please post your comments and feedback. Your good feedback is the main desire of me to continue writing useful posts for my blog reader. Thanks

Friday, May 18, 2012

How to change "font-family" in dompdf script

In latest web development industry document conversion from one format to other format is very important. Sometimes we need to generate spread sheet files, some times we need to generate word files and some times PDF files. In this topic I will be talking about PDF file conversion.

For generating PDF files from the given data, there are a number of scripts and modules written in php and different languages. DomPDF is one of them written in php. DomPDF is fabulous in its features. It allows direct conversion of HTML files to PDF files. But there are some limitations like some times it never generates the exact copy of that HTML. Some times font-family doesn't apply correctly as we apply in HTML file. I had the same problem last days when I was using DomPDF for my PDF generation. I goggled the web and found some solutions. And on the basis of those many solutions and posts, I wrote a summarized article focusing on this problem.

It need some simple steps to follow,

  1. Download archive from approved answer. Extract files /dompdf/lib/fonts/times*.*.
  2. Copy them in your dompdf fonts folder.
  3. Edit dompdf_font_family_cache.dist.php with snippet 1.
  4. In CSS use font-family: times;.

Snippet 1:

 /* ... */  
 'times' => array (  
   'normal' => DOMPDF_FONT_DIR . 'times',  
   'bold' => DOMPDF_FONT_DIR . 'timesbd',  
   'italic' => DOMPDF_FONT_DIR . 'timesi',  
   'bold_italic' => DOMPDF_FONT_DIR . 'timesbi'  
 ),  
 'times-roman' => array (  
   'normal' => DOMPDF_FONT_DIR . 'times',  
   'bold' => DOMPDF_FONT_DIR . 'timesbd',  
   'italic' => DOMPDF_FONT_DIR . 'timesi',  
   'bold_italic' => DOMPDF_FONT_DIR . 'timesbi'  
 ),  
 /* ... */  

If you want to use your own TTF font (say, Arial.ttf):
  1. Run: ttf2afm -o Arial.afm Arial.ttf. (I did it in Ubuntu.)
  2. Run: ttf2ufm -a -F Arial.ttf. (you can use /dompdf/lib/ttf2ufm/bin/ttf2ufm.exe.)
  3. Copy Arial.* files in /dompdf/lib/fonts/.
  4. Add to dompdf_font_family_cache.dist.php snippet 2.
  5. In CSS use font-family: arial;.

Snippet 2:

 /* ... */  
 'arial' => array (  
   'normal' => DOMPDF_FONT_DIR . 'Arial',  
   'bold' => DOMPDF_FONT_DIR . 'Arial',  
   'italic' => DOMPDF_FONT_DIR . 'Arial',  
   'bold_italic' => DOMPDF_FONT_DIR . 'Arial'  
 )  
 /* ... */  

 Please feel free to post you comments and suggestions.

Thanks
 

Thursday, May 3, 2012

Working with arrays in pyrocms plugins

Hi guys, I am writing this post for one of my cool blog reader. He posted a comment that how we can return arrays from plugins to plugin view files and then how we can loop through and display the values of that array.

Pyrocms is very cool in handling this type of thing because it has a very strong template engine already built-in its codeignitor package. In order to explain how to use array in pyrocms plugin, i will take the same "example" plugin which I explained in this post http://our-knowledge-base.blogspot.com/2012/04/how-to-develop-custom-plugin-in-pyrocms.html.

Adding another function:

Open "example" plugin code and put the following function some where in that class.
 <?php  
 public function myposts()  
 {  
           $plugin_data = array();  
           $plugin_data[] = array(  
                                    'value'          => "Post # 1 value",  
                                    'title'          => 'Post # 1 title'  
                               );  
           $plugin_data[] = array(  
                                    'value'          => "Post # 2 value",  
                                    'title'          => 'Post # 2 title'  
                               );  
           $plugin_data[] = array(  
                                    'value'          => "Post # 3 value",  
                                    'title'          => 'Post # 3 title'  
                               );  
           return $plugin_data;  
      }  
 ?>  

so after adding this function whole plugin code will look like this,
1:  <?php defined('BASEPATH') OR exit('No direct script access allowed');  
2:  /**  
3:   * Example Plugin  
4:   *  
5:   * Quick plugin to demonstrate how things work  
6:   *  
7:   * @package          PyroCMS  
8:   * @author          PyroCMS Dev Team  
9:   * @copyright     Copyright (c) 2009 - 2010, PyroCMS  
10:   *  
11:   */  
12:  class Plugin_Example extends Plugin  
13:  {  
14:       /**  
15:        * Hello  
16:        *  
17:        * Usage:  
18:        * {{ example:hello }}  
19:        *  
20:        * @param     array  
21:        * @return     array  
22:        */  
23:       function hello()  
24:       {  
25:            $name = $this->attribute('name', 'World');  
26:            return 'Hello '.$name.'!';  
27:       }  
28:   
29:  
30:
31:   public function myposts()  
32:   {  
33:         $plugin_data = array();  
34:         $plugin_data[] = array(  
35:                                    'value'          => "Post # 1 value",  
36:                                    'title'          => 'Post # 1 title'  
37:                               );  
38:         $plugin_data[] = array(  
39:                                    'value'          => "Post # 2 value",  
40:                                    'title'          => 'Post # 2 title'  
41:                               );  
42:         $plugin_data[] = array(  
43:                                    'value'          => "Post # 3 value",  
44:                                    'title'          => 'Post # 3 title'  
45:                               );  
46:          return $plugin_data;  
47:      }  
48:  }  
49:  /* End of file example.php */

How to use this?
Using this is very simple. You just have to paste following code in view file. It will show post titles in the form of a list.
 {{ example:myposts }}  
     <strong>{{ name }}:</strong> {{ value }}<br />  
 {{ /example:myposts }}  

Although this is a very simple explanation of how to handle arrays in pyrocms, but after ready and understanding this example, you can easily modify this or even can develop your own complex plugin.

Please feel to post comments on this.

Thanks

Monday, April 30, 2012

Downloading a file forcibly using php


This is a very important and useful topic and we programmers normally need this kind of script in our websites etc. I wrote this scripts and now I am going to share you this to my blog readers.

The idea behind this is to use php header parameters to do this. Whenever you try to open some file which browser cant open (files like .doc, .docx etc ) itself, browser prompts you a download window and will ask you to download the file. This thing is done automatically by browser for some file formats. But what will happen when you open a .html, or .php file using a url? The answer to this is that browser will open or try to run these files in the browser window. But if you want to just download the files and not to open them in browser, then you have to tell php that download these files. This can be done by using some php header settings. The class that I am using for this thing is shown below.

 <?php  
 session_start();  
 $path="";  
 $filename = $path.$_GET['file'];  
 // required for IE, otherwise Content-disposition is ignored  
 if(ini_get('zlib.output_compression'))  
  ini_set('zlib.output_compression', 'Off');  
 // addition by Jorg Weske  
 $file_extension = strtolower(substr(strrchr($filename,"."),1));  
 if( $filename == "" )   
 {  
  echo "<html><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";  
  exit;  
 } elseif ( ! file_exists( $filename ) )   
 {  
  echo "<html><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";  
  exit;  
 };  
 switch( $file_extension )  
 {  
  case "pdf": $ctype="application/pdf"; break;  
  case "exe": $ctype="application/octet-stream"; break;  
  case "zip": $ctype="application/zip"; break;  
  case "doc": $ctype="application/msword"; break;  
  case "docx": $ctype="application/msword"; break;  
  case "xls": $ctype="application/vnd.ms-excel"; break;  
  case "xlsx": $ctype="application/vnd.ms-excel"; break;  
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;  
  case "pptx": $ctype="application/vnd.ms-powerpoint"; break;  
  case "gif": $ctype="image/gif"; break;  
  case "png": $ctype="image/png"; break;  
  case "jpeg":  
  case "jpg": $ctype="image/jpg"; break;  
  default: $ctype="application/force-download";  
 }  
 header("Pragma: public"); // required  
 header("Expires: 0");  
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  
 header("Cache-Control: private",false); // required for certain browsers   
 header("Content-Type: $ctype");  
 // change, added quotes to allow spaces in filenames, by Rajkumar Singh  
 header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );  
 header("Content-Transfer-Encoding: binary");  
 header("Content-Length: ".filesize($filename));  
 readfile("$filename");  
 exit();  
 ?>  

you can download this script using this url
http://dl.dropbox.com/u/37908711/public_scripts/php_downloadfile.rar

Sunday, April 29, 2012

How to search within a defined radius using MySql and PHP

Hey guys, today my manager assigned me a task to search property listing withing a specific radius like within 10 km or 10 miles. I did it very easily because I have done this already in one of my project. But first time this task was very hard to do and I did a lot of research and goggled the internet to find out the solution. Well that is an old and long story. Today after doing my task I thought why not I post my work in the form of an article on my blog. So here is the article...