• About Sarwar
  • Portfolio
  • আমার বাংলা

sarwar's weblogs

~ story of web applications…..

sarwar's weblogs

Tag Archives: PHP

jquery UI tab – ajax loading CKEDITOR in a tab and some issues

28 Thursday Jul 2011

Posted by Sarwar in Ajax, CakePHP, ckeditor, jQuery UI, PHP

≈ 42 Comments

Tags

ajax, ckeditor, Jquery UI, PHP


I tried to load CKEDITOR in a jquery tab via ajax. I got problem that only first time the ckeditor is working but when I click on other tab and again got o ckeditor tab its not working. in Load section for tab I put the following code.

load: function(event, ui) {
  if(ui.index == 3){ // Checked tab no 4
    var instance = CKEDITOR.instances['reditor']; // reditor is text area id, check if instances exists for readitor or not 
    if(instance){ 
       CKEDITOR.remove(instance); //if existed then remove it
    }
    CKEDITOR.replace( 'reditor' ); // Create instance for 'reditor'
 }
}

in this way we can get rid the problem of “CKEditor instance already exists”

Here is whole configuration

$(document).ready(function () {
           var $tabs = $("#tabs").tabs({ 
                                
                                alignment: "top",
                                spinner : false,
                                ajaxOptions: {
                                    error: function( xhr, status, index, anchor ) {
                                                    $( anchor.hash ).html( "Couldn't load this tab. Please try again.");
                                                },
                                    complete: function(){
                                        
                                        
                                    }
                                    
                                },
                                load: function(event, ui) {
                                    if(ui.index == 3){
                                        var instance = CKEDITOR.instances['reditor'];
                                        if(instance){
                                            CKEDITOR.remove(instance);
                                        }
                                    }
                                },
                                select: function(e, ui){
                                            $(ui.panel).html('<img src="img/ajax_loader.gif" />'); // Loader after click on each tab
                                        }
                                
                                });
           $tabs.tabs('select', <?=$tab_no?>); // used for selected default tab
           
        });
        

Here is HTML/PHP (I used cakephp syntax for url ) used “TEXT” in a link to show the loading text on tab otherwise it will not show the loading tabl

<div id="tabs">
    <ul>
        <li>
            <?=$html->link("<span>Information</span>", array("controller" => "listings", "action" => "information", $id), array("escape" => false, "title" => "Information"))?>
            
        </li>
        <li>
            <?=$html->link("<span>Detail</span>", array("controller" => "listings", "action" => "detail", $id), array("escape" => false))?>
        </li>
        <li>
            <?=$html->link("<span>Peoples</span>", array("controller" => "listing", "action" => "peoples", $id), array("escape" => false))?>
        </li>
        <li>
            <?=$html->link("<span>Enhance</span>", array("controller" => "listings", "action" => "enhance", $id), array("escape" => false))?>
       </li>
    </ul>
 </div>

In this way I did and it work for me 🙂

Advertisement

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

trace visitor location based on their geolocation- how to

07 Tuesday Jun 2011

Posted by Sarwar in PHP

≈ 1 Comment

Tags

block ip, find country, geo location, PHP


I tried to find out a solution how we can block or trace visitor location and based on that location we do some action

First you have to use 3rd party api to get visitor location. The following url will give you the detail.
http://ipinfodb.com/ip_location_api.php

Lets assume the visitor ip is 180.234.12.237 (you’ll get key from that website)
http://api.ipinfodb.com/v3/ip-city/?key=&ip=180.234.12.237

Its has some response format that is xml, json, raw, just you have to pass a get variable &format=json

  if (getenv(HTTP_X_FORWARDED_FOR)){
        $pipaddress = getenv(HTTP_X_FORWARDED_FOR);
        $ipaddress = getenv(REMOTE_ADDR);
        //echo "Your Proxy IPaddress is : ".$pipaddress. "(via $ipaddress)" ;
    } else {
        $ipaddress = getenv(REMOTE_ADDR);
        //echo "Your IP address is : $ipaddress";
    }     

    

