/** * Switch TOR to a new identity. **/ function tor_new_identity($tor_ip='127.0.0.1', $control_port='9051', $auth_code=''){ $fp = fsockopen($tor_ip, $control_port, $errno, $errstr, 30); if (!$fp) return false; //can't connect to the control port fputs($fp, "AUTHENTICATE \"$auth_code\"\r\n"); $response = fread($fp, 1024); list($code, $text) = explode(' ', $response, 2); if ($code != '250') return false; //authentication failed //send the request to for new identity fputs($fp, "signal NEWNYM\r\n"); $response = fread($fp, 1024); list($code, $text) = explode(' ', $response, 2); if ($code != '250') return false; //signal failed fclose($fp); return true; }
/** * Load the TOR's "magic cookie" from a file and encode it in hexadecimal. **/ function tor_get_cookie($filename){ $cookie = file_get_contents($filename); //convert the cookie to hexadecimal $hex = ''; for ($i=0;$i<strlen($cookie);$i++){ $h = dechex(ord($cookie[$i])); $hex .= str_pad($h, 2, '0', STR_PAD_LEFT); } return strtoupper($hex); }
TOR Authentication
Depending on your configuration, the script may need to authenticate before it can signal TOR to switch to a new identity.
There are three authentication modes TOR supports :
- None – no authentication required. You don’t need to set the third parameter of tor_new_identity().
- Cookie – TOR stores a “magic cookie” in the control_auth_cookie file inside it’s data directory. You have to authenticate by sending this cookie encoded in hexadecimal form. You can use tor_get_cookie() to read and properly encode the cookie.
Example :
$cookie = tor_get_cookie('/path/to/tor/data/dir/control_auth_cookie'); tor_new_identity('127.0.0.1', 9051, $cookie);
- Password – your basic password authentication. To authenticate you will need to use the password in “quotes” or a hex-encoded version of the password.
Example :
tor_new_identity('127.0.0.1', '9051', '"secret_passw0rd"');
http://w-shadow.com/blog/2008/06/20/tor-how-to-new-identity-with-php/