PHP - Validieren von Benutzereingaben
Aus Wikizone
Beispielfunktionen für die Validierung in PHP[Bearbeiten]
Quelle: http://www.phpbuddy.eu/emails-mit-php-versenden.html?start=1 2012-03
<?php
header( 'Content-Type: text/html; charset=utf-8' );
// Benutzereingabe bereinigen (trimmen, Slashes entfernen)
function cleanInput()
{
checkInjection();
if (get_magic_quotes_gpc()) $_POST = array_map( 'stripslashes', $_POST );
$_POST = array_map( 'trim', $_POST );
}
// Name auf Gültigkeit prüfen
function checkName( $name )
{
$muster_name = '/^([a-zA-ZäÄöÖüÜß\xc0-\xc2\xc8-\xcf\xd2-\xd4\xd9-\xdb\xe0-\xe2\xe8-\xef\xf2-\xf4\xf9-\xfb\x9f\xff\.\'\-_]?(\s)?)+$/';
if (preg_match( $muster_name, $name ))
{
return $name;
}
else
{
die( 'Der eingegebene Name enthält nicht erlaubte Zeichen!' );
}
}
// Email auf korrektes Format prüfen
function checkEmail( $email )
{
$nonascii = "\x80-\xff";
$nqtext = "[^\\\\$nonascii\015\012\"]";
$qchar = "\\\\[^$nonascii]";
$normuser = '[a-zA-Z0-9][a-zA-Z0-9_.-]*';
$quotedstring = "\"(?:$nqtext|$qchar)+\"";
$user_part = "(?:$normuser|$quotedstring)";
$dom_mainpart = '[a-zA-Z0-9][a-zA-Z0-9._-]*\\.';
$dom_subpart = '(?:[a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*';
$dom_tldpart = '[a-zA-Z]{2,5}';
$domain_part = "$dom_subpart$dom_mainpart$dom_tldpart";
$pattern = "$user_part\@$domain_part";
$muster_email = "/^{$pattern}$/";
if (preg_match( $muster_email, $email ))
{
return $email;
}
else
{
die( 'Die eingegebene Email-Adresse hat kein gültiges Format!' );
}
}
// Benutzereingaben auf mögliche Injection prüfen
function checkInjection()
{
$email_injection = array( 'bcc:', 'boundary', 'cc:', 'content-transfer-encoding:', 'content-type:', 'mime-version:', 'subject:' );
// Auf potentielle Email Injections prüfen
foreach ($email_injection as $injection)
{
foreach ($_POST as $feld => $inhalt)
{
if (preg_match( "/{$injection}/i", $inhalt ))
{
header( 'location: http://www.google.com/search?hl=en&q=how+to+become+a+better+hacker' );
exit;
}
}
}
return true;
}
?>