Friday, October 16, 2009

Remove empty elements from array

To remove empty elements from array

foreach($array as $key => $value) {
if($value == "") {
unset($array[$key]);
}
}
$new_array = array_values($array);

Thanks
Jawed

Friday, October 9, 2009

8 Ajax Lightbox Scripts

Hi,

At the blow link you can find 8 Ajax Light Box scripts....... ENJOY

http://webtecker.com/2008/02/26/8-ajax-lightbox-scripts/


Thanks
Jawed

Light box that also show google map in it

The below url deals with a light box that opens a google map in it.

http://www.bitethebullet.co.uk/ModalGoogleMaps/tabid/88/Default.aspx

Thanks
Jawed

Thursday, August 27, 2009

The text to be printed is contained in a div



The id of the div is passed to the function.

Click to print div 1

On clicking the link the following sequence of events happens.

1. A new window is opened
2. The contents of the div are dynamically written to the new window
3. Data is sent to the printer
4. The new window is automatically closed (IE only)

Other areas of a page can be printed simply by defining another div and link



Click to print div 2


start the javascrpt tab


close the javascrpt tab

Tuesday, August 25, 2009

Resources Libraries Helpers Plugins For Code Igniter

Here you will find a lots of libraries,helpers plugins for CI


http://codeigniter.com/wiki/Summary_of_Resources_Libraries_Helpers_Plugins.../


Thanks
Jawed

Using Zend Framework with CodeIgniter

If you ever wanted to integrate CodeIgniter and Zend Framework, you might have come across this tutorial by Daniel Vecchiato.

Whilst Daniel has done a great job demonstrating the possibility of using the two frameworks together, concerns have been made: do we actually need to use hooks?

As I understand it, hooks are used to extend the core functionalities of CodeIgniter (as explained in the user guide). Obviously Zend Framework and CodeIgniter are two different systems and there is no intention for us to extend CodeIgniter’s core functionality with Zend Framework.

Using hooks can be dangerous as it’s system-wide, and it modifies the system behaviour.

What I have done is to simply use CodeIgniter’s library structure to load the Zend Framework resources. Below is the tutorial.

Assuming you already have CodeIgniter installed. If not please refer to the user guide for installation.

1. Download Zend Framework from the official website.
2. Unzip the Zend Framework package, and copy the Zend folder (under Library) to your CodeIgniter installation’s application/libraries/. You can actually place the folder anywhere, but remember to alter the script accordingly (read the comments in the script!).
3. Place the library script (provided at the end of the post) in application/libraries/
4. Done! That’s all you need to do. Now, let us see an example of using the library.

Usage Sample


01.02.
03.class Welcome extends Controller {
04.
05. function Welcome()
06. {
07. parent::Controller();
08. }
09.
10. function index()
11. {
12. $this->load->library('zend', 'Zend/Service/Flickr');
13. // newer versions of CodeIgniter have updated its loader API slightly,
14. // we can no longer pass parameters to our library constructors
15. // therefore, we should load the library like this:
16. // $this->load->library('zend');
17. // $this->zend->load('Zend/Service/Flickr');
18.
19. $flickr = new Zend_Service_Flickr('YOUR_FLICKR_API_KEY');
20.
21. $results = $flickr->tagSearch('php');
22. foreach ($results as $result)
23. {
24. echo $result->title . '
';
25. }
26. //$this->load->view('welcome_message');
27. }
28.}
29.?>

Library Script

Copy the code and paste it to a new file called Zend.php in application/libraries/.

