Javascript函数到Php

I need to encode a password to hexadecimal in javscript and then decode it in php. I have a function that does the two things but in javascript. I tried to transform it to php but there are some javascript native functions that i dont know what is the php equivalent.

The function to encode (Javascript)

function encodeToHex(str){
    var r="";
    var e=str.length;
    var c=0;
    var h;
    while(c<e){
        h=str.charCodeAt(c++).toString(16);
        while(h.length<3) h="0"+h;
        r+=h;
    }
    return r;
}

The function to decode (Javascript)

function decodeFromHex(str){
    var r="";
    var e=str.length;
    var s;
    while(e>=0){
        s=e-3;
        r=String.fromCharCode("0x"+str.substring(s,e))+r;
        e=s;
    }
    return r;
}

The function to decode (PHP) << This is what im trying to achieve

function decodeFromHex($str){
$r="";
$e=str.length;
$s;
while($e>=0){
        $s=$e-3;
        $r=String.fromCharCode("0x"+str.substring($s,$e))+$r;
        $e=$s;
    }
    return $r;
}

You need hexdec and dechex functions.

By the way, you get string length in php via strlen().

On a last note, client side encoding is quite pointless, as it's easy to sniff and decode your data - use SSL over HTTPS if you want to be sure.

Decoding HEX values in PHP can be done using either:

current(unpack('H*', $str))

Or:

hex2bin($str);

I'm hoping that you're not really encoding passwords into HEX though