PHP Weiterleitung auf andere Seite schlägt fehl

Timmey92

Commodore
Registriert
Okt. 2008
Beiträge
4.567
Ok, also erstmal zur Ausgangslage: dieses hier ist ein account registration script für meine website. Es soll, nachdem ein account registriert wurde automatisch auf eine website weiterleiten (die beinhaltet weiterführende informationen, faq etc.).
Ich habe mir gedacht ich füge einfach eine header( Location: blabla); am ende der create() funktion hinzu -> fehlanzeige, geht nicht da anscheinend schon headers gesendet wurden.
fopen geht nicht und http redirect schlägt auch fehl :S
Hoffe ihr könnt mir da helfen :)
Wäre sehr dankbar für Ansätze/Vorschläge/Lösungen.

PHP:
<?
//test display character equipment
		session_start();
include_once("config.php");



function validateEmail($email, $domainCheck = false, $verify = false, $probe_address='', $helo_address='', $return_errors=false) {
    global $debug;
    $server_timeout = 180; # timeout in seconds. Some servers deliberately wait a while (tarpitting)
    if($debug) {echo "<pre>";}
    # Check email syntax with regex
    if (preg_match('/^([a-zA-Z0-9\._\+-]+)\@((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,7}|[0-9]{1,3})(\]?))$/', $email, $matches)) {
        $user = $matches[1];
        $domain = $matches[2];
        # Check availability of DNS MX records
        if ($domainCheck && function_exists('checkdnsrr')) {
            # Construct array of available mailservers
            if(getmxrr($domain, $mxhosts, $mxweight)) {
                for($i=0;$i<count($mxhosts);$i++){
                    $mxs[$mxhosts[$i]] = $mxweight[$i];
                }
                asort($mxs);
                $mailers = array_keys($mxs);
            } elseif(checkdnsrr($domain, 'A')) {
                $mailers[0] = gethostbyname($domain);
            } else {
                $mailers=array();
            }
            $total = count($mailers);
            # Query each mailserver
            if($total > 0 && $verify) {
                # Check if mailers accept mail
                for($n=0; $n < $total; $n++) {
                    # Check if socket can be opened
                    if($debug) { echo "Checking server $mailers[$n]...\n";}
                    $connect_timeout = $server_timeout;
                    $errno = 0;
                    $errstr = 0;
                    # Try to open up socket
                    if($sock = @fsockopen($mailers[$n], 25, $errno , $errstr, $connect_timeout)) {
                        $response = fgets($sock);
                        if($debug) {echo "Opening up socket to $mailers[$n]... Succes!\n";}
                        stream_set_timeout($sock, 30);
                        $meta = stream_get_meta_data($sock);
                        if($debug) { echo "$mailers[$n] replied: $response\n";}
                        $cmds = array(
                            "HELO $helo_address",
                            "MAIL FROM: <$probe_address>",
                            "RCPT TO: <$email>",
                            "QUIT",
                        );
                        # Hard error on connect -> break out
                        # Error means 'any reply that does not start with 2xx '
                        if(!$meta['timed_out'] && !preg_match('/^2\d\d[ -]/', $response)) {
                            $error = "Error: $mailers[$n] said: $response\n";
                            break;
                        }
                        foreach($cmds as $cmd) {
                            $before = microtime(true);
                            fputs($sock, "$cmd\r\n");
                            $response = fgets($sock, 4096);
                            $t = 1000*(microtime(true)-$before);
                            if($debug) {echo htmlentities("$cmd\n$response") . "(" . sprintf('%.2f', $t) . " ms)\n";}
                            if(!$meta['timed_out'] && preg_match('/^5\d\d[ -]/', $response)) {
                                $error = "Unverified address: $mailers[$n] said: $response";
                                break 2;
                            }
                        }
                        fclose($sock);
                        if($debug) { echo "Succesful communication with $mailers[$n], no hard errors, assuming OK";}
                        break;
                    } elseif($n == $total-1) {
                        $error = "None of the mailservers listed for $domain could be contacted";
                    }
                }
            } elseif($total <= 0) {
                $error = "No usable DNS records found for domain '$domain'";
            }
        }
    } else {
        $error = 'Address syntax not correct';
    }
    if($debug) { echo "</pre>";}
    
    if($return_errors) {
        # Give back details about the error(s).
        # Return FALSE if there are no errors.
        if(isset($error)) return htmlentities($error); else return false;
    } else {
        # 'Old' behaviour, simple to understand
        if(isset($error)) return false; else return true;
    }
}
	$dbconn = mysql_connect(SQL_WWWHOST,SQL_WWWUSER,SQL_WWWPASS);


		



