most of your code is ok, however i think u reuse the key bits every 512 chars... i think an attacker could exploit this. maybe u should better create a keystream which is as long as the data u wanna encrypt. u just need to modify your for loop a little ($i < strlen($str) ) and remove the $x in the encryption loop, just use $i for all strings.
Moreover, u gotta seed the random number generator usin srand(time()), and use the mt_rand function (www.php.net/mt_rand) which will give u better random values (here u have to use mt_srand to initialize).
hth