2013-12-05 2 views
0

Я понимаю, что это может быть вопрос Noob, но я прочитал более 40 сообщений, и я до сих пор не мудрее о том, где и, возможно, даже о том, как дезинфицировать вывод из формы, которую я прикрепляю.Обработка PHP-формы

Я нашел следующий код (я адаптировал его под свою форму). Я видел здесь так много разных способов санирования вклада, что я сейчас полностью запутался. Является ли следующее дезинфекция или нет? Javascript в html-части, похоже, не проверяет. первых, это HTML часть, я раздели все биты я полностью понять, но извиняться за долготу:

 <script type="text/javascript"> 

    function validate(form) { 
     fail = validateContactname(form.Contactname.value) 
     fail += validateTelephonenumber(form.Telephonenumber.value) 
     fail += validateEmailaddress(form.Emailaddress.value) 
     fail += validateBoxwidtha(form.Boxwidtha.value) 
     fail += validateBoxdepthb(form.Boxdepthb.value) 
     fail += validateBoxheightc(form.Boxheightc.value) 
     fail += validateContents(form.Contents.value) 
     fail += validatePrinting(form.Printing.value) 
     fail += validateFinishing(form.Finishing.value) 
     fail += validateBoxquantity1(form.Boxquantity1.value) 
     fail += validateBoxquantity2(form.Boxquantity2.value) 
     fail += validateBoxquantity3(form.Boxquantity3.value) 
     fail += validateBoxquantity4(form.Boxquantity4.value) 
     if (fail == "") return true 
     else { alert(fail); return false } 
    } 
    </script> 


    </head> 
    <body> 

<form method="post" action="test_rb.php" onSubmit="return validate(this)"> 

    <div id="contact-form"> 

     <div class="contact-form-sections"> <!-- Start of contact details section --> 
      <div class="contact-form-sections-headings"> 
      Please supply your contact details</div> 
     <br /> 
     Your Contact Name (required) <br />  
     <input name="Contactname" type="text" size="30" maxlength="35" required/><br /><br /> 

     Your Telephone number (required) <br />   
     <input name="Telephonenumber" type="text" maxlength="15" required/><br /><br /> 

     Your e-mail address (required) <br />   
     <input name="Emailaddress" type="text" size="30" maxlength="55" required/><br /><br /> 


     </div> 

     </div><!--end of container/wrapper div --> 
    <script> 
function validateContactname(field) { 
    if (field == "") return "No Contactname was entered.\\n" 
    return "" 
} 

function validateTelephonenumber(field) { 
    if (field == "") return "No Telephone was entered.\\n" 
    else if (field.length < 5) 
     return "Telephone Numbers must be at least 10 numbers long.\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Only numbers allowed in Telephones Numbers.\n" 
    return "" 
} 

function validateEmailaddress(field) { 
    if (field == "") return "No Email Address was entered.\\n" 
     else if (!((field.indexOf(".") > 0) && 
       (field.indexOf("@") > 0)) || 
       /[^[email protected]_-]/.test(field)) 
     return "The Email address is invalid.\\n" 
    return "" 
} 

function validateBoxwidtha(field) { 
    if (field == "") return "No Box Width was entered.\\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Box width should only contain numbers.\\n" 
    return "" 
} 

function validateBoxdepthb(field) { 
    if (field == "") return "No Box Width was entered.\\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Box depth should only contain numbers.\\n" 
    return "" 
} 

function validateBoxheightc(field) { 
    if (field == "") return "No Box Height was entered.\\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Box Height should only contain numbers.\\n" 
    return "" 
} 

<!-- No text is required in the Contents field --> 
<!-- No text is required in the Printing field --> 
<!-- No text is required in the Finishing field --> 

function validateBoxquantity1(field) { 
    if (field == "") return "No Quantity was entered.\\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Box Height should only contain numbers.\\n" 
    return "" 
} 

function validateBoxquantity2(field) { 
    if (field == "") return "No Quantity was entered.\\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Box Quantity should only contain numbers.\\n" 
    return "" 
} 

function validateBoxquantity3(field) { 
    if (field == "") return "No Quantity was entered.\\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Box Quantity should only contain numbers.\\n" 
    return "" 
} 

function validateBoxquantity4(field) { 
    if (field == "") return "No Quantity was entered.\\n" 
    else if (/[^0-9_-]/.test(field)) 
     return "Box Quantity should only contain numbers.\\n" 
    return "" 
} 
</script> 




</body> 
</html> 

Следующие PHP работает, но, кажется, не Санируйте. Кроме того, я не могу больше добавить проверку ошибок, поскольку она затем падает.