function form() {
		echo '
<HTML>
<head>
<LINK REL=StyleSheet HREF="style.css" TYPE="text/css" MEDIA=screen>
</head>
<body>
		<h1>Create your own Account</H1><BR>
		<form action="inc_create.php?action=create&results=do"  name="createform" method="post">
		<table>
			<tr>
				<td>Account:</td>
				<td><input name="login" type="text" /></td>
			</tr>
			<tr>
				<td>Password:</td>
				<td><input name="password" type="password" /></td>
			</tr>
			<tr>
				<td>Confirm:</td>
				<td><input name="password2" type="password" /></td>
			</tr>
			<tr>
				<td>Email:</td>
				<td><input name="email" type="text" /></td>
			</tr>
			<tr>
				<td>Account Type: </td>
				<td><select name="flag" ><BR/>
					<option value="2">Wrath of The Lich Ling</option>
					<option value="1">Burning Crusade</option>
					<option value="0">Classic  Account</option>
					</select>
				</td>
			</tr>
			<!---<tr>
				<td>&nbsp;</td>
				<td><img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" /></td>
			</tr> 
			<tr>
				<td>Security Code:</td>
				<td><input name="security_code" type="text" /></td>
			</tr>  --->

			<tr>
				<td>&nbsp;</td>
				<td><input name="submitform" type="submit" value="Create Me!" /></td>
			</tr>
			
			<tr>
				<td>&nbsp;</td>
				<td>By creating an account, you agree that:<br>• You have read the Server Rules <br>• You accept all responsibility to follow the rules and regulations<br>• You will be responsible to check the rules frequently<br><br>Not knowing the rules can not serve as an excuse to violate them nor will save you any punishments should you do break any of them.</td>
			</tr>
		</table>
		</form>';
 
} //end form()

function create() {
	form();
	global $dbconn;
	
	if(count($_POST) > 0) {
		$values = $_POST;
	} elseif(count($_GET) > 0) {
		$values = $_GET;
	} else {
		$values = array();
	} 
	if(count($values) == 0) {
		echo "No data submitted!";
	} else {

		$login = $values['login'];
		$password = $values['password'];
		$password2 = $values['password2'];
		$email = $values['email'];
		$flag = $values['flag'];
		
		$logindb = "realmd";
		
		$checkacct_q = "
							select username 
							from $logindb.account 
							where 
							username = '$login'";
				
		$checkacct_query = mysql_query($checkacct_q, $dbconn)or die(mysql_error());
		$ip = $_SERVER['REMOTE_ADDR'];
		if(mysql_num_rows($checkacct_query) > 0) {
			$failreason = "Account Exists";
			echo "Sorry, but that account name is already in use.  Please correct your submission and try again.<BR>";
			echo 'You submitted:<BR>Login: '.$login.'<BR>';
		} elseif($password != $password2) {
			$failreason = "password missmatch";
			echo "Sorry, but your passwords did not match.  Please correct your submission and try again.<BR>";
			echo 'You submitted:<BR>Login: '.$login.'<BR>Password: '.$password.'<BR>Confirm:  '.$password2.'<BR>';
		} elseif(validateEmail($email, true) == FALSE) {
			$failreason = "bad email";
			echo "Sorry, but we couldn't contact your email server.  Please correct your submission and try again.<BR>";
			echo 'You submitted:<BR>Email: '.$email.'<BR>';
		} /* elseif($_SESSION['security_code'] != $_POST['security_code'] || empty($_SESSION['security_code'])) {
			$failreason = "bad captcha";
			echo "Sorry, the security code you entered was incorrect.  Please correct your submission and try again.<BR>";
			echo 'You submitted:<BR>Security Code: '.$_POST['security_code'].'<BR>'; 
		}*/ elseif(preg_match("![^0-9A-Za-z\s]!", $login) > 0) {
			$failreason = "bad account name";
			echo "Sorry, the account name you entered includes invalid characters.  Please correct your submission and try again.<BR>";
			echo 'You submitted:<BR>Login: '.$login.'<BR>';
		} else {
					
			$create_q = "
				INSERT INTO $logindb.`account` (
										`id` ,
										`username` ,
										`sha_pass_hash` ,
										`last_ip` ,
										`email` ,
										`expansion`
							)VALUES(
										NULL ,
										'$login',
										SHA1(CONCAT(UPPER('$login'),':',UPPER('$password'))),
										'$ip',
										'$email',
										'$flag');";
// for encrypted password:  			SHA1(CONCAT(UPPER('$login'),':',UPPER('$password'))),

			$create_query = mysql_query($create_q, $dbconn)or die(mysql_error());

			$checkacct2_q = "
							select id, username 
							from $logindb.account 
							where 
							username = '$login'";
				
			$checkacct2_query = mysql_query($checkacct2_q, $dbconn)or die(mysql_error());
			if(mysql_num_rows($checkacct2_query) > 0) {
				$checkacct2 = mysql_fetch_array($checkacct2_query);
				$acct=$checkacct2['id'];				
				$log_q = "
							INSERT INTO `session`.`create_log` (
							`id` ,
							`acct` ,
							`login` ,
							`timestamp` ,
							`ip` 
							)
							VALUES (
							NULL , '$acct', '$login', NOW() , '$ip'
							);";
				$log_query = mysql_query($log_q, $dbconn)or die(mysql_error());
	
			} // end validation if
			mysql_close($dbconn); 			
		}
	}
} //end create