01.02.
03./**
04. * Zend Framework Loader
05. *
06. * Put the 'Zend' folder (unpacked from the Zend Framework package, under 'Library')
07. * in CI installation's 'application/libraries' folder
08. * You can put it elsewhere but remember to alter the script accordingly
09. *
10. * Usage:
11. * 1) $this->load->library('zend', 'Zend/Package/Name');
12. * or
13. * 2) $this->load->library('zend');
14. * then $this->zend->load('Zend/Package/Name');
15. *
16. * * the second usage is useful for autoloading the Zend Framework library
17. * * Zend/Package/Name does not need the '.php' at the end
18. */
19.class CI_Zend
20.{
21. /**
22. * Constructor
23. *
24. * @param string $class class name
25. */
26. function __construct($class = NULL)
27. {
28. // include path for Zend Framework
29. // alter it accordingly if you have put the 'Zend' folder elsewhere
30. ini_set('include_path',
31. ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');
32.
33. if ($class)
34. {
35. require_once (string) $class . EXT;
36. log_message('debug', "Zend Class $class Loaded");
37. }
38. else
39. {
40. log_message('debug', "Zend Class Initialized");
41. }
42. }
43.
44. /**
45. * Zend Class Loader
46. *
47. * @param string $class class name
48. */
49. function load($class)
50. {
51. require_once (string) $class . EXT;
52. log_message('debug', "Zend Class $class Loaded");
53. }
54.}
55.
56.?>


Happy coding! Oh and don’t forget, Zend Framework is PHP 5 only, so it won’t work on your PHP 4 installation.
Update: Using it with Kohana
Update: The following instructions are deprecated, please follow the updated one here.

Even though Kohana has the ability to load vendor classes, I still find it useful to use the library approach so that loading Zend Framework libraries will be transparent. :)

Usage is exactly the same as in CodeIgniter.

01.02.
03./**
04. * Zend Framework Loader
05. *
06. * Put the 'Zend' folder (unpacked from the Zend Framework package, under 'Library')
07. * in CI installation's 'application/libraries' folder
08. * You can put it elsewhere but remember to alter the script accordingly
09. *
10. * Usage:
11. * 1) $this->load->library('zend', 'Zend/Package/Name');
12. * or
13. * 2) $this->load->library('zend');
14. * then $this->zend->load('Zend/Package/Name');
15. *
16. * * the second usage is useful for autoloading the Zend Framework library
17. * * Zend/Package/Name does not need the '.php' at the end
18. */
19.class Zend
20.{
21. /**
22. * Constructor
23. *
24. * @param string $class class name
25. */
26. function __construct($class = NULL)
27. {
28. // include path for Zend Framework
29. // alter it accordingly if you have put the 'Zend' folder elsewhere
30. ini_set('include_path',
31. ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');
32.
33. if ($class)
34. {
35. require_once (string) $class . EXT;
36. Log::add('debug', "Zend Class $class Loaded");
37. }
38. else
39. {
40. Log::add('debug', "Zend Class Initialized");
41. }
42. }
43.
44. /**
45. * Zend Class Loader
46. *
47. * @param string $class class name
48. */
49. function load($class)
50. {
51. require_once (string) $class . EXT;
52. Log::add('debug', "Zend Class $class Loaded");
53. }
54.}
55.
56.?>

Thursday, August 13, 2009

Sending mail via Mercury on localhost using codeigniter and XAMPP

This is my first time to use Mercury on XAMPP, I never had a mail project before so I guess I'm gonna blog it for future reference. Obviously, we will be using SMTP to send mails and POP3 to receive them. Since we do not have sendmail installed in Windows XP.

Using Mercury bundled witn XAMPP is so straight forward. I am assuming you have already installed XAMPP and Mercury Mail Transport is already running. I also assume you already know how to setup a mail client (eg Outlook, Outlook Express, ThunderBird, EudoraMail are few of them). Setting up a mail client is not covered here.

Requirements:

* XAMPP - Our webserver
* Codeigniter - PHP Framework
* Mail Client - Receive mails


Now, all we need to do is Add Users for testing:
1. Open XAMPP Control Panel and Click on Start on the Mercury Section
2. Click on the Admin Button to Add Users
3. On the Mercury Menu, go to Configuration -> Manage Local Users
4. To Add an account Click on ADD
5. Add your desired test Accounts by filling in the Username, Name and Password field
6. Then click OK, then click Close




Before testing, you might want to configure codeigniter's config to store your sender accounts. To do that:
1. Navigate to your codeigniter application->config folder
2. You may create you own config file or add them in the email.php config
3. if email.php does not exist you may create one.
4. You can use the basic config for sending smtp/pop3 below:


$config['protocol'] = 'smtp';
$config['smtp_host'] = 'localhost';


5. You may add your test account so you don't have to manually type them whenever you send.Take note, I used localhost.com as my host name. Mail clients may not permit you to add an account with just localhost so adding .com, .net, .org will do the trick.


$config['protocol'] = 'smtp';
$config['smtp_host'] = 'localhost';
$config['email_address'] = 'sender@localhost.com';
$config['email_name'] = 'Localhost test';


6. Remember not to close your 7. If you want to, you can also configure codeigniter to autoload the email config by adding it at the autoload.php file

We can now start sending mail with code igniter:
1. At the application->controllers create a controller class:

class Test_Mail extends Controller {
function Test_Mail()
{
parent::Controller();
}
function index()
{
// get config data
$from = $this->config->item('email_address', 'email');
$from_name = $this->config->item('email_name', 'email');
$to = 'tildemark@localhost.com';
$to_name = "To Name";
// we load the email library and send a mail
$this->load->library('email');
$this->email->from($from, $from_name);
$this->email->to($to, $to_name);
$this->email->subject('Email subject');
$this->email->message('Testing the email class.');
$this->email->send();
//to debug we can use print_debugger()
echo $this->email->print_debugger();
}
}

2. On your browser, type in http://localhost/codeigniter/test_mail
3. Check you mail client for new mails.
4. Thats it! We have successfully sent a mail using Mercury on XAMPP on in your local computer.

Wednesday, July 29, 2009

Time difference in php

function get_time_difference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{ if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
trigger_error( "Ending date/time is earlier than the start date/time", E_USER_WARNING );
}
}
else
{
trigger_error( "Invalid date/time data detected", E_USER_WARNING );
}
return( false );
}
--------------------------------------------------------------------------------
// a START time value
$start = '09:00';
// an END time value
$end = '10:30';

