Monday, June 24, 2013

Editable div using css and html

<div class="sticky_editor" contentEditable="true">
    Here is your html.<br/>Thanks.
</div>

.sticky_editor {
    background-color: #FFFFCC;
    background-image: url("images/document_body_rules.gif");
    background-position: -1px top;
    background-repeat: repeat;
    line-height: 20px;
    min-height: 113px;
    border: 1px solid #E7E7E7;
    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.3) inset;
    transition: border 0.2s linear 0s, box-shadow 0.2s linear 0s;
    font-family: monospace;
    padding-left: 12px;
    overflow: auto;
}

Download the image from here 

And this is JSFiddle link



Sunday, June 23, 2013

jQuery textarea append newline behavior

You use the jQuery val method, \n works consistently in Firefox and IE (Including IE8):
var txt = $("textarea#idhere");
txt.val( txt.val() + "\nSomething here\n\nAgain");

Saturday, June 22, 2013

PHP - Redirect and send data via POST

It is a simple way to do that.
Suppose you are in from.php, just call the function like:
<?php
actionPost("www.pritom.com/to.php", array(
    "id" => 1,
    "name" => "Pritom K Mondal";
)); 
?>
And suppose in to.php, write the following code:
<?php
print_r($_POST);
?>

That will output:

<?php
Array
(
    [id] => 1
    [name] => Pritom K Mondal
)
?>


<?php
function actionPost($action, $data = array()) 
{
    ?><html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <script type="text/javascript">
                function closethisasap (){
                    document.forms["redirectpost"].submit();
                }
            </script>
            <body onload="closethisasap();">
                <form name="redirectpost" method="post" action="<?php echo $action; ?>" >
                    <?php
                    if (!is_null($data)) {
                        foreach ($data as $k => $v) {
                            ?><input type="hidden" name="<?php echo $k; ?>" value="<?php echo $v; ?>" /><?php
                        }
                    }
                    ?>
                </form>
            </body>
        </head>
    </html>
    <?php exit();
}
?>

Friday, June 21, 2013

Encrypted Sessions with PHP

Here's the code, an explanation will follow:



<?php
class Session
{
    /**
     * Path to save the sessions to
     * @var string
     */
    private $savePathRoot = '/tmp';

    /**
     * Save path of the saved path
     * @var string
     */
    private $savePath = '';

    /**
     * Salt for hashing the session data
     * @var string
     */
    private $key = '282edfcf5073666f3a7ceaa5e748cf8128bd53359b6d8269ba2450404face0ac';

    /**
     * Init the object, set up the session config handling
     *
     * @return null
     */
    public function __construct()
    {
        session_set_save_handler(
            array($this, "open"), array($this, "close"),  array($this, "read"),
            array($this, "write"),array($this, "destroy"),array($this, "gc")
        );

        $this->savePathRoot = ini_get('session.save_path');
    }

    /**
     * Encrypt the given data
     *
     * @param mixed $data Session data to encrypt
     * @return mixed $data Encrypted data
     */
    private function encrypt($data)
    {
        $ivSize  = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $iv      = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $key     = substr(sha1($this->key), 0, $keySize);

        // add in our IV and base64 encode the data
        $data    = base64_encode(
            $iv.mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv
            )
        );
        return $data;
    }

    /**
     * Decrypt the given session data
     *
     * @param mixed $data Data to decrypt
     * @return $data Decrypted data
     */
    private function decrypt($data)
    {
        $data    = base64_decode($data, true);

        $ivSize  = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $key     = substr(sha1($this->key), 0, $keySize);

        $iv   = substr($data, 0, $ivSize);
        $data = substr($data, $ivSize);

        $data = mcrypt_decrypt(
            MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv
        );

        return $data;
    }

    /**
     * Set the key for the session encryption to use (default is set)
     *
     * @param string $key Key string
     * @return null
     */
    public function setKey($key)
    {
        $this->key = $key;
    }

    /**
     * Write to the session
     *
     * @param integer $id   Session ID
     * @param mixed   $data Data to write to the log
     * @return null
     */
    public function write($id, $data)
    {
        $path = $this->savePathRoot.'/'.$id;
        $data = $this->encrypt($data);

        file_put_contents($path, $data);
    }

    /**
     * Read in the session
     *
     * @param string $id Session ID
     * @return null
     */
    public function read($id)
    {
        $path = $this->savePathRoot.'/'.$id;
        $data = null;

        if (is_file($path)) {
            // get the data and extract the IV
            $data = file_get_contents($path);
            $data = $this->decrypt($data);
        }
        return $data;
    }

    /**
     * Open the session
     *
     * @param string $savePath  Path to save the session file locally
     * @param string $sessionId Session ID
     * @return null
     */
    public function open($savePath, $sessionId)
    {
        // open session, do nothing by default
    }

    /**
     * Close the session
     *
     * @return boolean Default return (true)
     */
    public function close()
    {
        return true;
    }

    /**
     * Perform garbage collection on the session
     *
     * @param int $maxlifetime Lifetime in seconds
     * @return null
     */
    public function gc($maxlifetime)
    {
        $path = $this->savePathRoot.'/*';

        foreach (glob($path) as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }

    /**
     * Destroy the session
     *
     * @param string $id Session ID
     * @return null
     */
    public function destroy($id)
    {
        $path = $this->savePathRoot.'/'.$id;
        if (is_file($path)) {
            unlink($path);
        }
        return true;
    }
}
?>

Resources

Php Session ID, Session Save Path, Session List

ini_set('session.save_path', "C:\temp_sessions");
session_id(md5("".time())); /* every time set new session id */
//ini_set('session.gc_probability', 1); /* To remove previous sessions */
session_start();

echo session_id();
echo session_save_path();
echo "Session Save Path: " . ini_get( 'session.save_path');
$sessions = array();

$path = realpath(session_save_path());
$files = array_diff(scandir($path), array('.', '..'));

foreach ($files as $file)
{
    if(is_file($path.DS.$file) ) {
        $content = file_get_contents($path.DS.$file);
        $sessions[$file] = $path."/".$file;
        $sessions[$file."_content"] = unserialize($content);
    }
}

$path = session_save_path()."/*";

foreach (glob($path) as $file) {
    $diff = time() - filemtime($file);
    echo $file.", Last Updated= ".filemtime($file)."   ,Difference=   ".$diff."<br/>";
}

Thursday, June 20, 2013

Storing a function with jQuery to a html element and call it


var myElm = $(".some-element-class");

myElm[0].someFunction = function() {
    console.log("here");
}

if(myElm[0].someFunction !== undefined && myElm[0].someFunction != null 
    && typeof myElm[0].someFunction == "function") {
    myElm[0].someFunction(param1, param2);
}

Overriding Core jQuery Methods

jQuery is such a well thought out, powerful Javascript library, that it actually uses itself to build itself. What I mean by that is that many of the methods provided by the jQuery library are actually built internally as plugins to the jQuery architecture. When you start to think about the methods in this way, it is a small leap to see that we can override a given jQuery method by simply creating a new plugin of the same name.

(function () {
    // Store a reference to the original remove method.
    var originalRemoveMethod = jQuery.fn.remove;

    // Define overriding method.
    jQuery.fn.remove = function () {
        // Log the fact that we are calling our override.
        console.log("Override method");

        // Execute the original method.
        originalRemoveMethod.apply(this, arguments);
    }
})();