Неопределенный индекс, когда данные не введены - PullRequest
0 голосов
/ 21 апреля 2020

Я работаю над v2 регистрации.

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

В любом случае, вот код PHP:

// Initializing variables
$username = "";
$email = "";

$errors = array(); 

// Connect to the database

$conn = mysqli_connect($database['host'], $database['user'],  $database['password'], $database['db'], $database['port']);

$email_show = $_POST['emailshow'];

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // Receive all input values from the form
  $username = mysqli_real_escape_string($conn, $_POST['username']);
  $email = mysqli_real_escape_string($conn, $_POST['email']);
  $email_show = mysqli_real_escape_string($conn, $_POST['emailshow']);
  $password_1 = mysqli_real_escape_string($conn, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($conn, $_POST['password_2']);
  $fname = mysqli_real_escape_string($conn, $_POST['fname']);
  $fname_show = mysqli_real_escape_string($conn, $_POST['fnameshow']);
  $lname = mysqli_real_escape_string($conn, $_POST['lname']);
  $lname_show = mysqli_real_escape_string($conn, $_POST['lnameshow']);
  $sex = mysqli_real_escape_string ($conn, $_POST['sex']);
  $bday = mysqli_real_escape_string($conn, $_POST['bday']);
  $country = mysqli_real_escape_string($conn, $_POST['country']);
  $private_account = mysqli_real_escape_string($conn, $_POST['privateacc']);
  $profile_style = mysqli_real_escape_string($conn, $_POST['profilestyle']);

  // Form validation: ensure that the form is correctly filled ...
  // By adding (array_push()) corresponding error unto $errors array
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if (empty($fname)) { array_push($errors, "Firstname is required"); }
  if (empty($lname)) { array_push($errors, "Lastname is required"); }
  if (empty($sex)) { array_push($errors, "What is your gender?"); }
  if (empty($bday)) { array_push($errors, "When is your birthday?"); }
  if (empty($_POST['country'])) { array_push($errors, "Test"); }
  if ($password_1 != $password_2) {
    array_push($errors, "The two passwords do not match");
  }

HTML вход:

            <div class="box-title"><h1>Sign up</h1></div>
            <div class="required-fields"><em>- Required fields are marked with *</em></div>
              <div class="account-wrapper">
                  <div class="account-title">YOUR ACCOUNT</div>
                    <form method="post" class="accountform" action="/sign-up">
                       <input type="text" placeholder="Username*" name="username" onfocus="showDesc1()">
                       <div id="desc1">How others will see you <i id="close" onclick="closeDesc1()" class="fas fa-times-circle"></i></div>
                       <input type="email" placeholder="Email*" name="email" onfocus="showDesc2()">
                       <div id="desc2">We need this for important use <i id="close" onclick="closeDesc2()" class="fas fa-times-circle"></i><br><a style="color: blue;"> Read more (soon)</a></div>
                       <div id="emailshow"><input type="checkbox" id="emailshow-input" name="emailshow" value="showemail"><label style="text-decoration: underline;" data-tooltip="When this option is enabled, other users will be able to see your email on your profile." for="emailshow-input">Show on profile</label></div>
                       <input id="passwordfield" type="password" placeholder="Password*" name="password_1">
                       <div onclick="passwordVisb()" class="visb-innerhtml"><i id="visbcon" class="fas fa-eye"></i><label style="cursor: pointer;" id="visb-innerhtml"> Show password</label></div>
                       <input type="password" placeholder="Confirm password*" name="password_2" onfocus="showDesc3()">
                       <div id="desc3">Remember the entered password? <i id="close" onclick="closeDesc3()" class="fas fa-times-circle"></i></div>
                       </div>
                    </div>
                       <div class="details-wrapper">
                         <div class="details-title">YOUR DETAILS</div>
                           <div class="details-fields1">
                             <input type="text" placeholder="Firstname*" name="fname" onfocus="showDesc4()">
                             <div id="desc4">Your firstname <i id="close" onclick="closeDesc4()" class="fas fa-times-circle"></i></div>
                             <div id="fnameshow"><input type="checkbox" id="fnameshow-input" name="fnameshow" value="1"><label style="text-decoration: underline;" data-tooltip="When this option is enabled, other users will be able to see your firstname on your profile." for="fnameshow-input">Show on profile</label></div>
                             <input type="text" placeholder="Lastname*" name="lname" onfocus="showDesc5()">
                             <div id="desc5">Your lastname  <i id="close" onclick="closeDesc5()" class="fas fa-times-circle"></i></div>
                             <div id="lnameshow"><input type="checkbox" id="lnameshow-input" name="lnameshow" value="1"><label style="text-decoration: underline;" data-tooltip="When this option is enabled, other users will be able to see your lastname on your profile." for="lnameshow-input">Show on profile</label></div>
                           <div class="gendersec">
                             <input id="genm" type="radio" name="sex" value="male">
                             <label for="genm">Male</label>
                             <input id="genf" type="radio" name="sex" required value="female">
                             <label for="genf">Female</label>
                             <input id="genc" type="radio" name="sex" value="custom">
                             <label for="genc" style="text-decoration: underline;" data-tooltip="Select this option if you do not want to tell us what your gender is or if you do have another gender not listed here." data-tooltip-location="top">Custom</label>
                           </div>
                             <input type="text" onkeypress="return false;" name="bday" autocomplete="off" placeholder="Birthday*" id="birthdaypicker">
                         </div>
                          <div class="details-fields2">
                            <?php include_once 'C:/xampp2/htdocs/includes/lang-select.php' ?>
                            <!-- <div id="tags-input">
                              <span>Socialhub</span>
                               <input type="text" disabled value="" placeholder="Interests (coming soon)">
                            </div> !-->
                            <p style="color: orange;">More options coming soon!</p>
                          </div>
                          </div>
                         <div class="settings-wrapper">
                           <div class="settings-title">QUICK SETTINGS</div>
                             <div class="settings-fields1">
                               <input type="checkbox" id="privateacc-input" name="privateacc" value="privateacctrue"><label for="privateacc-input" style="text-decoration: underline;" data-tooltip="If you enable this option, then the content of your account will be hidden for other users (they can still visit your account but they can't see the content). From your profile picture to your latest post will be hidden.">Private account</label>
                               <select class="profilestyle" name="profilestyle">
                                 <option selected disabled>Select a style for your profile...</option>
                                 <option value="default">Default (orange & green)</option>
                                 <option value="red">Red</option>
                                 <option value="black">Black</option>
                                 <option disabled>These are coming soon for sure, stay tuned!</option>
                                 <option disabled>Yellow</option>
                                 <option disabled>Blue</option>
                                 <option disabled>Pink</option>
                                 <option disabled>...</option>
                                </select>
                               <p style="margin-top: 50px; color: orange;">More settings coming soon!</p>
                            </div>
                         </div>
              <div class="bottom-wrapper">
                <div class="bottom-topframe">
                   <a href="/" class="btn-back"><i class="fas fa-arrow-left"></i> Nevermind!</a>
                   <div class="agree-wrapper">
                     <input type="checkbox" id="agreetos-input" name="agreetos" value="tosagreed" onchange="document.getElementById('btnsubmit_reg').disabled = !this.checked;"><label for="agreetos-input">I agree with the Terms of Service (coming soon)</label>
                     <input type="checkbox" id="verifyage-input" name="verifyage" value="ageverified"><label for="verifyage-input">I am 13 years or older</label>
                    </div>
                    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
                    <button type="submit"  disabled name="reg_user" id="btnsubmit_reg" class="btnsubmit_reg">Sign up</button>
                </div>

Спасибо уже. (Извините за поиск, большая форма)

Ответы [ 2 ]

0 голосов
/ 21 апреля 2020

Это поможет вам, и, как @Moayad. AlMoghrabi сказал, что вы действительно должны использовать лучшую безопасность, даже если она локальная. Научитесь всегда писать безопасный код.

$email = mysqli_real_escape_string($conn, $_POST['email']);

$email = isset($_POST['email']) ? mysqli_real_escape_string($conn, $_POST['email']) : '';

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

0 голосов
/ 21 апреля 2020

Я рекомендую вам исправить эту проблему и обеспечить большую безопасность, так как этот код можно легко использовать в Mysql Injection . Вы должны экранировать все значения из POST, затем вы должны проверить, если пусто, задайте значения по умолчанию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...