// what is the time difference between $end and $start?
if( $diff=@get_time_difference($start, $end) )
{
echo "Hours: " .
sprintf( '%02d:%02d', $diff['hours'], $diff['minutes'] );
}
else
{
echo "Hours: Error";
}





?>

Currency Converter in php

function exchangeRate( $amount, $currency, $exchangeIn )
{
$googleQuery = $amount . ' ' . $currency . ' in ' . $exchangeIn;
$googleQuery = urlEncode( $googleQuery );
$askGoogle = file_get_contents( 'http://www.google.com/search?q=' . $googleQuery );

$askGoogle = strip_tags( $askGoogle );
$matches = array();
preg_match( '/= (([0-9]|\.|,|\ )*)/', $askGoogle, $matches );
return $matches[1] ? $matches[1] : false;
}

echo exchangeRate( 1, 'dollars','rupee');




if(isset($from2) && trim($from2)!="" && isset($to) && trim($to)!=""){
?>

}else{
?>

}
?>

image slideshow with loader

1) http://www.dhtmlgoodies.com/scripts/image_slideshow/image_slideshow.html
2) http://www.dhtmlgoodies.com/index.html?whichScript=image_slideshow
3) http://www.developphp.com/
4) sliding window code ( http://www.panic.com/coda/ )

Upload images with resize or thumb image in php

function add_picture_story($story_id,$filename,$tmpname) {
global $config;
$filename_parts = explode(".",strrev($filename),2);
$filename_base = strrev($filename_parts[1]);
$filename_ext = strrev($filename_parts[0]);

$unique_filename_base = strtolower(sanitize_filename($filename_base));
$final_filename = $unique_filename_base . "." . $filename_ext;

// final fully qualified file name
$final_fqfn = $config["basedir"].'images/images_story/'.$final_filename;

if (is_uploaded_file($tmpname)) {
if (!move_uploaded_file($tmpname,$final_fqfn)) {
$result['errors'] .= sprintf(plog_tr('Could not move uploaded file! %s to %s'),$tmpname,$final_fqfn);
return $result;
}
}

@unlink($tmpname);
$res = chmod($final_fqfn, 0755);
$destination= $config["basedir"].'images/images_story/thumb_story/'.$final_filename;
$imagename = $final_filename;
$height =111;
$width =158;
if(isset($filename) && trim($filename)!=""){
image_thumb($final_fqfn,$destination,$imagename,$height,$width);
}

$update_story = mysql_query("update plogger_stories SET image_story ='$final_filename' where id='$story_id'");

}



function image_thumb($filename,$destination,$imagename,$height,$width)
{

$length=strlen($imagename);
$newpos=strrpos($imagename,".")+1;
$type=substr($imagename,$newpos,$length-$newpos);
$imagetype=strtolower($type);
$th_height=$height;
$th_width=$width;
$new = imagecreatetruecolor($th_width, $th_height);
if(strtolower($imagetype)=="png")
{
$source = imagecreatefrompng($filename);
imagecopyresampled($new, $source, 0, 0, 0, 0, $th_width, $th_height,
imagesx($source), imagesy($source));
imagepng($new, $destination);
}
elseif(strtolower($imagetype)=="gif")
{
$source = imagecreatefromgif($filename);
imagecopyresampled($new, $source, 0, 0, 0, 0, $th_width, $th_height,
imagesx($source), imagesy($source));
imagegif($new, $destination);
}
else
{
$source = imagecreatefromjpeg($filename);
imagecopyresampled($new, $source, 0, 0, 0, 0, $th_width, $th_height,
imagesx($source), imagesy($source));
imagejpeg($new, $destination);
}


}

Create xml using database

include("conn.php");

$query = "SELECT * FROM user_record";

$result = mysql_query($query);

$num = mysql_num_rows($result);
$somecontent = '';
for($n=0; $n < $num-1; $n++)
{

$i=$n+1;
$name = mysql_result($result,$i,'name');
$email = mysql_result($result,$i,'email');
$address = mysql_result($result,$i,'address');
$city = mysql_result($result,$i,'city');
$state = mysql_result($result,$i,'state');
$phone = mysql_result($result,$i,'phone');
$cuntery = mysql_result($result,$i,'cuntery');
$image_add = mysql_result($result,$i,'image_add');



$somecontent .= "<$i>";

$somecontent .= "$name";

$somecontent .= "$email";

$somecontent .= "
$address
";
$somecontent .= "$city";
$somecontent .= "$state";

$somecontent .= "$cuntery";
$somecontent .= "$phone";

$somecontent .= "$image_add";
$somecontent .= "";
}
/////////////////////////////////write data in file ////////////////////
$filename = 'c:\webserv\wwwroot\htdocs\san\record.xml';

if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);