<?php 
$to = '[email protected]' ; 
$from = $_REQUEST['Emailaddress'] ; 
$contactname = $_REQUEST['Contactname'] ; 
$headers = "From: $from"; 
$subject = "Box Quote Request"; 


// Checks to see if anything has been typed into the form 
// and calls the fix_string function to sanitize the input 
if (isset($_POST['Contactname'])) 
    $Contactname = fix_string($_POST['Contactname']); 
if (isset($_POST['Telephonenumber'])) 
    $Telephonenumber = fix_string($_POST['Telephonenumber']); 
if (isset($_POST['Emailaddress'])) 
    $Emailaddress = fix_string($_POST['Emailaddress']); 
if (isset($_POST['Boxwidtha'])) 
    $Boxwidtha = fix_string($_POST['Boxwidtha']); 
if (isset($_POST['Boxdepthb'])) 
    $Boxdepthb = fix_string($_POST['Boxdepthb']); 
if (isset($_POST['Boxheightc'])) 
    $Boxheightc = fix_string($_POST['Boxheightc']); 
if (isset($_POST['Contents'])) 
    $Contents = fix_string($_POST['Contents']); 
if (isset($_POST['Printing'])) 
    $Printing = fix_string($_POST['Printing']); 
if (isset($_POST['Finishing'])) 
    $Finishing = fix_string($_POST['Finishing']); 
if (isset($_POST['Boxquantity1'])) 
    $Boxquantity1 = fix_string($_POST['Boxquantity1']); 
if (isset($_POST['Boxquantity2'])) 
    $Boxquantity2 = fix_string($_POST['Boxquantity2']); 
if (isset($_POST['Boxquantity3'])) 
    $Boxquantity3 = fix_string($_POST['Boxquantity3']); 
if (isset($_POST['Boxquantity4'])) 
    $Boxquantity4 = fix_string($_POST['Boxquantity4']); 



//this bit sets the sections of the form and must have an entry for each form element 
$fields = array(); 
$fields{"Contactname"} = "Contact Name"; 
$fields{"Telephonenumber"} = "Telephone Number"; 
$fields{"Emailaddress"} = "Email Address"; 
$fields{"Boxwidtha"} = "Box width or a"; 
$fields{"Boxdepthb"} = "Box depth or b"; 
$fields{"Boxheightc"} = "Box height or c"; 
$fields{"Contents"} = "Contents"; 
$fields{"Printing"} = "Printing"; 
$fields{"Finishing"} = "Finishing"; 
$fields{"Boxquantity1"} = "Box Quantity 1"; 
$fields{"Boxquantity2"} = "Box Quantity 2"; 
$fields{"Boxquantity3"} = "Box Quantity 3"; 
$fields{"Boxquantity4"} = "Box Quantity 4"; 

//this bit prints out each fields title and contents in turn each on new line 
$body = "A quote request:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); } 

//this bit is the stuff that goes to the enquirer 
$headers2 = "From: [email protected]"; 
$subject2 = "Thank you for contacting us"; 
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.website.co.uk/index"; 

//this bit is what shows if there is an error 
if($from == '') {print "We need an email address to be able to contact you, please go back and try again";} 
else { 
if($contactname == '') {print "You have not entered a name, please go back and try again";} 
else { 

//this bit is used if there are no errors 
$send = mail($to, $subject, $body, $headers); 
$send2 = mail($from, $subject2, $autoreply, $headers2); 
if($send) 
{header("Location: http://www.website.co.uk/thank-you-for-quote.html");} 
else 
{print "We encountered an error sending your mail, please notify [email protected]"; } 


} 
} 

function fix_string($string) 
{ 
    $string = stripslashes($string); 
    $string = htmlentities($string); 
    $string = strip_tags($string); 
    return $string 
} 


?> 

Вся помощь с благодарностью получил, я провел в течение недели, пытаясь получить эту работу, и я все еще идет по кругу.

+0

Что вы подразумеваете под «санитаризацией»? – FastTrack

+0

Санизировать для WHAT целевой среды? Это не что-то вроде взрыва дробовика - взрывайте область с помощью гранул и надейтесь, что вы что-то ударили. sanitization/escaping - это то, что должно быть TARGETTED для конкретного использования. –

+0

Hi @FastTrack. Я надеялся, что функция fix_string будет вызвана и что это сделает некоторую очистку и предотвратит хотя бы некоторые попытки отправки спама через сайт, когда он идет вживую. Я понимаю, так много читаю здесь, что это обширный предмет, и что, будучи новичком в PHP, я только смогу сделать простейший из вещей на данный момент. – user3067188

ответ

Смежные вопросы