To upload and save files to server, refer to this:
http://www.w3schools.com/php/php_file_upload.asp[
^]
Always store the upload images in the same folder say "bg-images".
In the php script for changing the background image (your code shown), do not hard code the $bg array, instead scan the image folder to update the $bg array like this:
$dir = 'bg-images/';
$bg = glob($dir . '*.jpg');
http://php.net/manual/en/function.glob.php[
^]