//////////////////////////////////////////// end///////////////////////
?>
conn.php


$localhost = "localhost";
$username = "root";
$password = "";
$database = "record";

mysql_connect($localhost,$username,$password) or die("unable to connect");
mysql_select_db($database);


?>

Create xml using database

include("conn.php");

$query = "SELECT * FROM user_record";

$result = mysql_query($query);

$num = mysql_num_rows($result);
$somecontent = '';
for($n=0; $n < $num-1; $n++)
{

$i=$n+1;
$name = mysql_result($result,$i,'name');
$email = mysql_result($result,$i,'email');
$address = mysql_result($result,$i,'address');
$city = mysql_result($result,$i,'city');
$state = mysql_result($result,$i,'state');
$phone = mysql_result($result,$i,'phone');
$cuntery = mysql_result($result,$i,'cuntery');
$image_add = mysql_result($result,$i,'image_add');



$somecontent .= "<$i>";

$somecontent .= "$name";

$somecontent .= "$email";

$somecontent .= "
$address
";
$somecontent .= "$city";
$somecontent .= "$state";

$somecontent .= "$cuntery";
$somecontent .= "$phone";

$somecontent .= "$image_add";
$somecontent .= "";
}
/////////////////////////////////write data in file ////////////////////
$filename = 'c:\webserv\wwwroot\htdocs\san\record.xml';

