<?php

$fritz_host = 'fritz.box';
$fritz_url = 'http://' . $fritz_host . '/login_sid.lua';
$fritz_user = 'xxxxxx'; //optional
$fritz_pwd = 'xxxxxxxx';
$with_debug_output = true;

// Get Challenge-String
$tmp = simplexml_load_string(file_get_contents($fritz_url));
if ($tmp->BlockTime > 0) {
	sleep($tmp->BlockTime);
	$tmp = simplexml_load_string(file_get_contents($fritz_url));
}
	
if ($with_debug_output) {
	print_r('Got challenge: ' . $tmp->asXML() . PHP_EOL);
	$challenge = $tmp->Challenge;
	
	// Get SID
	$challenge_str = $challenge . '-' . $fritz_pwd;

	print_r(' $challenge_str: ' . $challenge_str . PHP_EOL);

	$md_str = md5(iconv("UTF-8", "UTF-16LE", $challenge_str));
	print_r(' $md_str: ' . $md_str . PHP_EOL);
	
	$response = $challenge . '-' . $md_str;
	$tmp = simplexml_load_string(file_get_contents($fritz_url . '?user=' . $fritz_user . '&response=' . $response));

	if ($with_debug_output) {
		print_r(' Got session ID: ' . $tmp->asXML() . PHP_EOL); $sid = $tmp->SID;
		// Logout
		$tmp = simplexml_load_string(file_get_contents($fritz_url . '?logout=1&sid=' . $sid));
		if ($with_debug_output) {
			print_r(' Logout: ' . $tmp->asXML() . PHP_EOL);
		}
	}
}
?>