$_API = "83838s88s4e0a65jhk80246d77d8s5s3988d9fb1asdkf000asd8fslasdlfasdf6s9sce";
$_URL = "http://api.ipinfodb.com/v3/ip-country/?key=$_API&ip=$ipaddress&format=json";

$data = file_get_contents($_URL);

$data = json_decode($data);
if(isset($data->statusCode) && $data->statusCode == "OK"){
    if(isset($data->countryCode) && ($data->countryCode != "USA" )) || $data->countryCode != "BD")){
        header("Location:http://www.yourdomain.com/geolocation.php");     
        exit;
    }
}

In this way we can find out the country, city, post code, time zone etc. we can block or trace visitors in our website.

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

Extract Zip File Using PHP

24 Thursday Mar 2011

Posted by Sarwar in PHP

≈ 2 Comments

Tags

PHP, unzip, zip, ziparchive


Sometime we need to extract a file on the server, say you don’t have access to shell and you want to extract a zip file, just put this to a php file and upload and run

     $zipObj = new ZipArchive;
     $file = $zipObj->open(’zip_file_name.zip’);
     if ($file == TRUE) {
         $zipObj->extractTo('extract_directory/');
         $zipObj->close();
         echo 'Unzip Successfully';
     } else {
         echo 'Failed to unzip';
     }

Its very simple and available idea everywhere, i jut wrote for note
Done!!! 🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

twitter api fetch twitter user feeds, manage and display on your website using php

18 Friday Mar 2011

Posted by Sarwar in API, PHP, Twitter

≈ 2 Comments

Tags

Fetch Data, Format Data, PHP, Retwittet, Twitter API


I know this one is old thing and helps is available but sometime we need to fetch twitter feeds Retwittet, Mentions, to our websites. Now i used json request and format the texts and print.

 function twi_fid(){
  
  ## NUMBER OF TWITTET 
  $size = 5;
  
  ## FETCH THE TWITTER TWITTET
  $twittet = file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=bdsarwar&count=$size&include_rts=t&include_entities=t");
  
  
  $data = json_decode($twittet);
  $o_text = "";
  foreach($data as $t)
  {
      $o_text = $t->text;
      
      ## MAKING URLS ENABLE TO TEXT
      $entities = $t->entities;
      
      $i = 0;
      foreach($entities->urls as $url)
      {
          $indicate = $url->indices;

          $replace[$i] = $url->url;
          $string[$i] = "<a target='_blank' href='".$url->url."'>".$url->url."</a>";

          
          $i++;
      }
      
      ## MAKING MENTIONS 
      foreach($entities->user_mentions as $mention)
      {
          $indicate = $mention->indices;
          
          $string[$i] = "<a target='_blank' href='http://www.twitter.com/".$mention->screen_name."'>".$mention->screen_name."</a>";
          $replace[$i] = $mention->screen_name;
          
          $i++;
      }
     
      for($i = 0; $i < count($string); $i++)
      {
          
          $pattarn = $replace[$i];
          $o_text = str_replace($pattarn, $string[$i], $o_text);
     
      }
      
    echo $o_text;
    echo "<br />";
    echo date("d/m/Y, H:m a", strtotime($t->created_at));
    echo "<br/> ___ <br />";

      
  }
  }
  twi_fid();

For detail parameter please visit: http://apiwiki.twitter.com/w/page/22554679/Twitter-API-Documentation
and for user timeline json visit http://dev.twitter.com/doc/get/statuses/user_timeline

Done !!

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

use PHP print_r function and return a string

07 Tuesday Dec 2010

Posted by Sarwar in Debug, PHP

≈ 1 Comment

Tags

debug, PHP, print_r, var_dump


print_r is one of the most useful feature of PHP, print_r prints a human-readable string representation of a variable. Sometime we need to get print_r value as sting to log or to combine the messages.

You can notice that print_r function have two argument first one is for string/array to be printed and another one use for whether it will print or return as string


#To have print_r return the data as a string, include the second argument "true":
$message = print_r($obj, true);

sometime you might be need to use var_export function instead of print_r

$msg = var_export($obj, true);

I use this several time while I debugging.

Happy Debugging 🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

storing array to mysql and retrieve string and use it as variable using php

07 Tuesday Dec 2010