if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);

//////////////////////////////////////////// end///////////////////////
?>
conn.php


$localhost = "localhost";
$username = "root";
$password = "";
$database = "record";

mysql_connect($localhost,$username,$password) or die("unable to connect");
mysql_select_db($database);


?>

Valid Date in javascript

function validDate(date2)
{
// date formate 12-27-2007 mm-dd-yyyy
/* var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currentDate = month + "-" + day + "-" + year;
alert(currentDate); */

var currentTime = new Date();
var currentDate = currentTime.format('m-d-Y');
//alert(currentDate);
if(trim(currentDate)!="" && trim(date2)!="")
{
var str1 = currentDate;
var str2 = date2;
var mon1 = parseInt(str1.substring(0,2),10);
var dt1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var mon2 = parseInt(str2.substring(0,2),10);
var dt2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date11 = new Date(yr1, mon1, dt1);
var date22 = new Date(yr2, mon2, dt2);
if(date22 < date11) return true;
}
}

Trim in javascript remove left & right space

function trim(str)
{
return str.replace(/^\s*|\s*$/g,"");
}

Date comparison in javascript

function validDeparturDate(date_arrival,date_departur){

var str1 = date_arrival;
var str2 = date_departur;
if(trim(str1)!="" && trim(str2)!="")
{
var yr1 = parseInt(str1.substring(0,4),10);
var mon1 = parseInt(str1.substring(5,7),10);
var dt1 = parseInt(str1.substring(8,10),10);
var yr2 = parseInt(str2.substring(0,4),10);
var mon2 = parseInt(str2.substring(5,7),10);
var dt2 = parseInt(str2.substring(8,10),10);
var date_arrival1 = new Date(yr1, mon1, dt1);
var date_departur2 = new Date(yr2, mon2, dt2);

if(date_departur2 < date_arrival1)
{
return false;
}
}
return true;
}

if(trim(g.date_of_departure.value)=="")
{
alert("");
g.date_of_departure.focus();
return false;
}
var date1 = g.date_of_arrival.value;
var date2 = g.date_of_departure.value;
if(trim(g.date_of_departure.value)!="" && !validDeparturDate(date1,date2))
{
alert("Date of departure should be grater then date of arrival!");
g.date_of_departure.focus();
return false;
}

Multiple Checkbox Validation in javascript

var g = document.formname;
var checkSelected=0;
for(var i=0; i < g.elements.length; i++) {
if(g.elements[i].name && g.elements[i].name.substr(0, 8) == "category" && g.elements[i].checked == true && g.elements[i].name != "categoryname") {
checkSelected = 1;
break;
}
}

if( checkSelected == 0 ){
alert("");
g.elements[i].focus();
return false;
}

Valid phone no. like 222-222-2222 in javascript

var g = document.frm;
if(trim(g.phone.value)=="")
{
alert("Please enter phone no.");
g.phone.value = trim(g.phone.value);
g.phone.focus();
return false;
}
if(!validatePhone(g.phone.value))
{
alert("Please enter valid phone no. like 222-222-2222.");
g.phone.value = trim(g.phone.value);
g.phone.focus();
return false;
}


function validatePhone(number)
{
var textV = number;
var reg = new RegExp("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", "i")
if(textV.match(reg)) {
return true;
} else {
return false;
}
}

IsNumeric in javascript

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var IsNumbe r= true;
var Char;
for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
if (Char =='.' && ValidChars.indexOf(Char)!= ValidChars.lastIndexOf(Char))
{
IsNumber=false;
}
}
return IsNumber;
}

Thursday, July 23, 2009

Upcoming changes in PHP 6.0