if($_GET['results'] == "do") {
	create();
} else {
	form();
}



//SWITCHES


?>
 
Ohne deinen Code gelesen zu haben, was hindert dich daran per headers_sent zu schauen, wo welche Header bereits gesendet wurden?
 
mich hindert ... das wissen das sowas existiert und ich weiß nicht wie ich das einsetzen muss :(
 
Zuletzt bearbeitet:
Na dann ists ja kein Problem :)
Wenn du z. B. die Beispielfunktion von php.net nimmst dürftest du verstehen wie das funktioniert.
Ansonsten weißte ja wie du das Forum findest ;)
 
Zuletzt bearbeitet:
naja habs gelöst ... hatte mit der funktion form() schon html code erzeugt -> keine weiteren header ...
benutze jetzt javascript zum weiterleiten.
 
Falls du in Zukunft öfters auf das Problem, nicht zu wissen wie man welche php-methode einsetzt, stoßen solltest empfehle ich dir auf php.net die Dokumentation zu php herunterzuladen. Die Hilfedatei (chm-Datei) hat eine Volltext- und Indexsuche die einem sehr hilfreich sein kann ;)
 
Weiterleitung ist ganz einfach, egal ob schon header gesendet wurde und ob javascript aktiviert ist.
eine php function erstellen mit
weiterleitung($zeit, $url){
echo "<meta http-equiv='refresh' content='" . $zeit . "; URL= " . $url . "'>";
}
direkte weiterleitung würde dann einfach mit
<?php
weiterleitung(0,www.forumbase.de)
?>
funktionieren.
Man kann natürlich auch immer
<meta http-equiv="refresh" content="0;url=www.forumbase.de">
schreiben, aber ich finde
weiterleitung(0,www.forumbase) einfacher und verhindere so Syntaxfehler. desweiteren finde ich den Code lesbarer.
solche funktionen schreibe ich normalerweise immer in myfunc.php, die dann von jeder meiner php seiten includet werden. So das ich von überall darauf zugreifen kann. Geht natürlich nicht bei Forms, die schon daten beinhalten.
 
Zuletzt bearbeitet:
Mal davon abgesehen, dass man das meta-refresh nicht benutzen sollte, weil man die Funktion der Zurück-Schaltfläche beeinträchtigt, wäre es angebrachter den Grund des Problems zu beheben, statt dessen Symptome.
Oder kaufst dir dir immer ein neues Auto, wenn dein Aschenbecher voll ist?
 
Zurück
Oben