If you found bad code at the top of your index.php or any other php files that you didn't put there. It means your website has been hacked and now the hacker is able to do anything with your website.
To prevent future attacks, you have to disable all the dangerous functions in php.ini.
allow_url_fopen = off
allow_url_include = off
register_globals = Off
disable_functions = "shell_exec, eval, exec, system, proc_get_status, inject_code, proc_nice, proc_open, proc_terminate, apache_child_terminate, apache_setenv, fp, fput, ftp_connect, tp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, popen, escapeshellcmd, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, osix_setuid, posix_setuid, posix_uname, syslog, xmlrpc_entity_decode, proc_close, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, passthru, phpAds_xmlrpcDecode, hpAds_xmlrpcEncode, mysql_pconnect, escapeshellarg, highlight_file, define_syslog_variables, ini_restore,ini_alter, ini_get_all, openlog"