PHP 6.0 looks to be an exciting release. Nothing is absolutely fixed yet, but it looks like it will see the demise of three of my pet peeves: register_globals, magic_quotes_gpc and safe_mode. The first was just a big security hole, the second messed with the data and made changing environments potentially nightmarish, while the third was a misnomer that nobody really understood, and provided a false sense of security. There's also quite a lot of work scheduled to do with Unicode. Here are some of the changes:
  • The register_globals, safe_mode and the various magic quotes options will be removed.
  • The ereg extension is removed, while the XMLReader, XMLWriter and Fileinfo extensions are added to the core, and by default are on.
  • Another addition I find particularly exciting is that APC (Alternative PHP Cache) will be added to the core, though will be off by default. APC can provide serious performance benefits.
  • All E_STRICT messages will be merged into E_ALL, another positive change that will encourage good programming practice.
  • ASP style <% tags will no longer be supported.
  • Addition of a new 64-bit integers. The current integer type remains as is, 32 or 64-bit dependent on the platform.
  • Use of foreach with multi-dimensional arrays, for example foreach($array as $k => list($a, $b)).
  • A new switch in php.ini will allow you to disable Unicode semantics (by default they will be on).
  • There will also be various string improvements related to Unicode.
  • The microtime() function will return the full floating point number, rather than microseconds unix_timestamp, as at present, probably making the function more readily useful for most people.
  • The {} notation for string indexes will no longer be supported, while the [] version will get added substr() and array_slice() functionality. Previously [] was deprecated, but most developers, including myself, seem to use [].
  • FastCGI will always be enabled for the CGI SAPI, and will not be able to be disabled.
  • The ancient HTTP_*_VARS globals will no longer be supported. Everyone should have had more than enough time to remove any traces of these.
  • var will alias public. var was permitted with PHP4 classes, but in PHP 5 this raised a warning. In PHP 6 var will simply be an alias for public, so no warning is necessary.
  • The ze1 compatibility mode, which tried to retain PHP 4 behaviour but had some bugs, will be removed.
  • Dynamic functions will no longer be permitted to be called with static syntax.

There's still much to be determined, namespaces being one of the more important, but as yet there's little agreement. You can read the full minutes from the recent PHP Developer's meeting here where PHP 6 was discussed at length. With PHP 6 still quite a way off, I'm sure there'll be much more wailing and gnashing of teeth before we see the final product, but I'm excited by where it seems to be heading, and the progress that is being made.

Friday, July 17, 2009

Interface in Php

An Interface is like a template similar to abstract class
with a difference where it uses only abstract methods.

In simple words, an interface is like a class using
interface keyword and contains only function
declarations(function with no body).

An Interface should be implemented in the class and all the
methods or functions should be overwridden in this class.

for eg:

interface InterfaceName{
function fun1();
function fun2(a,b);
}

class ClassName implements InterfaceName{
fuction fun1(){
function implementation.......
}
fuction fun2(a,b){
function implementation.......
}
}

Tuesday, July 14, 2009

Removing index.php from the url in codeigniter

Hi,

I also tried to find out many the exact way to remove the index.php from the url but did not get much help. Then after lots of hits and try I made the .htacess that is working for me. So I wanted to share this with you all.
My framework is in the folder abc.

The .htaccess

RewriteEngine on
RewriteCond %{QUERY_STRING} ^(ACT=.*)$ [NC]
RewriteRule ^(.*)$ index.php?%1 [L]
RewriteCond $1 !^(images|_css|_js|scripts|cal|uploads|portal_member_image|index.php) [NC]
RewriteRule ^(.*) /abc/index.php?/$1 [L]

And when ever you make a call to a controller please specify the full url without the index.php like if I want to call a controller called hi controller and inside that a hello function then what i will have to write is.

redirect($this->config->item('baseurl').'hi/hello');

Hope this will of any help to someone.

Thanks
Jawed

Pagination in codeigniter

I've often see forum posts asking why the Pagination class isn't working. I decided to create a tutorial on the Pagination class for those who need to learn about the pagination class.

Let's now start with the pagination tutorial. This tutorial assumes that you have connected your CodeIgniter application to the database.

