Monday, February 18, 2013

sort an array without using array php

<?php
function sort1($arr) {
  for ($i=0; $i<count($arr); $i++) {
    for ($j=0; $j<count($arr)-1-$i; $j++) {
        if ($arr[$j+1] <$arr[$j]) {
            swap($arr, $j, $j+1);
        }
     }
  }
  return $arr;
}

function swap(&$arr, $a, $b) {
   $tmp = $arr[$a];
   $arr[$a] = $arr[$b];
   $arr[$b] = $tmp;
}

//using sorting functions
$arr = array(1,13,2,9,5,7,0,3);

 echo("Before sorting");
 print_r($arr);



 echo("qafter sorting array");
 print_r(sort1($arr));

php session handling class

<?php
class FileSessionHandler
{
    private $savePath;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

// the following prevents unexpected effects when using objects as save handlers


session_start();
$handler->open('D:\xampp\tmp\bikas','bikash');
$sessionid=session_id();
$data=array(
'bikash',
'delhi');

$handler->write($sessionid,$data);
$handler->read($sessionid);
$handler->destroy($sessionid);
$handler->close();