Posted by Sarwar in PHP

≈ Leave a comment

Tags

array, PHP, serialize, store, unserialize


Sometime we need to store array to database then we need to retrieve and use as variable array. I used session variable to save data and used it later.

Its simple just use the following

#using serialize() method
$data = serialize($_SESSION);
$sql = "Insert into sessioninfo `data` values('$data')";

just run the above query and save the whole session data into a database table. You might be use any array here.

Now retrieve the data

# I assume you can retrieve the data from database and assign to the following variable
$data = unserialize($row['data']);

Now $data have the same value or nested array.

So just using serialize() and unserialize() we can do this.

Done !

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

direct to specific page instead of get variable www.domain.com/username using php and .htaccess

31 Sunday Oct 2010

Posted by Sarwar in .htaccess, PHP

≈ 5 Comments

Tags

.htaccess, PHP, url rewrite


Sometime we need to get direct access any specific page. We need a user profile page http://www.domain.com/username, but our actual url is http://www.domain.com/profile/profile.php?username=Abc

I’m trying to describe how to make the url friendly, I used .htaccess and php for rewrite the url.
.htaccess

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?uri=$1 [QSA,L]

In this case the uri took parameter after index.php file.
So if url is http://www.domain.com/username
uri will have the value uri=useranme

We need following code to retrieve the parameter.

 $_SERVER['QUERY_STRING']

I followed the following way inside index.php file to get the username

  $flag = false; 
  if(isset($_SERVER['QUERY_STRING']))
  {
      $q = $_SERVER['QUERY_STRING'];
      $data = explode("=",$q);  // Assume uri=username 
      if(isset($data[0]) && isset($data[1]) && $data[0] == 'uri')
      {
          $a = $data[1];
          $q = "SELECT * FROM user_profiles WHERE user_profile_name = '$a'";
          $cnt = mysql_num_rows(mysql_query($q));
          if($cnt > 0)
          {
             include("profile/profile.php");
             $flag = true;
          }
          
      }
      
  }
if($flag == false)
{
   include("home.php") // your index or homepage 
}

So above code I tried to find the uri and check it on database if username/profile name exists or not. If it found I include the profile page. if not then include the homepage. After including profile.php page, all variables (only above include) are available in profile.php file.

its working with me very well.

You may have better solutions. But I need it very urgent that’s why I write the code in this way. If you have better solution please share your thoughts.

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

passing get variable in cakephp pagination url

12 Tuesday Jan 2010

Posted by Sarwar in CakePHP, Framework, PHP

≈ 17 Comments

Tags

argument, CakePHP, GET, pagination, paginator, parameter passed, PHP


For searching we many need to pass variable like ?keyword=test, and we may need to add pagination withen the search, Here I describe multiple cases where we may need to use pagination and how we manage the url for pagination when we make some searching

Case 1: if the url like the following
http://www.mydomain.com/controller/method/?keyword=test1&opt=test2

In this case we need to add the paginator option like this
First we retrive the passing variable and assign value, we can get it from “$this->params[‘url’]

$urls = $this->params['url']; $getv = "";
foreach($urls as $key=>$value)
{
if($key == 'url') continue; // we need to ignor the url field
$getv .= urlencode($key)."=".urlencode($value)."&"; // making the passing parameters
}
$getv = substr_replace($getv ,"",-1); // remove the last char '&'

Now we have the all get parameter, lest assign this to paginator option

$paginator->options(array('url' => array("?"=>$getv)));

Now all the pagination links always taking this get parameter so now if we gos to the next page the url look like this
http://www.mydomain.com/controller/method/page:2?keyword=test1&opt=test2

Now If we need passing an argument as id like the following
http://www.mydomain.com/controller/method/1/?keyword=test1&opt=test2
where 1 is an id or something we get this 1 from $this->passedArgs[0] So now we have to set the paginator option like this

$paginator->options(array('url' => array($this->passedArgs[0],"?"=>$getv)));

If we have passed more than one argument, we need to take it

$pass_argument = $this->passedArgs[0]."/"$this->passedArgs[1]."/".$this->passedArgs[2]."/";
$paginator->options(array('url' => array($pass_argument,"?"=>$getv)));