First, we need to create a table.


CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(50) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Next, we create our own Model for our articles table.


class Articles_model extends Model {

function Articles_model()
{
parent::Model();
}

function get_posts($limit = NULL, $offset = NULL)
{
$this->db->limit($limit, $offset);
return $this->db->get('posts');
}

function count_posts()
{
return $this->db->count_all_results('posts');
}



The method Articles_model() is the constructor. In PHP 4, constructors are named after the class they are located in.

The method get_posts(), retrieves the information from the database. Notice that it has parameters for limiting and the offset of returned rows.

The method count_posts(), retrieves the total number of posts available in the table.

Next on our list is creating the controller function.



class Posts extends Controller {

function Posts()
{
parent::Controller();
}

function manage()
{
$this->load->model('posts_model');
$per_page = 10;
$total = $this->posts_model->count_posts();
$data['posts'] = $this->posts_model->get_posts($per_page, $this->uri->segment(3));

$base_url = site_url('posts/manage');
$config['base_url'] = $base_url;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['uri_segment'] = '3';

$this->pagination->initialize($config);
$this->load->view('admin/posts/manage', $data);
}

Copy and paste and do not worry if you don't understand that chunk of code yet. We will get back to that later on.

Monday, July 13, 2009

Webservice in php

Hi,

At the link below, there is a quick and good reference about web services in php

http://talks.php.net/show/oscon-webservices/

Saturday, July 11, 2009

download all php framework from here

Hi

you can download all php frameworks (popular) from this link.

http://www.phpframeworks.com/php-frameworks-download/

developing facebook application with cakephp

hi

Here you can find something usefull for developing facebook application in cake php

http://facebook-developer.net/2007/10/18/building-your-first-facebook-application-with-cakephp/

Jquery plugings for codeigniter

hi,

At this link you can find many jquery plugins for code ignitor


http://malsup.com/jquery/form/

Nice cake php tutorials

Hi,

At this link you can find nice cake php tutorials


http://cakebaker.42dh.com/tags/tutorial/

Making site in some other language like hebrew

I’ve been working on a little application that grabs data from Hebrew news sites into a mySQL database.

While working on this mini-project I’ve realized that there is hardly any online tutorials on using the Hebrew font. Here’s my solution which is fairly simple and works effectively.

Step 1) Set the HTML page charset encoding to utf8:

meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8

Step 2) set the ‘collation’ attribute for the fields which are to accept hebrew text to: utf8_bin

Step 3) within your php script, right before calling the mysql_query function to insert the data into your DB, use both the utf8_encode function along with addslashes. This will encode the data into utf8 friendly characters.

Step 4) when pulling the text from the DB onto the page, make sure to use the utf8_decode along with stripslashes in order to display the data on the page.


Some Important Link to read about OOPs with php

http://www.devarticles.com/c/a/PHP/Object-Oriented-Programming-in-PHP/

Testing Web Based Applications with JMeter

http://www.devarticles.com/c/a/PHP/Regression-Testing-With-JMeter/

lot of books collection here !

http://www.yourbooklib.com/

useful url rewriting examples using .htaccess

1)Rewriting product.php?id=12 to product-12.html
It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
2) Rewriting product.php?id=12 to product/ipod-nano/12.html
SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html
$ product.php?id=$2
3) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz
Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
4) Redirecting the domain to a new subfolder of inside public_html.
Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1

useful URL for PHP date problem

PHP Date Generator
http://www.b2ben.com/php/phpdate.php

Example of Custom URL rewritting

RewriteEngine on
RewriteRule ^career-options/(.*)-([0-9]+)\.html$ careerdetails.php?carr_id=$2RewriteRule ^career-advice$ careeradvice.phpRewriteRule ^parent-career-help$ parent_profile.phpRewriteRule ^Forum/(.*)-([0-9]+)\.html$ forum_index.php?career_category_id=$2RewriteRule ^career-advice/career-counselling$ careercounselling.phpRewriteRule ^career-advice/interview-training$ interviewsuccess.phpRewriteRule ^career-advice/interview-questions-answers$ interview_questions.phpRewriteRule ^career-options$ career.phpRewriteRule ^community$ community.phpRewriteRule ^career--options/(.*)-([0-9]+)\.html$ careerdetails.php?carr_id=$2&addFirstChoice=1

PayPal Identity Token (PHP Script)

if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $req); // read the body data $res = ''; $headerdone = false; while (!feof($fp)) { $line = fgets ($fp, 1024); if (strcmp($line, "\r\n") == 0) { // read the header $headerdone = true; } else if ($headerdone) { // header has been read. now read the contents $res .= $line; } }
// parse the data $lines = explode("\n", $res); $keyarray = array(); if (strcmp ($lines[0], "SUCCESS") == 0) { for ($i=1; $iaddPaymentDetails($keyarray['txn_id'], 'Paypal', $keyarray['mc_gross'], $keyarray['option_name1'],$status);
header("location:thanks_payment.php"); } else if (strcmp ($lines[0], "FAIL") == 0) { header("location:error.php"); // log for manual investigation //header("location:thanks_payment.php"); }
}
fclose ($fp);?>

How do I generate a PayPal Identity Token

1. Click the My Account tab.
2. Click Profile at the top of the page.
3. On the right under Selling Preferences click on Website Payment Preferences.
4. Under Auto Return for Website Payments click "on"
5. After Return URL put http://www.mytalentplace.co.uk
6. Under Payment Data Transfer (Optional) click "on"
7. Scroll to the bottom of the page and click Save.
8. Copy the Identity Token (everything after the word "Token:" in the new window), and paste it into your My talent place PayPal Information.

Website Payments Standard Integration Guide (Paypal)

https://www.paypalobjects.com/WEBSCR-580-20090702-1/en_US/pdf/PP_WebsitePaymentsStandard_IntegrationGuide.pdf

Opening Cake THTML file with Dreaweaver CS4

Just go to:

C:\Program Files\Adobe\Adobe Dreamweaver CS4\configuration

Open file: Extensions.txt

edit line 16 and add THTML

Save and Close the File

Next, Open MMDocumentTypes.xml at C:\Program Files\Adobe\Adobe Dreamweaver CS4\configuration\DocumentTypes

Add THTML online 75 : winfileextension=”thtml,php,php3,php4,php5″ macfileextension=”thtml,php,php3,php4,php5″

Save, close and Restart Dreamweaver!


For more Info :- http://keithics.com/blog/article/opening-cake-thtml-file-with-dreaweaver-cs4/118/

php realex payment gateway code

$timestamp = strftime("%Y%m%d%H%M%S");
$topay = '5';
$merchantid = "mytalentplace";//here grant crow`s realex merchent id should come
$secret = "wXcHmZ9yec";


$orderid= $timestamp.'-'.$_SESSION['ord_id'];





$amount =$_POST['amt']*100;

if($_REQUEST['currency']=="doller"){

$curr= "USD";

} elseif($_REQUEST['currency']=="euro"){

$curr= "EUR";

}else {

$curr= "GBP";

}

$tmp = "$timestamp.$merchantid.$orderid.$amount.$curr";
//$tmp = "$timestamp.$merchantid.$orderid";

$md5hash = sha1($tmp);

$tmp = "$md5hash.$secret";

$md5hash = sha1($tmp);

$up="UPDATE `mtp_user_payment` SET order_id='".$lid."' where user_payment_id='".$lid."'";
mysql_query($up);
?>



for live
for test

Wednesday, July 1, 2009

One more good blog

Hi this is one more good php blog from my friend Anurag. You can also find good php resource here

http://anuragtrivediphp.blogspot.com/

Thanks

Jawed

Help for php developers

Hi to all,

I am making this blog keeping this mind that sometimes we search for codes and questions that are hard to find and we waste many time in it. So, I will put those kind of code and stuff, so that other can get help too. And I request to you all that you people too do the same.

Thanks
Jawed