It depend on you how much you want to passed the argument, if you faced any problem print the $this->passedArgs and see how it organize the argument. Its really easy and I’ve already used it. Cheers

–new update
I got the idea from comments, here is update, the following code will useful for multiple arguments or params.

//extract the get variables
$url = $this->params['url'];
unset($url['url']);
$get_var = http_build_query($url);

$arg1 = array(); $arg2 = array();
//take the named url
if(!empty($this->params['named']))
$arg1 = $this->params['named'];

//take the pass arguments
if(!empty($this->params['pass']))
$arg2 = $this->params['pass'];

//merge named and pass
$args = array_merge($arg1,$arg2);

//add get variables
$args["?"] = $get_var;

$paginator->options(array('url' => $args));

done.. But I’m trying to make better solution, will update it soon.

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

Author

  • Sarwar

Categories

  • .htaccess
  • Apache
  • API
  • CSS
  • Debug
  • Framework
    • CakePHP
  • HTML
  • JavaScript
    • Ajax
    • ckeditor
    • jquery
    • jQuery UI
    • tinymce
  • Joomla
    • Virtumart
  • Linux
  • MySQL
  • PHP
  • SVN
  • Twitter
  • WHM/cPanel
View Sarwar Hossain's profile on LinkedIn
Follow bdsarwar on Twitter

Tweets

  • RT @ESPNUK: If Erling Haaland wanted to match Cristiano Ronaldo's 700 league goals, he'd have to score 40 goals a season until the year 203…    2 months ago
  • RT @Cristiano: Great team effort and a good victory. We stand together. Let’s go, United! 💪🏽 https://t.co/GnjAR3oM3s    4 months ago
  • RT @Cristiano: Hard work always pays off 🙏🏽💪🏽 https://t.co/kMqIpB2nfV    7 months ago
  • RT @realDonaldTrump: Just finished a very good conversation with President Xi of China. Discussed in great detail the CoronaVirus that is r…    2 years ago
  • “Running a small business without a plan is a lot like driving without directions.” — @GoldmanSachs via @appexchange    6 years ago
  • RT @TechCrunch: 5K people turn up to catch Pokémon in Chicago tcrn.ch/2aaLRys https://t.co/VVQSd7nmN4    6 years ago

Flickr Photos

From Helipad ViewAbove the CloudHillNear to SkySunset Moment#sunset #beach #ocean #coxsbazar#jamroll #food #deliciousfood #homemade  #homemadefood#seaside #ocean #oceanview #travelphotography #coxsbazar #bayofbengal #travel #longestbeach#beach #lifeguard #seaside #holiday #tour #longestbeach #travel #travelphotography #coxsbazar #bayofbengal#resort #mountains
More Photos

Archives

  • February 2012 (1)
  • January 2012 (2)
  • August 2011 (1)
  • July 2011 (1)
  • June 2011 (2)
  • May 2011 (2)
  • April 2011 (1)
  • March 2011 (3)
  • December 2010 (3)
  • November 2010 (1)
  • October 2010 (4)
  • September 2010 (1)
  • June 2010 (1)
  • May 2010 (2)
  • April 2010 (1)
  • March 2010 (1)
  • January 2010 (2)
  • July 2009 (1)
  • January 2009 (1)
  • August 2008 (1)

Recent Comments

  • Kush on how to cakephp in a sub-directory, access it from root using .htaccess
  • Mr Griever on Access session data in a model -cakephp
  • apnarahimyarkhan on cakephp- CONCAT in query, Virtual Fields and make a drop down
  • Toko Kunci Pintu Murah on set & reset form text value onfocus, onblur, onclick using javascript
  • nevitaputri1.doodlekit on cakephp- CONCAT in query, Virtual Fields and make a drop down
  • RSS - Posts
  • RSS - Comments

Meta

  • Register
  • Log in
  • Entries feed
  • Comments feed
  • WordPress.com

Create a free website or blog at WordPress.com.

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Follow Following
    • sarwar's weblogs
    • Join 328 other followers
    • Already have a WordPress.com account? Log in now.
    • sarwar's weblogs
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
%d bloggers like this: