Bazaar – php example code – part 12 – CAPTCHA login hardening

Article focus on implementation of CAPTCHA with tools available in PHP. Separate script generate randomly rotated and by scratches and lines distorted text consist from 6 alphanumeric characters stored in a picture. Also provide hash of generated pass_phrase stored in session variable. Login page read text from verification field, hash them and compare against value stored in session. If password and captcha pass_phrases are as expected. User is validated as logged in user.

Expectation from CAPTCHA hardened login

CAPTCHA (/kæp.tʃə/, a contrived acronym for „Completely Automated Public Turing test to tell Computers and Humans Apart“) is a type of challenge–response test used in computing to determine whether or not the user is human. ( as is is mentioned in wiki, 25.12.2020).

Most common way how to implement captcha verification, is generating human readable picture containing alphanumeric characters that are displayed on pages with some type of prompt for a data. Our login page expect login name and password, rouge system (robot) can attempt for brute force access gain. Inserting third field for retyping code from provided image is a way how to eliminate automatized mechanism for gaining page access.

Our expectation from way how it will be implemented are:

  • simple CAPTCHA image generation only with resource available in PHP code
  • generated CAPTCHas must be hardly readable by captcha OCR software (image rotation, scratches, ping or red color text, random lines)
  • main captcha code stored separately from login or other pages implementing them
  • way how to delete used captcha images
  • quick implementation on login page without large code retyping

Captcha image is implemented in frontpage of login as it display next image.

Captcha verification on login page

If user type incorrect text, error message is displayed along with new CAPTCHA image as it is shown on next picture.

captcha.php generating code

Our CAPTCHA images generating ode is stored in separate script. This approach enable further improvements and transfer into other applications.

Leading part of code enable define dimensions of generated image, next variety of alphanumeric characters included in to a code and number of them in one image.

<!– ***************************************************************** –>
<!– PHP  code generating verification captcha image                                      –>
<!– ***************************************************************** –>
<!– Vrsion: 1.0        Date: 8. – 9.11.2020 by CDesigner.eu                                  –>
<!– ***************************************************************** –>

<?php
    //require_once(‚appvars.php‘); // including variables for database
    
    // if included whole not necessary session_start(); // start the session – must be added on all pages for session variable accessing

    // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
    /*if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
        if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
            $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
            $_SESSION[‚username‘] = $_COOKIE[‚username‘];
            $_SESSION[‚user_role‘] = $_COOKIE[‚user_role‘]; // added for role
        }
     } */
     
     // important captcha constants
     define(‚CAPTCHA_NUMCHARS‘, 6); // number of charakters in CAPTCHA
     define(‚CAPTCHA_WIDTH‘, 200); // width of image
     define(‚CAPTCHA_HEIGHT‘, 60); // height of image
     // Set Correct Path to Font File
     $fontPath=’C:\xampp_7_4_2020\htdocs\bazaar\images\courier_new_bold.ttf‘; 

     // generating passphrase by random numbers
     $pass_phrase = „“;
     for($i = 0; $i < CAPTCHA_NUMCHARS; $i++ ) {
        $pass_phrase .= chr(rand(97, 122));
     }

     // store the encryption pass-phrase in a session variable
     $_SESSION[‚pass_phrase‘] = sha1($pass_phrase);

     //create the image
     $img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT);

     //set a white background with black text and gray graphics
     $bg_color = imagecolorallocate($img, 255, 255, 255); //white
     $text_color = imagecolorallocate($img, 255, 146, 130); //pale red
     $graphic_color = imagecolorallocate($img, 64, 64, 64); //darkgray
     $graphic_color_noise_red = imagecolorallocate($img, 255, 128, 128); //red noise pattern
     $graphic_color_noise_green = imagecolorallocate($img, 128, 255, 128); //green noise pattern

     // fill the background
     imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color);

     // image edges rectangle drawing 
     imagerectangle ( $img , 0 , 0, CAPTCHA_WIDTH -1  , CAPTCHA_HEIGHT -1 , $graphic_color  );

     //draw some random lines
     for($i = 0; $i < 5; $i++) {
         imageline($img,0, rand() % CAPTCHA_HEIGHT, CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, $graphic_color);
     }
     
     //sprinkle in some random green dots
     for($i = 0; $i < 1000; $i++) {
        imagesetpixel($img, rand() % CAPTCHA_WIDTH,  rand() % CAPTCHA_HEIGHT, $graphic_color_noise_green);
    } 

    // draw the pass-phrase string
    imagettftext($img, 36, rand(0,10), rand(0, 12) , CAPTCHA_HEIGHT – rand(-5, 5), $text_color, $fontPath, $pass_phrase);

    //sprinkle over in some random dots
    for($i = 0; $i < 1000; $i++) {
        imagesetpixel($img, rand() % CAPTCHA_WIDTH,  rand() % CAPTCHA_HEIGHT, $graphic_color_noise_red);
    } 
    

    // VERY IMPORTANT: Prevent any Browser Cache!! – older approach send by header
    // header(„Cache-Control: no-store, 
    //no-cache, must-revalidate“);  

    // output the image as PNG using a header;
    /* ob_clean(); 
    header(„Content-type: image/jpg“);
    imagejpg($img);*/
    // creating filename and sending them through session and variable

    $imageCaptchafilename = IMAGE_PATH . „captcha“.rand(1,1000).“.png“;
    // debug echo $imageCaptchafilename;
    $_SESSION[‚imageCaptchafilename‘] = $imageCaptchafilename;
    //writting image to png
    imagepng($img, $imageCaptchafilename, 5);

    //clean up
    imagedestroy($img);

 ?>    

Example of generated image for closer look follows

Improved login page with CAPTCHA

Link to generated CAPTCHA image and pass_phrase is available in session variables for login page scripts.

Existing form code is extended for verification field and is followed by CAPTCHA image. After unsuccessfully retyped code, error message is displayed formatted with bootstrap danger style.

Al parts implementing CAPTCH in login page are marked by orange for better understanding and distinguishing them from other text.

<!– ****************************************************************** –>
<!– PHP „self“ code handling login into the bazaar app                                   –>
<!– ****************************************************************** –>
<!– Vrsion: 1.0        Date: 11.10-24.10.2020 by CDesigner.eu                             –>
<!– ****************************************************************** –>

<?php
 require_once(‚appvars.php‘); // including variables for database
 require_once(‚captcha.php‘); // including generator of captcha image
 session_start(); // start the session
   
 // two variables for message and styling of the mesage with bootstrap
 $msg = “;
 $msgClass = “;
 $usr_username = “;
 $usr_passwd = “;

 $verified_human_by_CAPTCHA = -1; //

//get info that user is loged in, if not try it looking at cookies
//if(!isset($_COOKIE[‚s‘])) { old solution with cookies
  if(!isset($_SESSION[‚users_id‘])) { //new with session variables
    if(isset($_POST[‚submit‘])) {
        /* Attempt MySQL server connection.  */
             $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
             
                // accessing user entered login data
             $usr_username = htmlspecialchars($_POST[‚u_name‘]);    
             $usr_passwd = htmlspecialchars($_POST[‚u_pass‘]);

             //implement CAPTCHA pass-phrase verification
    
            $user_pass_phrase = sha1(htmlspecialchars($_POST[‚verify‘]));
            $pass_phrase_now = htmlspecialchars($_POST[‚pass_phrase_now‘]);
            $imageCaptchafilename_now = htmlspecialchars($_POST[‚imageCaptchafilename_now‘]); // name of current captcha photo file for deletion after usage
             
            if($pass_phrase_now == $user_pass_phrase) {
              $verified_human_by_CAPTCHA = 1;
              @unlink($imageCaptchafilename_now); // delete captcha file
                //debug echo „captcha ok“;
        
            } else {
              $verified_human_by_CAPTCHA = 0;
              @unlink($imageCaptchafilename_now); // also delete captcha file because new one was created
              $msgClass = ‚alert-danger‘;
              $msgCAPTCHA = „Your CAPTCHA was written wrong, please correct it and resend.“;
            }; 

             if(!empty($usr_username) && !empty($usr_passwd) && $verified_human_by_CAPTCHA) {
              // try lookup user database
              $usr_passwd_SHA = sha1($usr_passwd);
              $sql = „SELECT users_id, username, user_role FROM bazaar_user WHERE username = „.“‚$usr_username'“. “ AND pass_word = „.“‚$usr_passwd_SHA'“ ;
              // debug output echo  $usr_username; 
              // echo  $usr_passwd;
              //echo $usr_passwd_SHA;
              $data = mysqli_query($dbc, $sql);   
              
              if(mysqli_num_rows($data) == 1) {
                  // login is ok, set user  ID and username cookies and redirect to the homepage
                  $row = mysqli_fetch_array($data);
                  //setcookie(‚users_id‘, $row[‚users_id‘]); old solution with cookies
                  //setcookie(‚username‘, $row[‚username‘]);
                  $_SESSION[‚users_id‘] = $row[‚users_id‘]; // sloution with sessions
                  $_SESSION[‚username‘] = $row[‚username‘];
                  $_SESSION[‚user_role‘] = $row[‚user_role‘]; // added user_role session variable
                  // new cookies for login persistency that expires after 30 days without logout combination SESSION with COOKIES is awailable
                  setcookie(‚users_id‘, $row[‚users_id‘], time()+(60+60*24*30));
                  setcookie(‚username‘, $row[‚username‘], time()+(60+60*24*30));
                  setcookie(‚user_role‘, $row[‚user_role‘], time()+(60+60*24*30)); // cookie for user_role of loged in user added

                  $home_url = ‚http://‘. $_SERVER[‚HTTP_HOST‘] . dirname($_SERVER[‚PHP_SELF‘]) . ‚/index.php‘;
                  header(‚Location:‘. $home_url);

                  // Free result set
                  mysqli_free_result($data);
                  // Close connection
                  mysqli_close($dbc);

              } else  {
                  // urename/ password are incorrect – error meesage is displayed
                  $msg = „Incorrect username or password. Login denied!  „;
                  $msgClass = ‚alert-danger‘;
   
            }     

              
            } else {
                // username/ password were not entered – display error message
                $msg = „Sorry, you must eneter username and password along with correct CAPTCHA phrase to log in. „;
                $msgClass = ‚alert-danger‘;
   
            }     
    }  

?>

<!– **************************************** –>
<!– HTML code containing Form for submitting –>
<!– **************************************** –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar login page  </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
  
</head>
<body>
  <nav class=“navbar „>
      <div class=“container“ id=“header_container_580″>
        <div class=“navbar-header“>  
          <?php
             require_once(‚headerlogo.php‘);
          ?>  
          <a class=“navbar-brand“ href=“index.php“>Bazaar – Login page</a>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  
    <?php if($msg != “): ?>
        <br> 
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
      
      <?php 
            //if(empty($_COOKIE[‚users_id‘])) { solution with cookies
              if(empty($_SESSION[‚users_id‘])) { // solution with sessions
                // only show for if session with name users_id does not exist
                //echo ‚ <br> ‚;
                //echo  ‚<p class=“alert alert-danger“>‘ . $msg . ‚</p>‘;
       ?> 
        
        <br> 
        <img id=“calcimage“ src=“./images/login.png“ alt=“bazaar image“ width=“150″ height=“150″>
        <br>

        <form  method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
           <div id=“login“>
                <legend> Log In <legend>
                <label>Username:</label>
                    <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚u_name‘]) ? “ : “; ?>'“ name=“u_name“ class=“form-control“ value=“<?php echo isset($_POST[‚u_name‘]) ? ‚Please reenter‘ : ‚Login name‘; ?>“>

                    <label>Password:</label>
                    <input type=“password“ onfocus=“this.value='<?php echo isset($_POST[‚u_pass‘]) ? “ : “; ?>'“ name=“u_pass“ class=“form-control“ value=“<?php echo isset($_POST[‚u_pass‘]) ? ‚Please reenter‘ : ‚Login name‘; ?>“>

                    <label for=“verify“>Verification – enter text from image below:</label>
                    <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚verify‘]) ? “ : “; ?>'“ name=“verify“ class=“form-control“ value=“<?php echo isset($_POST[‚verify‘]) ? “ : ‚Enter the CAPTCHA verify code‘; ?>„>
                    <br>

                    <?php if(($verified_human_by_CAPTCHA == 0) ): //error messaging if wrong CAPTCHA?>
                    <br> 
                    <div class=“alert <?php echo $msgClass; ?>“><?php echo $msgCAPTCHA; ?></div>
                    <?php endif; ?> 

                    <center> <img src=“<?php echo $imageCaptchafilename ; ?>“ alt=“Verification pass-phrase“ > </center> 
                    <!– ass a hidden is sent sha actualy generated captcha pass-phrase only this way it is producet in same run –>
                    <input type=“hidden“ name=“pass_phrase_now“ value=“<?php echo sha1($pass_phrase); ?>“ />
                    <!– as a hidden is sentname of captcha file for deletion after use –>
                    <input type=“hidden“ name=“imageCaptchafilename_now“ value=“<?php echo $imageCaptchafilename; ?>“ />
            </div>
           <input id=“loginsubmitt“ type=“submit“ name=“submit“ class=“btn btn-info“ value=“Log In“> 
           <br>

        </form>

        <?php }  else { 
                 // successfull login
                  // cookie solution echo ‚<p class=“alert alert-success“> You are loged in as ‚ . $_COOKIE[‚username‘]. ‚</p>‘;
                  echo ‚<br>‘;
                  echo ‚<p class=“alert alert-success“> You are loged in as <em>‘ . $_SESSION[‚username‘]. ‚</em></p>‘; // session solution
                  echo ‚<p class=“alert alert-success“> If you will logout or login with anither credentials, please first <a href=“logout.php“>logout!. </a></p>‘;
              } 
        ?>  
      </div>

          
    
    
      <?php  // footer include code
          require_once(‚footer.php‘); // including footer
          generate_footer(580); // function from footer.php for seting width, you can use 580 and 1060px width
        ?>  
 

</body>
</html>

As it was mentioned before we must have way how to signal generated codes for verification, they are stored in session variable as pass_phrase, also image name. Second problem is, how to deleted unused images. Our implementation is simple, but if app run with many connected clients then in a short time can by generated many pictures. There is small posibility for generate one with same numbering part. Wider number is for consideration, also new problems will arisen in heavy loads that we must take in mind.

Conclusion

CAPTCHA verified login provide new level of security for gaining access to our application. Please keep in mind, that verification user and distinguishing them for automatized scripts is now a must have thing. It is a bare minimal for supporting basic level of security for today apps.

Full code of our bazaar education project can be obtained from github here.




Bazaar – php example code – part 11 – profile page for user

Our article focus on way how all logged in users can maintain accurate information about themselves. Profile page will contain data fully adjustable by logged in user and can display data fully accessible only in time of subscribing or next maintainable by site admin.

Expectation from edit profile page

Way how to maintain user profile information accurate is to enable to user maintain it by themselves. This function can be implemented by edutprofile.php form. From this form we expect these functionalities:

  • table display all currently provided information
  • some information was obtained during registration process but some must be provided later (finer info about current city of living, streeet, avatar photos etc.)
  • output display also un editable part of data as registration e-mail or users ID and name – these information will be editable in some manner only for administrator of page
  • from must be visually attractive and must be able display selected avatar photo
  • latest part must enable change user password

editprofile.php code

Next part of page display code of editprofile.php page. Interesting part of from input element is this:

 <div id=„frame_gray“>
              <label> Your registered with these credentials. They cannot be changed, only way how to obtain new is deleting account asking page admin and create new one:</label>
              <label>User ID:</label>
          <input type=“text“  name=“users_id“ class=“form-control“ value=“<?php echo $_SESSION[‚users_id‘]?>“ disabled>
              <br>
              <label>User name:</label>
          <input type=“text“  name=“username“ class=“form-control“ value=“<?php echo $_SESSION[‚username‘]?>“ disabled>
              <br>
              <label>E-mail:</label>
              <input type=“text“  name=“email“ class=“form-control“ value=“<?php echo $email?>“ disabled>
              <br>
            </div>  

DIV element with id=“frame_gray“ link external css style from style.css:

#frame_gray {  padding: 10px;  background-color: rgb(167, 167, 167) ;  border: 1px dotted #616161 ;
}

This approach enable color distinguishing some part of page as it show next picture:

Upper part of editprofile page from Bazaar app

Also in input element of our form we can find new term disabled, this option disable editing option for that element. data are only for read only.

Full code o editprofile.php scrip follows:

<!– ***************************************************************** –>
<!– PHP „self“ code handling user profile editing                                            –>
<!– ***************************************************************** –>
<!– Vrsion: 1.0        Date: 25.10-30.10.2020 by CDesigner.eu                            –>
<!– ***************************************************************** –>

<?php
    require_once(‚appvars.php‘); // including variables for database
  // two variables for message and styling of the mesage with bootstrap
  session_start(); // start the session – must be added on all pages for session variable accessing

  // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
    if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
    if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
      $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
      $_SESSION[‚username‘] = $_COOKIE[‚username‘];
      $_SESSION[‚user_role‘] = $_COOKIE[‚user_role‘]; // added for role
    }
   }
  $msg = “;
  $msgClass = “;

  // default values of auxiliary variables
  $users_id = „“;
  $username = „“;
  $pass_word = „“;
  $nickname= „“;
  $first_name = „“;
  $lastname_name = „“;
  $address = false;
  $city = „“;
  $ZIPcode = „“;
  $email = „“;
    $GDPR_accept = false;
    $rules_accept = false;
    $avatar = „“; // photo location of avatar
    $profile_text = „“;
  $is_result = false; //before hitting submit button no result is available
  
  // Control if data was submitted
  if(filter_has_var(INPUT_POST, ‚submit‘)) {
        // Data obtained from $_postmessage are assigned to local variables
        
        $users_id = $_SESSION[‚users_id‘]; // obtained from login user
        $username = $_SESSION[‚username‘];
        
        $pass_word1 = sha1(htmlspecialchars($_POST[‚pass_word1‘]));
        $pass_word2 = sha1(htmlspecialchars($_POST[‚pass_word2‘]));
        $pass_word_old = sha1(htmlspecialchars($_POST[‚pass_word_old‘]));

      $nickname= htmlspecialchars($_POST[‚nickname‘]);
      $first_name = htmlspecialchars($_POST[‚first_name‘]);
      $lastname_name = htmlspecialchars($_POST[‚lastname_name‘]);
      $addresss = htmlspecialchars($_POST[‚addresss‘]);
      $city = htmlspecialchars($_POST[‚city‘]);
      $ZIPcode = htmlspecialchars($_POST[‚ZIPcode‘]);
      
       // $GDPR_accept = isset($_POST[‚GDPR_accept‘]); // checkbox doesnot send post data, they must be checked for its set state !!!
        isset($_POST[‚rules_accept‘]) ? $rules_accept =“1″: $rules_accept =“0″; // checkbox doesnot send post data, they must be checked for its set state !!!
        isset($_POST[‚GDPR_accept‘]) ? $GDPR_accept =“1″: $GDPR_accept =“0″;
    
        $avatar = htmlspecialchars($_FILES[‚avatar‘][‚name‘]);           // photo location of avatar
        $profile_text = htmlspecialchars($_POST[‚profile_text‘]);
    
        //echo ‚users_id‘; echo $users_id;
        //echo $rules_accept;
        //echo $GDPR_accept;
        //echo $nickname;
    
  

    

    // Controll if all required fields was written
    if( !empty($nickname) && $rules_accept && $GDPR_accept) { // these item identifiers are mandatory and can not be empty
      // If check passed – all needed fields are written
      // Check if E-mail is valid
      //echo $rules_accept;
      //  echo $GDPR_accept;

                
                // move image to /images final folder from temporary download location
        $avatar_target1 = IMAGE_PATH . $avatar;
        

        

           // insert into databse 
                      if (1) {
                         move_uploaded_file($_FILES[‚avatar‘][‚tmp_name‘], $avatar_target1);
              
              // make database connection
              $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
              // Check connection
                if($dbc === false){
                  die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                }
              
              // INSERT new entry
              // need systematic debug!!!  – now it is ok, it can be used as further example  
          
              // example working and tested syntax for UPPDATE query $sql = „UPDATE bazaar_user SET nickname = ‚“.$nickname.“‚,  first_name = ‚“.$first_name.“‚
              //               WHERE   users_id = ‚“.$users_id. „‚ AND username = ‚“.$username.“‚“ ; 

              $sql = „UPDATE bazaar_user SET
                                            nickname = ‚“.$nickname.“‚,
                                            first_name = ‚“.$first_name.“‚,
                                            lastname_name = ‚“.$lastname_name.“‚,
                                            addresss = ‚“.$addresss.“‚,
                                            city = ‚“.$city.“‚,
                                            ZIPcode = ‚“.$ZIPcode.“‚,
                                            write_date = now(),
                                            
                                            GDPR_accept = ‚“.$GDPR_accept.“‚,
                                            rules_accept = ‚“.$rules_accept.“‚,
                                            avatar  = ‚“.$avatar.“‚,
                                            profile_text = ‚“.$profile_text.“‚
                                            

                                            WHERE   users_id = ‚“.$users_id. „‚ AND username = ‚“.$username.“‚“; 

              // . $_POST[‚userid‘] . „‚, first_name='“ . $_POST[‚first_name‘] . „‚, last_name='“ . $_POST[‚last_name‘] . „‚,
              // city_name='“ . $_POST[‚city_name‘] . „‚ ,email='“ . $_POST[‚email‘] . „‚ WHERE userid='“ . $_POST[‚userid‘] . „‚“);
                               
              //show updated user data true
              $is_result = true; 
              if(mysqli_query($dbc, $sql)){
                
                $msg = ‚Profile updated succesfuly. ‚;
                $msgClass = ‚alert-success‘;
              } else {
                
                $msg = „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc);
                $msgClass = ‚alert-danger‘;
                            }
                            // echo „DEBUG – idem k casti s heslom“;            
                            // update password only if both passwords are not emty and are equal and old password match 
                            //pass_word = $pass_word, and only add hash to filed not plane password
                           // $pass_word1 = htmlspecialchars($_POST[‚pass_word1‘]);
                           // $pass_word2 = htmlspecialchars($_POST[‚pass_word2‘]);
                           // $pass_word_old = htmlspecialchars($_POST[‚pass_word_old‘]);
                           //DEBUG – echo $pass_word1;
                           //DEBUG – echo $pass_word2;
                           //DEBUG – echo $pass_word_old;
                           if(isset($pass_word1) && isset($pass_word2) && isset($pass_word_old )){ // old and two input for new password are provided
                            if($pass_word1 == $pass_word2){ // new passwords is ok typed 2x the same
                                // echo „DEBUG – hesla sa rovnaju“; 
                                // obtain old password sha1 for reference
                                $_username = $_SESSION[‚username‘];
                                // echo „DEBUG -username $_username“;
                                $_users_id = $_SESSION[‚users_id‘];
                                //echo “ DEBUG -users_id $_users_id  „;
                                //$sql = „SELECT * FROM bazaar_user WHERE username = „.“‚$_username'“. “ AND users_id = „.“‚$_users_id'“ ;
                                $sql = „SELECT * FROM bazaar_user WHERE username = „.“‚$_username'“.“LIMIT 1″  ;
                                if($output = mysqli_query($dbc, $sql)){
                                    if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                                        
                                        while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                                       
                                                $pass_word_old_stored = $row[‚pass_word‘];
                                                // echo „DEBUG – 0. vo while hash stareho hesla je $pass_word_old_stored  „;
                                                                                     
                                        }
                                        
                                        // Free result set
                                        mysqli_free_result($output);
                                    } else{
                                        echo „Old password can not be obtained.“; // if no records in table
                                    }
                                } else{
                                    echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                                }
                                //echo „DEBUG – 1. hash stareho hesla je $pass_word_old_stored „;
                                //echo „DEBUG – 2. hash stareho zadaneho hesla uzivatelom $pass_word_old) „;
                                if($pass_word_old_stored == $pass_word_old){ // if old pasword provided by user is the same as in database, passwords can be changed
                                //  echo „DEBUG – 3. stare heslo bolo zadane spravne“; 
                                   
                                //  echo „DEBUG – pasword je zmienany na $pass_word1“;
                                    $sql = „UPDATE bazaar_user SET
                                        
                                            
                                            pass_word = ‚“.$pass_word1.“‚
                                   
                                            WHERE   users_id = ‚“.$users_id. „‚ AND username = ‚“.$username.“‚“ ;   
                                    if($output = mysqli_query($dbc, $sql)){
                                        if($output) {  // if any record obtained from SELECT query
                                          //echo „Heslo bolo úspešne zmenené“; 
                                          $msg .= ‚ PASSWORD changed succesfuly. ‚;
                                          $msgClass = ‚alert-success‘;
                                          
                                        } else{
                                            //echo „Password cannot be changed.“; // if no records in table
                                            $msg .= ‚ PASSWORD cannot be changed. ‚;
                                            $msgClass = ‚alert-danger‘;
                                        }
                                    } else{
                                        echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                                    }        

                                }
                            } 
                           
                           }

              // end connection
                mysqli_close($dbc);
                
      
      
            } else {
              // Failed – if not all fields are fullfiled
              $msg = ‚Please fill in all * marked contactform fields – nickname, GDPR and portal rules are mandatory!‘;
              $msgClass = ‚alert-danger‘; // bootstrap format for allert message with red color
                        };
                        
                   
        } else {
          // Failed – if not all fields are fullfiled
          $msg = ‚Please fill in all * marked contactform fields – nickname, GDPR and portal rules are mandatory!‘;
          $msgClass = ‚alert-danger‘; // bootstrap format for allert message with red color
                    };
        
    

  };  
  
  

  
    
?>

<!– **************************************** –>
<!– HTML code containing Form for submitting –>
<!– **************************************** –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar – item for sell  </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
  
</head>
<body>
  <nav class=“navbar „>
      <div id=“header_container_580″>
        <div class=“navbar-header“>  
        <?php  
            require_once(‚headermenu.php‘); // including menu items
        ?>    
         
          <?php /*– older solution only for this page menu if(isset($_SESSION[‚users_id‘])) {  // display different page header along way why is user loged in or not – users_id is set when user is loged in
                  echo  ‚<a class=“navbar-brand“ href=“editprofile.php“>Bazaar – editing personal profile</a>‘;
                } else { 
                  echo  ‚<a class=“navbar-brand“ href=“login.php“>Unauthorized – please Log In </a>‘; 
            }; */
            ?>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  

<!– ***************************************** –>
<!– HTML par available after succesfull login –>
<!– ***************************************** –>    
<?php if(isset($_SESSION[‚users_id‘])) { //if user is loged with users_id then editprofile form is available?> 

    <?php if($msg != “): ?>
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
        
        <br> 
        <img id=“calcimage“ src=“./images/logout.png“ alt=“Edit profile main page icon“ width=“150″ height=“150″>
        <br>

      <?php   //part displaying user_role of loged user
         
          

            echo “ <br> <br>“;
            echo “ <table class=\“table table-success\“> „;
            $user_role = $_SESSION[‚user_role‘];
            $username = $_SESSION[‚username‘];
            echo “ <tr>
                 <td><h5>  User_role of succesfully loged user with name <strong> $username </strong> is <strong>$user_role</strong> . „;    
            
              
            echo “     <td>   </tr> „; 
            echo “ </table> „;
          
          //echo “ <input type=“text“ id=“result_field“ name=“result_field“ value=“$result“  >  <br>“ ;
        
         ?>  

      <form enctype=“multipart/form-data“ method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
      <input type=“hidden“ name=“MAX_FILE_SIZE“ value=“5242880″>
        <div class=“form-group“>

          <?php // here read data from bazar_user table and prefill input fileds with previeously obtained data from user
            $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

                // Check connection
               if($dbc === false){
                 die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
               };
             
             
              
                            $_username = $_SESSION[‚username‘];
                            $_users_id = $_SESSION[‚users_id‘];
              // create SELECT query for category names from database
              $sql = „SELECT * FROM bazaar_user WHERE username = „.“‚$_username'“.“ AND users_id=“.“‚$_users_id'“ ;

              // execute sql and populate data list with existing category in database
              if($output = mysqli_query($dbc, $sql)){
                if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                  
                  while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                  
                                            
                                            $pass_word = $row[‚pass_word‘];
                                            $nickname= $row[‚nickname‘];
                                            $first_name = $row[‚first_name‘];
                                            $lastname_name = $row[‚lastname_name‘];
                                            $addresss = $row[‚addresss‘];
                                            $city = $row[‚city‘];
                                            $ZIPcode = $row[‚ZIPcode‘];
                                            $email = $row[‚email‘];
                                            $gdpr = $row[‚GDPR_accept‘]; // checkbox doesnot send post data, they must be checked for its set state !!!
                                            $rules_accept = $row[‚rules_accept‘];
                                        
                                            $avatar = $row[‚avatar‘];           // photo location of avatar
                                            $profile_text = $row[‚profile_text‘];
                      
                      
                  
                  }
                  
                  // Free result set
                  mysqli_free_result($output);
                } else{
                  echo „There is no category in category table. Please wirite one.“; // if no records in table
                }
              } else{
                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
              }

       
                      // Close connection
                            mysqli_close($dbc);
                    ?>
            <!– these data are only displayed but cannot be changed –>

            <div id=“frame_gray“>
              <label> Your registered with these credentials. They cannot be changed, only way how to obtain new is deleting account asking page admin and create new one:</label>
              <label>User ID:</label>
          <input type=“text“  name=“users_id“ class=“form-control“ value=“<?php echo $_SESSION[‚users_id‘]?>“ disabled>
              <br>
              <label>User name:</label>
          <input type=“text“  name=“username“ class=“form-control“ value=“<?php echo $_SESSION[‚username‘]?>“ disabled>
              <br>
              <label>E-mail:</label>
              <input type=“text“  name=“email“ class=“form-control“ value=“<?php echo $email?>“ disabled>
              <br>
            </div>  
              <br>
              <br>
              
            <div id=“frame_green“>
              <label>Further user data data:</label>
              <br>

              <label>*Nickname:</label>
          <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚nickname‘]) ? $nickname : “; ?>'“ name=“nickname“ class=“form-control“ value=“<?php echo isset($_POST[‚nickname‘]) ? $nickname : $nickname; ?>“>
              <br>
              <label>First name:</label>
          <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚first_name‘]) ? $first_name: “; ?>'“ name=“first_name“ class=“form-control“ value=“<?php echo isset($_POST[‚first_name‘]) ? $first_name : $first_name; ?>“>
              <br>
              <label>Last name:</label>
          <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚lastname_name‘]) ? $lastname_name : “; ?>'“ name=“lastname_name“ class=“form-control“ value=“<?php echo isset($_POST[‚lastname_name‘]) ? $lastname_name : $lastname_name; ?>“>
              <br>
              <label>Adress in form – Street Nr.:</label>
          <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚addresss‘]) ? $addresss : “; ?>'“ name=“addresss“ class=“form-control“ value=“<?php echo isset($_POST[‚addresss‘]) ? $addresss : $addresss; ?>“>
              <br>
              <label>City:</label>
          <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚city‘]) ? $city : “; ?>'“ name=“city“ class=“form-control“ value=“<?php echo isset($_POST[‚city‘]) ? $city : $city; ?>“>
              <br>
              <label>ZIP code in form XXXXX:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚ZIPcode‘]) ? $ZIPcode : “; ?>'“ name=“ZIPcode“ class=“form-control“ value=“<?php echo isset($_POST[‚ZIPcode‘]) ? $ZIPcode : $ZIPcode; ?>“>
              <br>
            </div> 

            <br> 
              <!– GDPR and rule of the portal acceptance –>
            <div id=“frame_red“>
              <div class=“form-group“>
              <label>Acceptation of portal rules and GDPR regulations – IMPORTANT PART:</label>
              <br>
              <br>
            <input type=“checkbox“ name=“GDPR_accept“ class=“form-control“ <?php if($gdpr) { echo „checked“; } ?> >
              <label>* I agree with GDPR regulations</label>
              <br>
              <input type=“checkbox“ name=“rules_accept“ class=“form-control“ <?php if($rules_accept) { echo „checked“; } ?> >
              <label>* I agree with rules of the portal</label>
              <br>
              </div>
            </div>  

        
        
        </div>
        <div id=“frame_green“>
                 <?php
                        // From database obtain avatar image file name and next recreate their location
                       
                        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

                        // Check connection
                        if($dbc === false){
                          die(„ERROR: Could not connect to database – stage of article listing. “ . mysqli_connect_error());
                        }
                
                    
                       // read $avatar value from databaze of user
                        $_username = $_SESSION[‚username‘]; // get info about currently loged user
                        $_users_id = $_SESSION[‚users_id‘];
                        $sql = „SELECT * FROM bazaar_user WHERE username = „.“‚$_username'“.“ AND users_id=“.“‚$_users_id'“; // query avatar
                        
                        if($output = mysqli_query($dbc, $sql)){
                          if(mysqli_num_rows($output) > 0){
                           $row = mysqli_fetch_array($output);
                           $write_date_obtained = $row[‚write_date‘]; // get latest profile update date for output located at the botoom part of page
                           if (!empty($row[‚avatar‘])) {
                            $image_location = IMAGE_PATH.$row[‚avatar‘];
                            echo „<center> <td id=\“gray_under_picture\“>  <br> <img  align=\“middle\“ src=\“$image_location\“ alt=\“ profile avatar picture \“  height=\“250\“> <br> <br> <br> </td> </center>“;
                           } else {
                            echo „<center> <td id=\“gray_under_picture\“> <br> <img align=\“middle\“ src=\“./images/default_avatar.png\“ alt=\“ profile avatar picture \“  height=\“250\“> <br> <br> </td> </center>“;
                           }
                           
                           mysqli_free_result($output);
                          }
                        }    
                        

                        // Close connection
                        mysqli_close($dbc);
                 ?>        
                <p> In this part you can select your profile avatar! </p>
                <label>* Please select location of your avatar from drive – max 5MB!</label>
                <div class=“custom-file“>
                <br>
                <input type=“file“ name=“avatar“ class=“custom-file-input“ id=“avatar“ lang=“en“ onchange=“getFilename(this)“>
                    <label class=“custom-file-label1 custom-file-label“  for=“customFile“>Screenshot1 – required:</label>
                <br>
                </div>
          </div>       

          

        <script type=“application/javascript“> // javascript handling chaging filename of selected file
               $(document).ready(function(){
        $(„#avatar“).change(function(){
          //alert(„A file 1 has been selected.“);
                    var thefile1 = document.getElementById(‚avatar‘);
                    
          var fileName1 = thefile1.value;
                    //var fileName1 = „A file 1 has been selected.“;
                    $(‚.custom-file-label1‘).html(fileName1);
            
        });
        $(„#screenshot2“).change(function(){
          //alert(„A file 2 has been selected.“);
          var thefile2 = document.getElementById(‚screenshot2‘);
                    
                    var fileName2 = thefile2.value;
          //var fileName2 = „A file 2 has been selected.“;
                    $(‚.custom-file-label2‘).html(fileName2);
        });
        $(„#screenshot3“).change(function(){
          //alert(„A file 3 has been selected.“);
          var thefile3 = document.getElementById(‚screenshot3‘);
                    
                    var fileName3 = thefile3.value;
          //var fileName3 = „A file 3 has been selected.“;
                    $(‚.custom-file-label3‘).html(fileName3);
        });
              });
            
        
         
             </script>
       

          <br><br>
     
          <div id=“frame_green“> 
            <div class=“form-group“>
                <label>Profile text – plese provide some description for your profile if will:</label>  <!– textera for input large text –>
                <textarea id=“profile_text“ onfocus=“this.value='<?php echo isset($_POST[‚profile_text‘]) ? $profile_text : ‚Please provide description for your profile if will …‘; ?>'“ name=“profile_text“ class=“form-control“ rows=“3″ cols=“50″><?php echo isset($_POST[‚profile_text‘]) ? $profile_text : $profile_text; ?></textarea>
                <br>
            </div>
         </div>
         <br>
         <div id=“frame_red“>
              <label> If you will change password. Write old password and then for verification two times new one:</label>
              <label>Old password:</label>
          <input type=“password“  name=“pass_word_old“ class=“form-control“ >
              <br>
              <label>New password:</label>
          <input type=“password“  name=“pass_word1″ class=“form-control“ >
              <br>
              <label>New password once again for verification:</label>
              <input type=“password“  name=“pass_word2″ class=“form-control“ >
              <br>
            </div>  
              <br>
    
      
         <br><br>
     
   
      <center> <button type=“submit“ name=“submit“ class=“btn btn-warning btn-lg“> Update profile information </button> </center>
      
    
     
          <br><br>
      

      <?php   //part displaying info after succesfull added subscriber into a mailinglist
         if ($is_result ) {
          

            echo “ <br> <br>“;
            echo “ <table class=\“table table-success\“> „;
            echo “ <tr>
                 <td><h5>  Personal info  for user  <strong> $username </strong> was last modified at $write_date_obtained. „;    
            
              
            echo “     <td>   </tr> „; 
            echo “ </table> „;
          
          //echo “ <input type=“text“ id=“result_field“ name=“result_field“ value=“$result“  >  <br>“ ;
        } ; 
         ?>
                 <br>
    
    </form>
     
<!– ***************************************** –>
<!– HTML part displayed for unloged user      –>
<!– ***************************************** –> 
    <?php } else { // else if user is not loged then form will noot be diplayed?>  
      <br> 
        <img id=“calcimage“ src=“./images/logininvit.png“ alt=“Log in invitation“ width=“150″ height=“150″>
        <br>
        <h4>For further profile editing please log in<a class=“navbar-brand“ href=“login.php“><h4><u>here.</u> </h4></a></h4>
        <br>
      <?php } ?>  
    
    
    </div>

          
    
    
    <?php  // footer include code
      require_once(‚footer.php‘); // including footer
      generate_footer(580); // function from footer.php for seting width, you can use 580 and 1060px width
    ?>  
    
      
</body>
</html>

Last part of form enable change existing user password. Provided passwords must contain currently valid password and two identical new password. On script handling part of site are controlled these new passwords and from database is obtained sha1 hash of currently used password. Only if current password provided by user is equal to that stored in database (hashes not plain passwords!!!) and both new passwords are the same, then old hash of password is overwritten that new.

Visual implementation is shown next (bottom part of editprofile form).

Conclusion

Our editprofile form enable further user data maintaining by logged in user. Only registered user are permitted to access own profile. For better maintainability user_ID, registration username and registration e-mail is not editable (gray style with disabled option in appropriate input element).

Full code for further study can be obtained from github here.




Bazaar – php example code – part 10 – pagination in list output

Article will focus on way how to create pagination functionality for larger list of displayed data (list of items for sell, list of registered users, cart items, …). Our implementation will be portable among a pages or other projects, visually attractive and ergonomic.

Expectation from pagination functionality

Larger list output of data can be for user a bit overwhelming. Best way how to break output into a separate chunks of data is paginate them with support of separate numbered page links.

For our implementation of pagination mechanism is expected:

  • user can define or in code is hardcoded number of items per page, this is held in $number_per_page variable
  • page links must be shown as numbered hyperlinks in bottom left part of data lists
  • arrows for next and previous page must be present with its graphical representation
  • separate function for generating pagination link will be created (its name is functions.php and appropriate function is named   function generate_page_links($user_search, $sort_by, $order, $cur_page, $num_pages) { //($user_search, $sort_by, $order, $cur_page, $num_pages);

Our expectation how pagination links will look like show next picture:

Pagination links in bottom part of a item list on main Bazaar page

Code for page links generation

Function for paging links creation is inserted into a functions.php script. Full content of mentioned function follows:

function generate_page_links($user_search, $sort_by, $order, $cur_page, $num_pages) { //($user_search, $sort_by, $order, $cur_page, $num_pages);
    $page_links = „“;
    echo „<br>“;
   
    // if this is not first in row, we need generate the „previous“ link
    if  ($cur_page > 1) {
        $page_links .= ‚<a id=“pagination“ href=“‚ . $_SERVER[‚PHP_SELF‘] . ‚?usersearch=‘
        .$user_search . ‚&sort_by=‘ . $sort_by . ‚&order=‘ . $order .’&page=‘ . ($cur_page – 1) . ‚“><img src=“./images/previous_icon.png“ alt=“previous image“ width=“30″ height=“30″></a>‘;

    } else {
        $page_links .= ‚<span id=“pagination“><img src=“./images/previous_icon.png“ alt=“previous image“ width=“30″ height=“30″></span> ‚;
    }

    // Loop through the pages generating the page numbered links
    for($i = 1; $i <= $num_pages; $i++) {
        if  ($cur_page == $i) {  
        $page_links .= ‚<span id=“pagination“>‘ . $i. ‚</span>‘; // span inline element mark non a tag (unlinked number) as pagination for further formating by css
        } else {
        $page_links .= ‚<a id=“pagination“ href=“‚ . $_SERVER[‚PHP_SELF‘] . ‚?usersearch=‘
        .$user_search . ‚&sort_by=‘ . $sort_by . ‚&order=‘ . $order .’&page=‘ . $i . ‚“>‘ . $i . ‚</a>‘;
        }
    } 

    // If this page is not last in row, generate „next“ link
    if  ($cur_page < $num_pages) {
        $page_links .= ‚<a id=“pagination“ href=“‚ . $_SERVER[‚PHP_SELF‘] . ‚?usersearch=‘
        .$user_search . ‚&sort_by=‘ . $sort_by . ‚&order=‘ . $order .’&page=‘ . ($cur_page + 1) . ‚“><img src=“./images/next_icon.png“ alt=“next image“ width=“30″ height=“30″></a>‘;

    } else {
        $page_links .= ‚ <span id=“pagination“><img src=“./images/next_icon.png“ alt=“next image“ width=“30″ height=“30″></span>‘;
    }
  

    return $page_links;

}

Our function can generate also user_search if needed for providing optional chunk of information trough GET able links.

In main implementation page we take closer look in a way how to display paginated outputs.

Way how to implement pagination in a main page code

For first approach we will show you code implementing pagination with calling generate_page_links($user_search, $sort_by, $order, $cur_page, $num_pages) function.

As a comments are displayed necessary leadings for understanding our code. Next code sniped is selected from main Bazaar page, from bottom list of items for sell (permanently displayed part, not part generated by user selected category – upper part is optionally displayed).

/**********************************************************************/
/*  Output in paginated form                                                                                  */
/**********************************************************************/

 /***
  *  Display pagination on the page – part included to listening in this area
  */
/* Attempt MySQL server connection. Assuming you are running MySQL
 */
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

//GET data for pagination send to page herself

//calculate pagination information
$cur_page = isset($_GET[‚page‘]) ? $_GET[‚page‘] : 1;
// results per page default declater as 5 on top of page and changed in submitt part after reset button handling $results_per_page = 5;
$skip = (($cur_page -1) * $results_per_page);
// first  question to database table for obtaining number of published items in a database – obtain value for $total
$sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY item_id DESC „;  // read in reverse order of score – highest score first              
$output_for_number_rows_count = mysqli_query($dbc, $sql); // query database
$total = mysqli_num_rows($output_for_number_rows_count);    //get number of rows in databse 
 
… omitted part of code enabling ordering along selected category
if(($sort_by == „name“) && ($order == „1“)) { // along name and ASC order
        $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY name_of_item ASC LIMIT $skip$results_per_page“; 
    };

    if(($sort_by == „name“) && ($order == „-1“)) { // along name and DESC order
        $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY name_of_item DESC LIMIT $skip, $results_per_page“; 
    };

    if(($sort_by == „price“) && ($order == „1“)) { // along price and ASC order
        $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY price_eur ASC LIMIT $skip, $results_per_page“
    };

    if(($sort_by == „price“) && ($order == „-1“)) { // along price and DESC order
        $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY price_eur DESC LIMIT $skip, $results_per_page“; 
    };

    if(($sort_by == „category“) && ($order == „1“)) { // along category and ASC order
        $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY subcategory_id ASC LIMIT $skip, $results_per_page“; 
    };

    if(($sort_by == „category“) && ($order == „-1“)) { // along category and DESC order
        $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY subcategory_id DESC LIMIT $skip, $results_per_page“; 
    };

    if(($sort_by == „default“)) { // along category and DESC order
        $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY item_id DESC LIMIT $skip, $results_per_page“; 
    };

} else {  // first run without ordering – no get link generated
    $sql = „SELECT * FROM bazaar_item WHERE published=“.“‚1′“.“ AND cart_number=“.“‚0′“.“ ORDER BY item_id DESC LIMIT $skip, $results_per_page“;  // read in reverse order of score – highest score first
}
 
/***********************************************************************/
/*  Output in Table – solution 1 – for debuging data from database                 */
/***********************************************************************/
 
echo „<br><br>“;
echo „<h4>Latest added items for you! </h4>“;
echo „<br>“;

/***
 *  Obtaining wished number of item per page – option for select
 */
?>
<form  method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
      
<div class=“form-group“>
<label> Set expected number of items per page -5 is default:</label>
<input list=“number_per_page“ name=“number_per_page“ placeholder=“please select or write nr.“>
      <datalist id=“number_per_page“> <!– must be converted in subcategory_id in script – marked with (*) –>
          <option value=“5″>
          <option value=“10″>
          <option value=“15″>   
          <option value=“20″>   
          <option value=“50″>
          <option value=“100″>      
        </datalist>
     
    
    

      <!– users_id from session obtaining – for debuging and testing is set as hidden –>
     
      <button type=“submit“ name=“nr_of_pages“ class=“btn btn-warning“> Use selected number of pages! </button>
</div>
</form>
<?php

echo „<br>“; echo „<br>“;

if($output = mysqli_query($dbc, $sql)){
    if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
        // create table output
        echo „<table>“; //head of table
            echo „<tr>“;
                //echo „<th>id</th>“;
                // functionality for ordering result
                /**
                 * SORTING – PART I. Here are generated GET links for UP/DOWN ordering by appropriate category – not pertinent to our explantation related to pagination functionality
                 */
                echo ‚<th>Name  <br /><a id=“SORT“ href=“index.php?sort_by=name&amp;order=1″> <img id=“arrow“ src=“./images/arrowup.png“> </a>
                                <a id=“SORT“ href=“index.php?sort_by=name&amp;order=-1″> <img id=“arrow“ src=“./images/arrowdown.png“> </a> </th>‘; //order 1 up -1 down
                echo ‚<th>Price <br /><a id=“SORT“ href=“index.php?sort_by=price&amp;order=1″> <img id=“arrow“ src=“./images/arrowup.png“> </a>
                                <a id=“SORT“ href=“index.php?sort_by=price&amp;order=-1″> <img id=“arrow“ src=“./images/arrowdown.png“> </a></th>‘;
                echo ‚<th>Category <br /><a id=“SORT“ href=“index.php?sort_by=category&amp;order=1″> <img id=“arrow“ src=“./images/arrowup.png“> </a>
                                <a id=“SORT“ href=“index.php?sort_by=category&amp;order=-1″> <img id=“arrow“ src=“./images/arrowdown.png“> </a> </th>‘;
                echo „<th>Screenshot1</th>“;
                echo „<th>More info</th>“;
                
                
            echo „</tr>“;
        while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
            echo “ <div class=\“mailinglist\“> “ ;
            echo „<tr>“;
                //echo „<td>“ . $row[‚item_id‘] . „</td>“;
                echo „<td class=\“item_name\“>“ . $row[‚name_of_item‘] . „</td>“;
                echo „<td class=\“price\“>“ . $row[‚price_eur‘] . “ € </td>“;

                            /* convert category_id in to category and subcategory */
                            $subcategory_id = $row[‚subcategory_id‘];
                            $category_idsupl    = „“ ;
                            $subcategory_idsupl = „“ ;
                            // (*) — conversion of category and subcategory into category%id
                                
                                //create SELECT query for category and subcategory names from database
                                 $sql_supl = „SELECT category, subcategory FROM bazaar_category WHERE subcategory_id = „.“‚$subcategory_id'“ ;
                                /*$output_supl = mysqli_query($dbc, $sql_supl);
                                $row_supl = mysqli_fetch_array($output_supl);
                                $category_id    = $row_supl[‚category‘] ;
                                $subcategory_id = $row_supl[‚subcategory‘] ;
                                echo „<td>“ . $category_id.“/“.$subcategory_id.“</td>“;*/
                                // execute sql and populate data list with existing category in database
                                if($output_supl = mysqli_query($dbc, $sql_supl)){
                                    if(mysqli_num_rows($output_supl) > 0){  // if any record obtained from SELECT query
                                        while($row_supl = mysqli_fetch_array($output_supl)){ //next rows outputed in while loop
                                            
                                            $category_idsupl    = $row_supl[‚category‘] ;
                                            $subcategory_idsupl = $row_supl[‚subcategory‘] ;
                                            
                                                
                                        }
                                        
                                        
                                        // Free result set
                                        mysqli_free_result($output_supl);
                                    } else {
                                        echo „There is no souch category-subcategory in category table. Please correct your error.“; // if no records in table
                                    }
                                } else{
                                    echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                                }

                echo „<td>“ . $category_idsupl.“/“.$subcategory_idsupl.“</td>“;
                
                    $image_location = IMAGE_PATH.$row[‚screenshot1‘];
                echo „<td id=\“gray_under_picture\“> <img  src=\“$image_location\“ alt=\“ screenshot of product primary \“  height=\“250\“> </td>“; 
                echo ‚<td colspan=“1″><a id=“DEL“ href=“item.php?item_id=‘.$row[‚item_id‘]. ‚“><img id=“next“ src=“./images/next.png“>   </a></td></tr>‘; //construction of GETable link
            echo „</tr>“;
            echo “ </div> “ ;
        }
        echo „</table>“;
        //count nuber of pages total
        $num_pages = ceil($total / $results_per_page);
        
        //generate navigational page links if we have more than one page
        
        if($num_pages > 1) {
            $user_search = „“; // not implemented yet, then set as clear values
            if(empty($sort_by)) { // if not obtained by get then default order is applied
                $sort_by=“default“;
            };
            if(empty($order)) { // if not obtained by get then default order is applied
                $order=“1″;
            };
            
            // included function for pagination generation function stored in functions.php page
            echo generate_page_links($user_search, $sort_by, $order, $cur_page, $num_pages);
            echo „<br><br>“;
        }
        // Free result set
        mysqli_free_result($output);
    } else{
        echo „There is no item for sell. Please add one.“; // if no records in table
    }
} else{
    echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
}
// Close connection
mysqli_close($dbc);
?>
 

By this way we can implement pagination also in admin page. If two or more ordering are present on page, only one selected number of page is mandatory for all lists. it means, if we selected page nr. 2 in one list, also other list are on page 2 after reloading page with appropriate GET links is generated for requesting that page for display.

This is not bad solution of most of our needs for simplifying information displayed in one time.

Conclusion

Pagination is a way how to limit number off information visible to a user in given time. For our solution we used selection with LIMIT functionality and further mechanism for reading total number of items for display. After necessary calculation, links for pagination are generated and with help of GET request, page obtain all information important for display only that part of selection, that is needed for that moment.

Full working code of bazaar training app can be downloaded from github here.

Main parts are implemented in as function in functions.php where is function for link generation. Index.php or admin.php are great examples how to implement two or more pagination per single page. This simple solution has its own limitation as it was mentioned before.




Bazaar – php example code – part 9 – cart and other notification icons

Article will focus on implementation user cart icon with display of number and total price for items in main menu page. For further visual improvement we use graphical icon with text. Also sell icon with link to sellitem page is added.

Expectation from cart icon display

Cart notification icon is small graphic remainder of number of items added into a cart and actual total price for pay.

Our implementation will offer these functionalities:

  • contain graphic depiction of cart
  • show total number of items in a cart
  • show total price that will be paid for all items in a cart
  • must be includable into a other bazaar pages
  • cart must be visible only for registered and loged in users

Visual implementations of cart icon

Next part provide further depiction of cart icon shown in upper part of logged in user pages.

Cart icon implemented in upper part of cart page (gray block)

Code of the cart icon and including into a page

In a next rows you can look at way how cart icon is implemented in script named cart_icon.php.

<!– *************************************************************** –>
<!– PHP included code for cart icon with number of items displaing      –>
<!– *************************************************************** –>
<!– Vrsion: 1.0        Date: 17. – 18.10.2020 by CDesigner.eu                          –>
<!– *************************************************************** –>
<?php
   $_user_id = $_SESSION[‚users_id‘];
   $_number_of_items_in_cart =“-„;
   $_total_price =“0″;

   /*********************************************************
    * Count mumber of items in cart and total item price
    */

    /* Attempt MySQL server connection. Assuming you are running MySQL
             */
            $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

            // Check connection
            if($dbc === false){
                die(„ERROR: Could not connect to database – stage of article listing. “ . mysqli_connect_error());
            }

            
                        
            // read all rows (data) from guestbook table in „test“ database
                
            $sql = „SELECT * FROM bazaar_item WHERE cart_number=“.“‚$_user_id'“.“ ORDER BY item_id ASC „;  // read items marked in cart_number with appropriate users_id
            /****************************************************************/
            /*  Output in Table – solution 1 – for debuging data from database    */
            /****************************************************************/
            // if data properly selected 
                        

            if($output = mysqli_query($dbc, $sql)){
                   if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                    // create table output
                    
                    $_total_price = 0; // initialize cariable calculating total price for items in cart
                    $_number_of_items_in_cart =0;
                    while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                        
                            $_total_price += $row[‚price_eur‘];
                            $_number_of_items_in_cart += 1;

              

                    }
                    

                    // Free result set
                    mysqli_free_result($output);
                } else {
                    echo „“; // if no records in table
                }
            } else {
                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
            }
            // Close connection
            mysqli_close($dbc); 

   //debug

   echo ‚&nbsp;  &nbsp; &nbsp; &nbsp;  <span class=“cart“> <a class=“navbar-brand“ href=“cart.php“> <img id=“cart“ src=“./images/small_cart.png“ alt=“cart small icon“ width=“35″ height=“35″><strong>(‚ .$_number_of_items_in_cart .‘)  ‚ .$_total_price .‘ €</strong></a> </span>‘;
   // add some space with &nbsp;
?>

Our code obtain users_id of currently logged in user from session variable, then go through all rows in bazaar_item table that are marked by users_id (they are added into a cart). If current row id marked by users_id of currently logged user then increment number of items and accumulate price of items by price of that item.

In next part of code snippet is cart_icon.php included in headermenu.php and header menu is included (required_once) in all pages that in some way implement menu. In this way we created decomposition and make our code much more modular.

<!– **************************************************************** –>
<!– PHP header menu  of bazaar for including                                               –>
<!– **************************************************************** –>
<!– Vrsion: 1.0        Date: 22. – 22.11.2020 by CDesigner.eu                            –>
<!– **************************************************************** –>
<?php
   // generate menu if user is loged in or not
         // old solution with cookies if(isset($_COOKIE[‚username‘])) { // loged in user
            require_once(‚headerlogo.php‘);
            
            if(isset($_SESSION[‚username‘])) { // loged in user
                 
                echo ‚<div id=“menu“>‘;
                echo ‚<a class=“navbar-brand“ href=“index.php“><img width=“150″ src=“./images/bazaarheader.png“> Bazaar – best items for a best prices!</a>‘;
                echo ‚<a class=“navbar-brand“ href=“editprofile.php“><img id=“menuimage“ src=“./images/menu_profile.png“> Edit profile </a>‘;
                                
                if(isset($_SESSION[‚user_role‘])==’admin‘) { // if loged user is admin role
                   echo ‚<a class=“navbar-brand“ href=“admin.php“><img id=“menuimage“ src=“./images/menu_admin.png“> Manage your page </a>‘;
               };
               echo ‚<a class=“navbar-brand“ href=“logout.php“><img id=“menuimage“ src=“./images/menu_logout.png“> Logout <b><span id=“username“>‘ .$_SESSION[‚username‘] .'</span></b></a>‘;
               echo ‚</div >‘;
               require_once(‚sell_icon.php‘); // graphic menu item for selling your items
               echo ‚<a class=“navbar-brand“ href=“rss.php“><img src=“./images/rss.png“ width=“45″></a>‘; //rss feed link
               require_once(‚cart_icon.php‘); // small cart icon in menu
               
              } else { // visitor without login
               echo ‚<div id=“menu“>‘;
               echo ‚<a class=“navbar-brand“ href=“login.php“><img id=“menuimage“ src=“./images/menu_login.png“> Log In </a>‘;
               echo ‚<a class=“navbar-brand“ href=“signup.php“><img id=“menuimage“ src=“./images/menu_signup.png“> Sign Up for better membership! </a>‘;
   
               echo ‚<a class=“navbar-brand“ href=“index.php“><img width=“150″ src=“./images/bazaarheader.png“> Bazaar – best items for a best prices!</a>‘;
               echo ‚</div >‘;
             };
             
?>

And final way how headermenu.php is called in our bazaar pages

… code omitted …
<body>
    <nav class=“navbar „>
      <div id=“header_container_1060″>
        <div class=“navbar-header“>   
        <?php 
           require_once(‚headermenu.php‚); // including menu items
        ?>   
         
        </div>
      </div>
    </nav>
    <div class=“container“ id=“container_1060″> 
… code omitted …

Conclusion

Cart_icon.php fulfill our expectation for good way how to constantly inform our customer about all items added to buy. Problem decomposition by implementing them into a headermenu.php and text to all pages is solution for further code maintainability.

Full code of bazaar app can be obtained from github here.




Bazaar – php example code – part 8 – shopping cart of user

Article focus on way of implementation of user shopping cart. Our bazar_item table is altered for new field cart_number. If cart number is zero, item is not added into a buyer cart. After adding item into a cart, this number is changed to a number of buing user. Showing content of cart relays on display bazaar_itmes marked by users_id of appropriate user.

Way how to implement shopping cart

Shopping cart will display all items added by appropriate user for further revision and commitment to buy.

In our cart page we must be able to do:

  • display all items added to buy by a single user
  • enable delete items from cart
  • calc total price for items in cart
  • delivery adress can be updated by editinfo.php page, here is only displayed content
  • after definitive submitting, send info to seler by e-mail about succesfull buy

Cart is available only for loged in users, also loged in user can commit buy to a seler/ sellers of selected items.

For further improvement or consideration is way how to inform sellers about succesull buy. Our simle solution send one e-mail for one item. But there is not a small possibility, tahat cart can contain more items from one seler. For all of these items is send to seler one buy commitment request.

Visual look of shopping cart

Next pictures show content of our shopping cart and related scripts output.

Shopping cart frontend

Displayed info about not selected comitting YES for BUY

Succesfully submited buy with notification about contacting of sellers for that items

Implementation of shopping cart

Next code shows how shopping cart is implemented in our aplication.

<!– ***************************************************************** –>
<!– PHP „self“ code showing content of items added into a cart                   –>
<!– ***************************************************************** –>
<!– Vrsion: 1.0        Date: 1.11.2020 by CDesigner.eu                                        –>
<!– ***************************************************************** –>

<!– ***************** MEMO – base is from index.php – show all items with cart_number = session(users_id) + calc total summ, create remove from cart link with removefromcart.php show address for delivery and button submitt to buy ************************************ –>

<?php
    require_once(‚appvars.php‘); // including variables for database
    session_start(); // start the session – must be added on all pages for session variable accessing

    // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
    if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
        if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
            $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
            $_SESSION[‚username‘] = $_COOKIE[‚username‘];
            $_SESSION[‚user_role‘] = $_COOKIE[‚user_role‘]; // added for role
        }
     }
    // two variables for message and styling of the mesage with bootstrap
    $msg = “;
    $msgClass = “;

    // default values of auxiliary variables
    $name_of_item = „“;
    $price_eur = „“;
    $subcategory_id = „“;
    $users_id = „“;
    $item_add_date = „“;
    $subcategory_id = „“;
    $published = false;
    $screenshot1 = „“;
    $screenshot2 = „“;
    $screenshot3 = „“;
    $item_description = “;
    $is_result = false; //before hitting submit button no result is available
    
    // Control if data was submitted
    if(filter_has_var(INPUT_POST, ‚submit‘)) {
        // Data obtained from $_postmessage are assigned to local variables
        if($_POST[‚confirm‘] == ‚Yes‚ ){ // if yuser selected YES and hit Buy button on below of the page
            //read all data from $_POST array
            $users_id = htmlspecialchars($_POST[‚users_id‘]);
            /***********************************************************
             *   obtain data about buyer
             */
            // read data about buying user with users id from database
            // make database connection
            $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
            // Check connection
                if($dbc === false){
                    die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                }
            
            //– only one needed — geting users data for purchase e-mail
            $sql = „SELECT * FROM bazaar_user WHERE users_id = „.“‚$users_id'“.“LIMIT 1″  ;
            if($output = mysqli_query($dbc, $sql)){
                if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                    
                    while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                            $first_name_buyer = $row[‚first_name‘];
                            $lastname_name_buyer = $row[‚lastname_name‘];
                            $addresss_buyer = $row[‚addresss‘];
                            $city_buyer = $row[‚city‘];
                            $ZIPcode_buyer = $row[‚ZIPcode‘];
                            $email_buyer = $row[‚email‘];
 
                                                    
                    }
                    
                    // Free result set
                    mysqli_free_result($output);
                } else{
                    echo „No info about buyer obtained.“; // if no records in table
                }
            } else{
                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
            };
            
             /**************************************************************
             *   obtain data buyed items from this buyer with users_id defined by current SESSION
             */
            //get info about sold items – we must go through all buyed items and send emaily one by one for all diferent selers of item (first approach for all item one)
            $sql = „SELECT * FROM bazaar_item WHERE cart_number = „.“‚$users_id'“  ;
            if($output = mysqli_query($dbc, $sql)){
                if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                    
                    while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                            $item_id = $row[‚item_id‘];
                            $name_of_item = $row[‚name_of_item‘];
                            $price_eur = $row[‚price_eur‘];
                            $users_id_of_seller = $row[‚users_id‘];
                            
                             /******************************************************
                             *   sent info to seler item by item in the buyer cart
                             */
                            // send appropriate e-mails about buy items by items
                             // validate e-mail
                            if(filter_var($email_buyer, FILTER_VALIDATE_EMAIL) === false){
                                // E-mail is not walid
                                $msg = ‚Wrong e-mail format of buyer, purchase can not be created. Please contact page admin.‘;
                                $msgClass = ‚alert-danger‘;
                            } else {
                                // E-mail is ok
                                $is_result = true;
                                /* request e-mail of seller */
                                 /****************************************************
                                 *   obtain e-mail of appropriate seller – this is done for all buying items one by one
                                 */
                                $sql2 = „SELECT email FROM bazaar_user WHERE users_id = „.“‚$users_id_of_seller'“  ;
                                if($output2 = mysqli_query($dbc, $sql2)){
                                    if(mysqli_num_rows($output2) > 0){  // if any record obtained from SELECT query
                                        
                                        while($row = mysqli_fetch_array($output2)){ //next rows outputed in while loop
                                            $email_of_seller = $row[‚email‘];
                                                
                     
                                                                        
                                        }
                                        
                                        // Free result set
                                        mysqli_free_result($output2);
                                    } else{
                                        echo „No email about seller can be obtained.“; // if no records in table
                                    }
                                } else{
                                    echo „ERROR: Could not able to execute $sql2. “ . mysqli_error($dbc); // if database query problem
                                };

                                 /******************************************              *   construct information e-mails about item buy one by one for all items in cart
                                 */

                                $toEmail = $email_of_seller; //!!! e-mail address to send to 
                                $subject = ‚Item ‚.$name_of_item.‘ purchased on Bazaar by ‚.$first_name_buyer.‘ ‚.$lastname_name_buyer;
                                $body = ‚<h2>Item ‚.$name_of_item.‘ was succesfully purchased by : ‚.$first_name_buyer.‘ ‚.$lastname_name_buyer.'</h2>
                                    <h4>Delivery adress for this purchase is: </h4><p>‘.$addresss_buyer.‘,</p><p> ‚.$city_buyer.‘, </p><p>‘.$ZIPcode_buyer.'</p>
                                    <h4>Email</h4><p>E-mail of buyer is‘.$email_buyer.‘ this e-mail can be used for further communication.</p>
                                    <h4>Selling price was:</h4><p‘.$price_eur.‘ €.</p>
                                    ‚;

                                // Email Headers
                                $headers = „MIME-Version: 1.0″ .“\r\n“;
                                $headers .=“Content-Type:text/html;charset=UTF-8″ . „\r\n“;

                                // Additional Headers
                                $headers .= „From: “ .$first_name_buyer. „<„.$email_buyer.“>“. „\r\n“;

                            

                                        
                                if(mail($toEmail, $subject, $body, $headers)){
                                    // Email Sent
                                    $msg .= ‚<p> Your seller of ‚.$name_of_item.‘ was successfully contacted via e-mail.</p>‘;
                                    $msgClass = ‚alert-success‘;
                                } else {
                                    // Failed
                                    $msg = ‚Information about your buy cannot be delivered to seller via e-mail. Please contact site admin for further help.‘;
                                    $msgClass = ‚alert-danger‘;
                                }
                            }
                                            
                                                                    
                                    }
                                    
                                    // Free result set
                                    mysqli_free_result($output);
                                } else{
                                    echo „No info about buyer obtained.“; // if no records in table
                                }
                            } else{
                                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                            };

    

            // close database connection
            mysqli_close($dbc);

         
          } else {
              echo  ‚<p class=“alert alert-danger“ > The selected operation cannot be performed. Please select YES for further buy confirmation. </p>‘; 
          }
    
        

        

    };  
  
    

    
        
?>

<!– **************************************** –>
<!– HTML code containing Form for submitting –>
<!– **************************************** –>
<!DOCTYPE html>
<html>
<head>
    <title> Bazaar Cart  </title>
    <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
    <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
    
</head>
<body>
    <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>   
        <?php // generate menu if user is loged in or not
         // old solution with cookies if(isset($_COOKIE[‚username‘])) { // loged in user
            if(isset($_SESSION[‚username‘])) { // loged in user
                echo ‚<a class=“navbar-brand“ href=“index.php“>Bazaar – best items for a best prices!</a>‘;
                echo ‚<a class=“navbar-brand“ href=“editprofile.php“> Edit profile </a>‘;
                echo ‚<a class=“navbar-brand“ href=“logout.php“> Logout ‚ .$_SESSION[‚username‘] .'</a>‘;
                if(isset($_SESSION[‚user_role‘])==’admin‘) { // if oged user is admin role
                   echo ‚<a class=“navbar-brand“ href=“admin.php“> Manage your page </a>‘;
               };
               require_once(‚sell_icon.php‘); // graphic menu item for selling your items
               require_once(‚cart_icon.php‘); // small cart icon in menu
             } else { // visitor without login
               echo ‚<a class=“navbar-brand“ href=“login.php“> Log In </a>‘;
               echo ‚<a class=“navbar-brand“ href=“signup.php“> Sign Up for better membership! </a>‘;
   
               echo ‚<a class=“navbar-brand“ href=“index.php“>Bazaar – best items for a best prices!</a>‘;
            }
        ?>   
         
        </div>
      </div>
    </nav>
    <div class=“container“ id=“container_1060″> 
        
        
      <?php if($msg != “): ?>
            <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?>   
        
        <br> 
        <img id=“calcimage“ src=“./images/cart.png“ alt=“cart image“ width=“150″ height=“150″>
        <br>
      <h4> Cart item of user 
        <?php    echo $_SESSION[‚username‘];  // creating title of cart for users
                 echo “ with id –  {$_SESSION[‚users_id‘]} are:“; 
        ?>
        <br>
      </h4>

      <!– Showing content of the cart of appropriate user with items marked with users_id in filed cart_number –>
      <?php 
                /* Attempt MySQL server connection. Assuming you are running MySQL
            server with default setting (user ‚root‘ with no password) */
            $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

            // Check connection
            if($dbc === false){
                die(„ERROR: Could not connect to database – stage of article listing. “ . mysqli_connect_error());
            }

      
                        
            // read all rows (data) from guestbook table in „test“ database
            $_usr_id = $_SESSION[‚users_id‘];   
            $sql = „SELECT * FROM bazaar_item WHERE cart_number=“.“‚$_usr_id'“.“ ORDER BY item_id ASC „;  // read items marked in cart_number with appropriate users_id
            /**************************************************************/
            /*  Output in Table – solution 1 – for debuging data from database  */
            /**************************************************************/
            // if data properly selected from guestbook database tabele
            
            echo „<br>“;
           

            echo „<br>“; echo „<br>“;

            if($output = mysqli_query($dbc, $sql)){
                if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                    // create table output
                    echo „<table>“; //head of table
                        echo „<tr>“;
                            //echo „<th>id</th>“;
                            echo „<th>Name</th>“;
                            echo „<th>Price</th>“;
                            echo „<th>Category</th>“;
                            echo „<th>Screenshot1</th>“;
                            echo „<th>More info</th>“;
                            
                            
                        echo „</tr>“;
                    $cart_total_eur = 0; // initialize cariable calculating total price for items in cart
                    while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                        echo “ <div class=\“mailinglist\“> “ ;
                        echo „<tr>“;
                            //echo „<td>“ . $row[‚item_id‘] . „</td>“;
                            echo „<td class=\“item_name\“>“ . $row[‚name_of_item‘] . „</td>“;
                            echo „<td class=\“price\“>“ . $row[‚price_eur‘] . “ € </td>“;
                            $cart_total_eur += $row[‚price_eur‘];

                                        * convert category_id in to category and subcategory */
                                        $subcategory_id = $row[‚subcategory_id‘];
                                        $category_idsupl    = „“ ;
                                        $subcategory_idsupl = „“ ;
                                        // (*) — conversion of category and subcategory into category%id
                                            
                                            // create SELECT query for category and subcategory names from database
                                            $sql_supl = „SELECT category, subcategory FROM bazaar_category WHERE subcategory_id = „.“‚$subcategory_id'“ ;
                                            /*$output_supl = mysqli_query($dbc, $sql_supl);
                                            $row_supl = mysqli_fetch_array($output_supl);
                                            $category_id    = $row_supl[‚category‘] ;
                                            $subcategory_id = $row_supl[‚subcategory‘] ;
                                            echo „<td>“ . $category_id.“/“.$subcategory_id.“</td>“;*/
                                            // execute sql and populate data list with existing category in database
                                            if($output_supl = mysqli_query($dbc, $sql_supl)){
                                                if(mysqli_num_rows($output_supl) > 0){  // if any record obtained from SELECT query
                                                    while($row_supl = mysqli_fetch_array($output_supl)){ //next rows outputed in while loop
                                                        
                                                        $category_idsupl    = $row_supl[‚category‘] ;
                                                        $subcategory_idsupl = $row_supl[‚subcategory‘] ;
                                                        
                                                            
                                                    }
                                                    
                                                    
                                                    // Free result set
                                                    mysqli_free_result($output_supl);
                                                } else {
                                                    echo „There is no souch category-subcategory in category table. Please correct your error.“; // if no records in table
                                                }
                                            } else{
                                                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                                            }

                            echo „<td>“ . $category_idsupl.“/“.$subcategory_idsupl.“</td>“;
                            
                                $image_location = IMAGE_PATH.$row[‚screenshot1‘];
                            echo „<td id=\“gray_under_picture\“> <img  src=\“$image_location\“ alt=\“ screenshot of product primary \“  height=\“250\“> </td>“; 
                            echo ‚<td colspan=“1″><a id=“DEL“ href=“removefromcart.php?cart_number=‘.$row[‚cart_number‘]. ‚&amp;item_id=‘. $row[‚item_id‘] . ‚&amp;name_of_item=‘. $row[‚name_of_item‘] .'“> >> Remove from cart  </a></td></tr>‘; //construction of GETable link
                        echo „</tr>“;
                        echo “ </div> “ ;
                    }
                    echo „</table>“;
                    echo „<br><br>“;
                    echo „<p><center><h5>Total price for items in cart: <strong> $cart_total_eur </strong>€ </h5></center></p>“;
                    // Free result set
                    mysqli_free_result($output);
                } else{
                    echo „There is no item for sell. Please add one.“; // if no records in table
                }
            } else{
                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
            }
            // Close connection
            mysqli_close($dbc); 
      
      ?>

     <!– Recapitulation of user delivery adress – important beacause is sent to seller with e-mail about succesfull buy of listened item –>
     <h4> Your delivery adress is: </h4>
        <?php 
            // connect to a database
            $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

               // Check connection
               if($dbc === false){
                   die(„ERROR: Could not connect to database – stage of article listing. “ . mysqli_connect_error());
               }
   
           // get info about user from database  
           $users_id = $_SESSION[‚users_id‘]; 
           $sql = „SELECT * FROM bazaar_user WHERE users_id = „.“‚$users_id'“.“LIMIT 1″  ;
           if($output = mysqli_query($dbc, $sql)){
               if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                   
                   while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                           $first_name = $row[‚first_name‘];
                           $lastname_name = $row[‚lastname_name‘];
                           $addresss = $row[‚addresss‘];
                           $city = $row[‚city‘];
                           $ZIPcode = $row[‚ZIPcode‘];
                           $email = $row[‚email‘];

                           ?>
                                <div id=“frame_green“>
                                
                                <br>
                                <h5> Please check your contact and delivery info, these information are important for
                                            seller of the items for correct contact and delivery! </h5>
                                        <br>
                                <table>
                                    <tr>
                                        
                                        
                                        <td>         
                                        <label>e-mail:</label>
                                        <input type=“text“  name=“nickname“ class=“form-control“ value=“<?php echo $email;  ?>“ disabled>
                                        <br>
                                        </td>
                                        <td>
                                        <label>First name:</label>
                                        <input type=“text“ name=“first_name“ class=“form-control“ value=“<?php echo $first_name; ?>“ disabled>
                                        <br>
                                        </td>
                                        <td>
                                        <label>Last name:</label>
                                        <input type=“text“ name=“lastname_name“ class=“form-control“ value=“<?php  echo $lastname_name;  ?>“ disabled>
                                        <br>
                                        </td>
                                    <tr>    
                                    </tr>   
                                        <td colspan=“3″>
                                        <label>Adress in form – Street Nr.:</label>
                                        <input type=“text“  name=“addresss“ class=“form-control“ value=“<?php  echo $addresss; ?>“ disabled>
                                        <br>
                                        </td>
                                    <tr>    
                                    </tr>   
                                        <td colspan=“3″>
                                        <label>City:</label>
                                        <input type=“text“ name=“city“ class=“form-control“ value=“<?php echo $city; ?>“ disabled>
                                        <br>
                                        </td>
                                    <tr>    
                                    </tr>   
                                        <td colspan=“3″>
                                        <label>ZIP code in form XXXXX:</label>
                                        <input type=“text“ name=“ZIPcode“ class=“form-control“ value=“<?php  echo $ZIPcode; ?>“ disabled>
                                        </td>
                                        
                                    </tr>   
                                </table>
                                <br>
                                        <h5> If any of displayed info need correction, please visit your profile page <a href=“editprofile.php“><u>here</u>. </a></h5>
                                </div> 

                           
                          <?php                                 
                   }
                   
                   // Free result set
                   mysqli_free_result($output);
               } else{
                   echo „Error while reading data.“; // if no records in table
               }
           } else{
               echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
           };
           // Close connection
            mysqli_close($dbc);        
        ?>
        <br>
      </h4>

       <form  method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
          <input type=“hidden“ name=“users_id“ value=“<?php echo $_SESSION[‚users_id‘] ?>“ />
          <h5> For confirmation of buy select YES and click on red button bellow:</h5>
          <center><input type=“radio“ name=“confirm“ value=“Yes“ /> Yes   <br>
          <input type=“radio“ name=“confirm“ value=“No“ checked=“checked“ /> No </center><br><br>  
          <center><button type=“submit“ name=“submit“ class=“btn btn-danger btn-bg“> I confirm the purchase with the obligation to pay </button> </center>
  
          <br><br>
      </form>
     
 
    </div>
    
        
    <div class=“footer“> 
          <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
    </div>
        
      
</body>
</html>

Cart page generate GETable link to script removefromcart.php to enable remove item from cart. This is done by reverting cart_number filed of appropriate item from number equal to buyers users_id to zero. User is befor removing item also informed about that item is now visible for other portal user for buy. And second decision must not be available, because item will add another user to a cart.

removefromcart.php script

Content of our supplementary removal script follows here:

<!– **************************************************************** –>
<!– PHP „self“ code GET request for remove from cart                                 –>
<!– **************************************************************** –>
<!– Vrsion: 1.0        Date: 2.11.2020 by CDesigner.eu                                       –>
<!– **************************************************************** –>

<?php // leading part of page for simple header securing and basic variable setup
    require_once(‚appvars.php‘); // including variables for database
    session_start(); // start the session – must be added on all pages for session variable accessing

  // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
  if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
    if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
      $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
            $_SESSION[‚username‘] = $_COOKIE[‚username‘];
            $_SESSION[‚user_role‘] = $_COOKIE[‚user_role‘]; // added for role
    }
   }
   
  // two variables for message and styling of the mesage with bootstrap
  $msg = “;
  $msgClass = “;

  // default values of auxiliary variables
  
?>

<!– ******************************************* –>
<!– script for removing item from cart          –>
<!– ******************************************* –>
<!– obtain GET data from cart.php and trough    –>
<!– POST submit remove goods from cart by       –>
<!– seting cart_number filed to 0 – notasigned  –>
<!– to any user                                 –>
<!– ******************************************* –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar remove from cart – remove script </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
  
</head>
<body>
  <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
          <a class=“navbar-brand“ href=“cart.php“>Return to your shopping car</a>
          <a class=“navbar-brand“ href=“index.php“> –> return to main shop page</a>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  
    
      
    <?php if($msg != “): ?> <!– alert showing part –>
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
       
      <br> <!– logo on the center of the page –>
      <h4>Confirmation of removal item from cart.</h4>
      <br>

      <br> <!– logo on the center of the page –>
        <img id=“calcimage“ src=“./images/delicon.png“ alt=“del image“ width=“150″ height=“150″>
      <br>

       
            
      <?php // code for GET info about what to remove and submit removing approval

        if(isset($_GET[‚cart_number‘]) && isset($_GET[‚item_id‘]) && isset($_GET[‚name_of_item‘]) ){
            // take a data from GET link generated by adminscript
            $cart_number = htmlspecialchars($_GET[‚cart_number‘]);
            $item_id = htmlspecialchars($_GET[‚item_id‘]);
            $name_of_item = htmlspecialchars($_GET[‚name_of_item‘]);
           
           

        } else if (isset($_POST[‚cart_number‘]) && isset($_POST[‚item_id‘]) && isset($_POST[‚name_of_item‘])) { //grab score from POST – different behavior for removal
            $cart_number = htmlspecialchars($_POST[‚cart_number‘]);
            $item_id = htmlspecialchars($_POST[‚item_id‘]);
            $name_of_item = htmlspecialchars($_POST[‚name_of_item‘]);
          
        }  else  { //error info message
            echo ‚<p class=“alert alert-danger“> Please specify any cart item for removal. </p>‘;

        };

        if(isset($_POST[‚submit‘])){
             
            if($_POST[‚confirm‘] == ‚Yes‘ ){ // delete appropriate score post with imagescreenshot
              //delete the screenshotimage from the 
              $cart_number = htmlspecialchars($_POST[‚cart_number‘]);
              $item_id  = htmlspecialchars($_POST[‚item_id‘]);
              $name_of_item  = htmlspecialchars($_POST[‚name_of_item‘]);
             

             
              // conect to the database
              $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

              //Delete score data from the database
              $sql = „UPDATE bazaar_item SET cart_number = ‚0‘ WHERE item_id = $item_id LIMIT 1“;
              // execute SQL
              mysqli_query($dbc, $sql);

              // close database connection
              mysqli_close($dbc);

              // confirm executed command
              echo ‚<p> The item ‚ . $name_of_item . ‚ with id<strong>‘ . $item_id . ‚</strong> was sucesfully removed from your cart and now is available in listening for sell
                    for another user. </p>‘;

           
            } else {
                echo  ‚<p class=“alert alert-danger“ > The selected item cannot be removed. </p>‘; 
            }
        } else if (isset($cart_number) && isset($item_id) && isset($name_of_item) ) {
            echo ‚<h5>Are you sure to remove ‚ . $name_of_item . ‚ from your cart? Item will be set for sell listening and can be bought by another user.</h5>‘; 
            // show short describtion of score for deletion
            echo ‚<p> <strong> item_id: </strong> ‚ . $item_id .  ‚<br> <strong> item name is: </strong>‘ . $name_of_item .
                 
                 ‚</p>‘; 
              
            //generating removing confirmation form      
            

            echo ‚<form method=“POST“ action=“removefromcart.php“>‘;   //not self but direct this script removecategory.php – we dont want include any GET data tahat previously send
            echo ‚<input type=“radio“ name=“confirm“ value=“Yes“ /> Yes   ‚; 
            echo ‚<input type=“radio“ name=“confirm“ value=“No“ checked=“checked“ /> No <br><br>‘;  
            
            echo ‚<input type=“hidden“ name=“cart_number“ value=“‚.$cart_number.'“  />‘; 
            echo ‚<input type=“hidden“  name=“item_id“ value=“‚.$item_id.'“  />‘;
            echo ‚<input type=“hidden“ name=“name_of_item“ value=“‚.$name_of_item.'“ />‘; 
            echo ‚<input type=“submit“ class=“btn btn-danger“ value=“submit“ name=“submit“ />‘; 
            echo ‚</form>‘; 

  

        };
        echo ‚<br><br>‘;
        echo  ‚<p> <a href = „cart.php“> &lt;&lt Back to your cart. </a></p>‘;

?>
    
      </div>

 
     <div class=“footer“> 
          <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
    </div>
    
      
</body>
</html>

Conclusion and final thoughts

Our cart solution implement simple way how to manage users items for buy. For further improvements is important mark sold items for admin removal or better mark them for removal by automated script after some time. Way how to do this, is mark item after succesfull buy comitt them from users_id to -1 (cart_number filed of that item in bazaar_item table). This mean item was sold and after some time they must be removed from portal.

Full aplcation code for further study can be obtained from github here.




Bazaar – php example code – part 7 – limiting user access and diferent page content display

Article deeper focus on mechanism how to use session variables created for loged in user for diferentiating page display. This mechanism relays on login features described in article part 6. Together make reusable solution for another projects with need in restricting access and diferent page content display for diferent categories of users.

Diferent content display – how to?

In many cases is important to display content of the page diferently for diferent types of users. Page for anonymous user will not display ability for editing user profiles or only loged in user can sell or buy listed items.

First part of all pages restricting access to them contains initialization session function call and reading info from session. If session is not set up, then look at data stored in cookies. If cookies contain valid information about loged in users, then session inforation is per page restored by their content. If not, page display content as for anonymous user.

This code looks like this

 require_once(‚appvars.php‘); // including variables for database
    // two variables for message and styling of the mesage with bootstrap
    session_start()// start the session – must be added on all pages for session variable accessing

    // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
    if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
        if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
            $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
            $_SESSION[‚username‘] = $_COOKIE[‚username‘];
            $_SESSION[‚user_role‘] = $_COOKIE[‚user_role‘]; // added for role
        }
     }

Diferent page content display

For diferent page display, we request for existence one fo session variable. If present, user is loged in, if not alternatve part of page code must be shown.

<!– *************************************************** –>
<!– HTML part available after succesfull login as user –>
<!– *************************************************** –>        
<?php if(isset($_SESSION[‚users_id‘]) ) { //if user is loged with users_id then editprofile form is available?> 
 
… part of page code shown if user loged in …
 
<!– ***************************************** –>
<!– HTML part displayed for unloged user      –>
<!– ***************************************** –> 
<?php } else { // else if user is not loged then form will noot be diplayed?>  
    
     
        <br> 
        <img id=“calcimage“ src=“./images/logininvit.png“ alt=“Log in invitation“ width=“150″ height=“150″>
        <br>
        <h4>For listening items for sell you must be loged in <a class=“navbar-brand“ href=“login.php“> here. </a></h4>
        <br>
      

<?php } ?>  

Main page menu variable content display

Main menu is another example of part fo adaptive dsiplay relaying on category of loged in user.

Next code display way how to display their content.

<body>
    <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
        <?php // generate menu if user is loged in or not
         // old solution with cookies if(isset($_COOKIE[‚username‘])) { // loged in user
            if(isset($_SESSION[‚username‘])) { // loged in user
                echo ‚<a class=“navbar-brand“ href=“index.php“>Bazaar – best items for a best prices!</a>‘;
                echo ‚<a class=“navbar-brand“ href=“editprofile.php“> Edit profile </a>‘;
                echo ‚<a class=“navbar-brand“ href=“logout.php“> Logout ‚ .$_SESSION[‚username‘] .'</a>‘;
                if(isset($_SESSION[‚user_role‘])==’admin‘) {
                   echo ‚<a class=“navbar-brand“ href=“admin.php“> Manage your page </a>‘;
               };
               require_once(‚sell_icon.php‘); // graphic menu item for selling your items  – we focus on this two items in next articles from tihis series
               require_once(‚cart_icon.php‘); // small cart icon in menu
             } else { // visitor without login
               echo ‚<a class=“navbar-brand“ href=“login.php“> Log In </a>‘;
               echo ‚<a class=“navbar-brand“ href=“signup.php“> Sign Up for better membership! </a>‘;
   
               echo ‚<a class=“navbar-brand“ href=“index.php“>Bazaar – best items for a best prices!</a>‘;
            }
        ?>   
        </div>
      </div>
    </nav>

Different display of content shows following pictures on example of admin page.

Display of admin page of unloged user

Display of admin page for user with low priviledges – relogin as admin requested.

Loged in as admin

Conclusions and further thoughts

We described ways how to display diferent content of the pages for diferent categories of users. Or mechanism use existence of sesion variables of loged user for making decision of which part of page is visible.

Inplementation of this features in whole project can be wisible on our github account here.




Bazaar – php example code – part 6 – user login with SESSIONS and COOKIES

This new year article will focus on using $_SESSION and $_COOKIE variables in proces on login user into a application. As first part of our next topics focused on user validation and diferentiation app behavior we will take closer look on signing up and login of page user.

Login mechanism in closer look

In our previeous application of mailer, we used for restricting access in to a specific page only HTTP header authentication mechanism. This approach is very simple but not scale well in larger sites with different pages with partialy or complet access restrictions.

New approach relays on login ability created by login.php script. Login script obtain user login credentials, compare it with those stored in database (passwords can not be stored as plain text, but we store only sha1 hashes and make comparisn with hashes together for deciding about corect or incorrect login).

After succesfull login $_SESSION variables are set. For better persistency there is made combination with $_ COOKIES variable. COOKIES are stored in local users browser and are available only if they are enabled by user, that must be keept in mind.

In all pages are SESSION started in first parts of php code and from COOKIES restore sessions among all pages where login restrictions must be made. In our next article, we take a closer look how limiting or difrentiating page looks for different category of users introduced with category of users database field.

For logout, there is available logout script with mechanism for invalidatin COOKIES and clearing SESSIONS variables.

Creating new users with sign up script

Our application need mechanism for subscribing new users for deeper access in pages for submitting items for sell ore more specific page available only for admin role of user – adminpage.

New user provide username, e-mail and type 2x password. Username must be unique and not used by another user. This mechanism is implemented in sql query but in our approach not in UNIQUE restriction in database field.

After succesfull login credentials creation, user can log in with existing login script.

Now we can take closer look at mentionied pages.

Sign Up script

User provide from sign up form username, e-mail and password. If username is unique (no unique e-mail is needed, because we can expect different logins of seler for different account with the same e-mail) user login credentials are added and user with role „user“ is introduced into bazar_user database table.

User role grant ability to buy and sell items, but not provide management ability mark items as eligible for visibility on title page of bazaar.

Listening of our script follows.

<!– ***************************************************************** –>
<!– PHP „self“ code handling sign up for membership on the bazaar app   –>
<!– ***************************************************************** –>
<!– Vrsion: 1.0        Date: 24.10-24.10.2020 by CDesigner.eu                            –>
<!– ***************************************************************** –>

<?php
 require_once(‚appvars.php‘); // including variables for database
   
 // two variables for message and styling of the mesage with bootstrap
 $msg = “;
 $msgClass = “;
 $u_name = “;
 $usr_passwd = “;
/* Attempt MySQL server connection.  */
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

if(isset($_POST[‚submit‘])) { 
    // obtaining submitted data from POST
    $u_name = htmlspecialchars($_POST[‚u_name‘]);
    $u_pass_1 = htmlspecialchars($_POST[‚u_pass_1‘]);
    $u_pass_2 = htmlspecialchars($_POST[‚u_pass_2‘]);
    $email = htmlspecialchars($_POST[‚email‘]);

    if(!empty($u_name) && !empty($email) && !empty($u_pass_1) && !empty($u_pass_2) && ($u_pass_1 = $u_pass_2)) {
     // make sure that username is available and is not registered for someone else
     $sql = „SELECT * FROM bazaar_user WHERE username = „.“‚$u_name'“ ;
     $data = mysqli_query($dbc, $sql);   
 
       if(mysqli_num_rows($data) == 0) {
           // username is unique and have not been used by any previous user
           $usr_passwd_sha1 =  sha1($u_pass_2);
           $sql = „INSERT INTO bazaar_user (username, pass_word, write_date, email, nickname) 
                   VALUES (‚$u_name‘, ‚$usr_passwd_sha1‘ , now(), ‚$email‘,’$u_name‘)“; // by default nickname and username are the same, next user can change

           if(mysqli_query($dbc, $sql)){
            $msg = ‚ Your new account has been created successfully. 
            You are now ready to <a href=“login.php“>log in</a>‘;
            $msgClass = ‚alert-success‘;
           } else{
               echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
           }
           //success confirmation for registered user
         
           

            // Free result set
      mysqli_free_result($data);
            // Close connection
            
            //exit(); if used blank page will be displayed without any other redirecting

       } else { // an account already exists for this username, so display an error message
           
            $msg = ‚ An account for submitted username already exsts. Please use different username …‘;
            $msgClass = ‚alert-danger‘;
       } 
    } else {
     
            $msg = ‚ Your must enter all of the required data, including contact e-mail address.‘;
            $msgClass = ‚alert-danger‘;
    }
      
}   
    // Close connection 
    mysqli_close($dbc);    
?>

<!– **************************************** –>
<!– HTML code containing Form for submitting –>
<!– **************************************** –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar signup page  </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
  
</head>
<body>
  <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
          <a class=“navbar-brand“ href=“index.php“>Bazaar – Signup for submitting/ buying your items</a>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  
        
    <?php if($msg != “): ?>
        <br> 
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
         
      
      
        
        <br> 
        <img id=“calcimage“ src=“./images/login.png“ alt=“bazaar image“ width=“150″ height=“150″>
        <br>

        <form  method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
           <div id=“login“>
                <legend> Please register for Bazaar membership <legend>
                    <label>Username:</label>
                    <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚u_name‘]) ? $u_name : “; ?>'“ name=“u_name“ class=“form-control“ value=“<?php echo isset($_POST[‚u_name‘]) ? $u_name : ‚Login name‘; ?>“>

                    <label>e-mail:</label>
                    <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚email‘]) ? $email : “; ?>'“ name=“email“ class=“form-control“ value=“<?php echo isset($_POST[‚email‘]) ? $email : ‚@‘; ?>“>
                    <label>Password:</label>
                    <input type=“password“ onfocus=“this.value='<?php echo isset($_POST[‚u_pass_1‘]) ? “ : “; ?>'“ name=“u_pass_1″ class=“form-control“ value=“<?php echo isset($_POST[‚u_pass_1‘]) ? “ : “; ?>“>

                    <label>Password:</label>
                    <input type=“password“ onfocus=“this.value='<?php echo isset($_POST[‚u_pass_2‘]) ? “ : “; ?>'“ name=“u_pass_2″ class=“form-control“ value=“<?php echo isset($_POST[‚u_pass_2‘]) ? “ : “; ?>“>
            </div>
           <input id=“loginsubmitt“ type=“submit“ name=“submit“ class=“btn btn-info“ value=“Sign In“> 
           <br>

        </form>

   
      </div>
    
<div class=“footer“> 
   <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
 </div>
 

</body>
</html>

Front look at signup page follows.

Login page

Code for loginpage take place only if user is not allready loged in. In this option is not set !isset($_SESSION[‚users_id‘]) . After verfication of login credentials SESSION variables and COOKIES are set for loged in user. Also loed in user is redirected on index.php main page as it contains next code.

<!– ***************************************************************** –>
<!– PHP „self“ code handling login into the bazaar app                                  –>
<!– ***************************************************************** –>
<!– Vrsion: 1.0        Date: 11.10-24.10.2020 by CDesigner.eu                            –>
<!– ***************************************************************** –>

<?php
 require_once(‚appvars.php‘); // including variables for database
 session_start(); // start the session
   
 // two variables for message and styling of the mesage with bootstrap
 $msg = “;
 $msgClass = “;
 $usr_username = “;
 $usr_passwd = “;

//get info that user is loged in, if not try it looking at cookies
//if(!isset($_COOKIE[‚s‘])) { old solution with cookies
  if(!isset($_SESSION[‚users_id‘])) { //new with session variables
    if(isset($_POST[‚submit‘])) {
        /* Attempt MySQL server connection.  */
             $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
             
                // accessing user entered login data
             $usr_username = htmlspecialchars($_POST[‚u_name‘]);    
             $usr_passwd = htmlspecialchars($_POST[‚u_pass‘]);
             

             if(!empty($usr_username) && !empty($usr_passwd)) {
              // try lookup user database
              $usr_passwd_SHA = sha1($usr_passwd);
              $sql = „SELECT users_id, username, user_role FROM bazaar_user WHERE username = „.“‚$usr_username'“. “ AND pass_word = „.“‚$usr_passwd_SHA'“ ;
              // debug output echo  $usr_username; 
              // echo  $usr_passwd;
              //echo $usr_passwd_SHA;
              $data = mysqli_query($dbc, $sql);   
              
              if(mysqli_num_rows($data) == 1) {
                  // login is ok, set user  ID and username cookies and redirect to the homepage
                  $row = mysqli_fetch_array($data);
                  //setcookie(‚users_id‘, $row[‚users_id‘]); old solution with cookies
                  //setcookie(‚username‘, $row[‚username‘]);
                  $_SESSION[‚users_id‘] = $row[‚users_id‘]; // sloution with sessions
                  $_SESSION[‚username‘] = $row[‚username‘];
                  $_SESSION[‚user_role‘] = $row[‚user_role‘]; // added user_role session variable
                  // new cookies for login persistency that expires after 30 days without logout combination SESSION with COOKIES is awailable
                  setcookie(‚users_id‘, $row[‚users_id‘], time()+(60+60*24*30));
                  setcookie(‚username‘, $row[‚username‘], time()+(60+60*24*30));
                  setcookie(‚user_role‘, $row[‚user_role‘], time()+(60+60*24*30))// cookie for user_role of loged in user added

                  $home_url = ‚http://‘. $_SERVER[‚HTTP_HOST‘] . dirname($_SERVER[‚PHP_SELF‘]) . ‚/index.php‘;
                  header(‚Location:‘. $home_url);

                  // Free result set
                  mysqli_free_result($data);
                  // Close connection
                  mysqli_close($dbc);

              } else  {
                  // urename/ password are incorrect – error meesage is displayed
                  $msg = „Incorrect username or password. Login denied!  „;
                  $msgClass = ‚alert-danger‘;
   
            }     

              
            } else {
                // username/ password were not entered – display error message
                $msg = „Sorry, you must eneter username and password to log in. „;
                $msgClass = ‚alert-danger‘;
   
            }     
    }  

?>

<!– **************************************** –>
<!– HTML code containing Form for submitting –>
<!– **************************************** –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar login page  </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
  
</head>
<body>
  <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
          <a class=“navbar-brand“ href=“index.php“>Bazaar – Login page</a>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  
    <?php if($msg != “): ?>
        <br> 
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
      
      <?php 
            //if(empty($_COOKIE[‚users_id‘])) { solution with cookies
              if(empty($_SESSION[‚users_id‘])) { // solution with sessions
                // only show for if session with name users_id does not exist
                //echo ‚ <br> ‚;
                //echo  ‚<p class=“alert alert-danger“>‘ . $msg . ‚</p>‘;
       ?> 
        
        <br> 
        <img id=“calcimage“ src=“./images/login.png“ alt=“bazaar image“ width=“150″ height=“150″>
        <br>

        <form  method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
           <div id=“login“>
                <legend> Log In <legend>
                <label>Username:</label>
                    <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚u_name‘]) ? “ : “; ?>'“ name=“u_name“ class=“form-control“ value=“<?php echo isset($_POST[‚u_name‘]) ? ‚Please reenter‘ : ‚Login name‘; ?>“>

                    <label>Password:</label>
                    <input type=“password“ onfocus=“this.value='<?php echo isset($_POST[‚u_pass‘]) ? “ : “; ?>'“ name=“u_pass“ class=“form-control“ value=“<?php echo isset($_POST[‚u_pass‘]) ? ‚Please reenter‘ : ‚Login name‘; ?>“>
            </div>
           <input id=“loginsubmitt“ type=“submit“ name=“submit“ class=“btn btn-info“ value=“Log In“> 
           <br>

        </form>

        <?php }  else { 
                 // successfull login
                  // cookie solution echo ‚<p class=“alert alert-success“> You are loged in as ‚ . $_COOKIE[‚username‘]. ‚</p>‘;
                  echo ‚<br>‘;
                  echo ‚<p class=“alert alert-success“> You are loged in as <em>‘ . $_SESSION[‚username‘]. ‚</em></p>‘; // session solution
                  echo ‚<p class=“alert alert-success“> If you will logout or login with anither credentials, please first <a href=“logout.php“>logout!. </a></p>‘;
              } 
        ?>  
      </div>

          
    
    
<div class=“footer“> 
   <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
 </div>
 

</body>
</html>

Next pictures display output on page after difrenet state of login process.

Log In page of Bazaar app

Error messaging after unsuccesfull login

Logout script

Last and shortest code page is logout page. After hitting link for logout, user sessions and cokkies are inmediatly destroyed and user is loged out. Without logout with cookies enabled, user is loged in in browser for 30 days. If brower disables cookies, user is loged in only if sessions are active up to closing browser windows.

Full code follows:

<!– ***************************************************************** –>
<!– PHP „self“ code handling logout procedure into the bazaar app       –>
<!– ***************************************************************** –>
<!– Vrsion: 1.0        Date: 24.10-24.10.2020 by CDesigner.eu           –>
<!– ***************************************************************** –>

<?php
 require_once(‚appvars.php‘); // including variables for database
    // part for SESSION solution for login persistence and its ending

    //even when logging out you have to first start the session in order to access the session variables
    session_start();
    if(isset($_SESSION[‚users_id‘])) {
        $_SESSION = array(); // deleting session vars
               
    };

    // if session cookie exists, then delete it
    if(isset($_COOKIE[session_name()])) {
        setcookie(‚session_name()‘,“,time() – 3600);
        
               
    };

    // Destroy session
    session_destroy();
    // logout user by deleting cookie – for COOKIES persistence solution
    
   /* if(isset($_COOKIE[‚users_id‘])) {
        setcookie(‚user_id‘,“,time() – 3600);
        setcookie(‚username‘,“,time() – 3600);
        echo „deleted cookies“;
               
    }; */

    // for our final solution SESSIONS+ longer login persistency with COOKIES must be also cokies deleted
    setcookie(‚users_id‘, $row[‚users_id‘], time()-3600);
    setcookie(‚username‘, $row[‚username‘], time()-3600);
    setcookie(‚user_role‘, $row[‚user_role‘], time()-3600); // added deletion of user_role cookie – after altering table for user_role

    // redirect to homepage in logout state
    $home_url = ‚http://‘. $_SERVER[‚HTTP_HOST‘] . dirname($_SERVER[‚PHP_SELF‘]) . ‚/index.php‘;
    header(‚Location:‘. $home_url);

 ?>

Conclusion and final thoughts

In this article we take focus on way how to grant user limited access in to a page resources. This solution uses sessions with suporting role by cookies.

In our next article we will focus how to use session log in information for diferentiating page display for diferent roles of page users (anonymous = unloged, user-s and admin-s).

Full code in as is state can be obtained from github here.




Bazaar – php example code – part 5 – admin page

Article focus on way how to create site admin page. In our first approach we focus only on content of the page, limiting access only for admin will be described in further articles.

Expectation for site admin page

Admin page is accessible only for specific user category. This category is defined by user_role as admin. Restricting access and iferent display of this page for diferent category of users will be explained in further articles.

With admin page we can publish/ unpublish or remove items for sell. Second functionality created up to ime of vriting of this article is category management.

Management operation is maintained by links leading to operational scripts as is removecategory.php or removeitem.php.

Removeitem php script is much moore interesting because display three options with conformation of operation. After succesfull submiting one of three posible sql is executed along content inserted in $oprtion variable.

Visual look of admin page

Visual look of admin page is as follows:

Admin page – first implemented version

After implementing login functionality, there will be two other output of this page, one for anonymous user and one for common user role.

admin page for loged out user

admin page for common user will request relogin with elevated priviledge

Implementation of desired functionality

Generating table for item and for category is most common, we will discuss these parts in previews articles. But we wil take a closer look at code of removeitem.php, with new option datalist functionality for selection among three functionalities: publishing, unpublishing and removing item by site admin.

All selection lead to different sql script, first two manipulate with contnt of field published on bazaar_item page. If this value is zero item si not displayed in listenings for users in index page. After seting on 1, items are dsiplayed.

Removing item is LIMITed on only one matching items for further security. Also one yes selection during submitting these operations are required.

Full code of removeitem.php script will follow:

<!– ***************************************************************** –>
<!– PHP „self“ code GET request for remove andable or disable product item        –>
<!-***************************************************************** –>
<!– Vrsion: 1.0        Date: 18.10.2020 by CDesigner.eu                                    –>
<!– **************************************************************** –>

<?php // leading part of page for simple header securing and basic variable setup
    require_once(‚appvars.php‘); // including variables for database

    session_start(); // start the session – must be added on all pages for session variable accessing

  // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
  if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
    if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
      $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
      $_SESSION[‚username‘] = $_COOKIE[‚username‘];
    }
   }
   
  // two variables for message and styling of the mesage with bootstrap
  $msg = “;
  $msgClass = “;

  // default values of auxiliary variables
  
?>

<!– ******************************************* –>
<!– script for appropriate scode removal        –>
<!– ******************************************* –>
<!– obtain GET data from admin.php and trough   –>
<!– POST submit remove data from database       –>
<!– ******************************************* –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar score – publish/unpublish/remove item script </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
       
</head>
<body>
  <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
          <a class=“navbar-brand“ href=“admin.php“> –> Bazaar admin page</a>
          <a class=“navbar-brand“ href=“index.php“> –> return to main shop page</a>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  
    
      
    <?php if($msg != “): ?> <!– alert showing part –>
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
       
      <br> <!– logo on the center of the page –>
      <h4>Please select what you will do.</h4>
      <br>

      <br> <!– logo on the center of the page –>
        <img id=“calcimage“ src=“./images/admin.png“ alt=“admin image“ width=“150″ height=“150″>
      <br>

       
            
      <?php // code for GET info about what to remove and submit removing approval

      /* structure of generated link on admin.php page for further reference
       echo ‚<td colspan=“1″><a id=“DEL“ href=“removeitem.php?item_id=‘.$row[‚item_id‘] . ‚&amp;name_od_item=‘
                         . $row[‚name_of_item‘] . ‚&amp;price_eur=‘. $row[‚price_eur‘] .
                         ‚&amp;published=‘. $row[‚published‘] . ‚&amp;screenshot1=‘. $row[‚screenshot1‘] .
                         ‚&amp;screenshot2=‘. $row[‚screenshot2‘] . ‚&amp;screenshot3=‘. $row[‚screenshot3‘] . ‚“> >>Publish/UnPub./Remove  </a></td></tr>‘;
      */

        if(isset($_GET[‚item_id‘]) && isset($_GET[‚name_of_item‘]) && isset($_GET[‚price_eur‘]) && isset($_GET[‚published‘]) && isset($_GET[‚screenshot1‘])){
            // take a data from GET link generated by adminscript
            $item_id = htmlspecialchars($_GET[‚item_id‘]);
            $name_of_item = htmlspecialchars($_GET[‚name_of_item‘]);
            $price_eur = htmlspecialchars($_GET[‚price_eur‘]);
            $published = htmlspecialchars($_GET[‚published‘]);
            $screenshot1 = htmlspecialchars($_GET[‚screenshot1‘]);
            $screenshot2 = htmlspecialchars($_GET[‚screenshot2‘]);
            $screenshot3 = htmlspecialchars($_GET[‚screenshot3‘]);
           

        } else if (isset($_POST[‚item_id‘]) && isset($_POST[‚name_of_item‘]) && isset($_POST[‚price_eur‘]) && isset($_POST[‚published‘]) && isset($_POST[‚screenshot1‘])) { //grab score from POST – different behavior for removal
            
            $item_id = htmlspecialchars($_POST[‚item_id‘]);
            $name_of_item = htmlspecialchars($_POST[‚name_of_item‘]);
            $price_eur = htmlspecialchars($_POST[‚price_eur‘]);
            $published = htmlspecialchars($_POST[‚published‘]);
            $screenshot1 = htmlspecialchars($_POST[‚screenshot1‘]);
            $screenshot2 = htmlspecialchars($_POST[‚screenshot2‘]);
            $screenshot3 = htmlspecialchars($_POST[‚screenshot3‘]);
           

        }  else  { //error info message
            echo ‚<p class=“alert alert-danger“> Please specify any category for removal. </p>‘;

        };

        if(isset($_POST[‚submit‘])){
             
            if($_POST[‚confirm‘] == ‚Yes‘ ){ // delete appropriate score post with imagescreenshot
              //read all data from $_POST array
              $item_id = htmlspecialchars($_POST[‚item_id‘]);
              $name_of_item = htmlspecialchars($_POST[‚name_of_item‘]);
              $price_eur = htmlspecialchars($_POST[‚price_eur‘]);
              $published = htmlspecialchars($_POST[‚published‘]);
              $screenshot1 = htmlspecialchars($_POST[‚screenshot1‘]);
              $screenshot2 = htmlspecialchars($_POST[‚screenshot2‘]);
              $screenshot3 = htmlspecialchars($_POST[‚screenshot3‘]);

              $operation = htmlspecialchars($_POST[‚operation‘]);

             
              // conect to the database
              $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

              //create sql query along selected operation
              switch ($operation) {
                case „publish„:
                    $sql = „UPDATE bazaar_item SET published = ‚1‘ WHERE item_id = $item_id LIMIT 1„;
                    // execute SQL
                    mysqli_query($dbc, $sql);
                    // confirm executed command
                    echo ‚<p> The item <strong>‘ . $name_of_item . ‚</strong> with id <strong>‘ . $item_id . ‚</strong> was succesfully published. </p>‘;
                    break;
                case „unpublish„:
                    $sql = „UPDATE bazaar_item SET published = ‚0‘ WHERE item_id = $item_id LIMIT 1„;
                    // execute SQL
                    mysqli_query($dbc, $sql);
                    // confirm executed command
                    echo ‚<p> The item <strong>‘ . $name_of_item . ‚</strong> with id <strong>‘ . $item_id . ‚</strong> was succesfully unpublished. </p>‘;
                    break;
                case „delete„:
                    $sql = „DELETE FROM bazaar_item WHERE item_id = $item_id LIMIT 1″;
                    // execute SQL
                    mysqli_query($dbc, $sql);
                    // confirm executed command
                    echo ‚<p> The item <strong>‘ . $name_of_item . ‚</strong> with id <strong>‘ . $item_id . ‚</strong> was succesfully deleted from listening on bazaar. </p>‘;
                    break;
            }
              
             

              // close database connection
              mysqli_close($dbc);

             

           
            } else {
                echo  ‚<p class=“alert alert-danger“ > The selected operation cannot be performed. </p>‘; 
            }
        } else if (isset($item_id) && isset($price_eur) && isset($name_of_item) && isset($published) && isset($screenshot1) ) {
            echo ‚<h5>Are you sure perform selected operation with bazaar item? </h5>‘; 
            // show short describtion of score for deletion
            $image_location = IMAGE_PATH.$screenshot1;
            echo ‚<p> <strong> Item_id: </strong> ‚ . $item_id .  ‚<br> <strong> Name: </strong>‘ . $name_of_item .
                  
                 
                           
                 ‚</p>‘; 
        echo “ <img src=\“$image_location\“ alt=\“ score image \“  height=\“150\“> „;
              
            //generating removing/ publishing/ unpublishing confirmation form      
            

            echo ‚<form method=“POST“ action=“removeitem.php“>‚;   //not self but direct this script removecategory.php – we dont want include any GET data tahat previously send
            echo ‚<h4> Please select your operation </h4>‘;

            echo ‚<input list=“operation“ name=“operation“ placeholder=“select“ >‘;
            echo ‚<datalist id=“operation“>‘;
            echo ‚<option value=“publish“>‘;
            echo ‚<option value=“unpublish“>‘;
            echo ‚<option value=“delete“>‘;
            echo ‚</datalist>‘;
         

            echo ‚<br><br>‘;

            
            echo ‚<input type=“radio“ name=“confirm“ value=“Yes“ /> Yes   ‚; 
            echo ‚<input type=“radio“ name=“confirm“ value=“No“ checked=“checked“ /> No <br><br>‘;  
            
            echo ‚<input type=“hidden“ name=“item_id“ value=“‚.$item_id.'“  />‘; 
            echo ‚<input type=“hidden“ name=“price_eur“ value=“‚.$price_eur.'“  />‘;
            echo ‚<input type=“hidden“ name=“name_of_item“ value=“‚.$name_of_item.'“ />‘; 
            echo ‚<input type=“hidden“ name=“published“ value=“‚.$published.'“ />‘; 
            echo ‚<input type=“hidden“ name=“screenshot1″ value=“‚.$screenshot1.'“ />‘; 
            echo ‚<input type=“hidden“ name=“screenshot2″ value=“‚.$screenshot2.'“ />‘; 
            echo ‚<input type=“hidden“ name=“screenshot3″ value=“‚.$screenshot3.'“ />‘; 
            echo ‚<input type=“submit“ class=“btn btn-danger“ value=“submit“ name=“submit“ />‘; 
            echo ‚</form>‚; 
                
        };
        echo ‚<br><br>‘;
        echo  ‚<p> <a href = „admin.php“> &lt;&lt Back to admin  page. </a></p>‘;

?>
    

    
    
    </div>

          
    
    
     <div class=“footer“> 
          <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
    </div>
    
      
</body>
</html>

Visual look of confirmation part with operation selection is displayed here:

rmoveitem.php script confirmation dialog with option

Conclusion and further thoughts

Our admin page contains baseline for page administration, in next times we can add some parts for admin or moderation if needed.

Full code of bazaar app can be obtained from github here.




Bazaar – php example code – part 4 – Selling item script

Our special Christmass article focus on listening item for sell on bazaar page. Data are obtained from registered user, inserted into a database and because default published filed in bazaar_item table is false, waiting for admin approval. In final version, this page is available only for registered user.

Expectation from sellingitem script

In final applicaton, selling page is available only for common registered user. User must be able do these things:

  • decribe name and price for selling item
  • add up to three different photos
  • select category with subcategory
  • provide any further describtion for selling item
  • item is not listed for sell untip approval of admin of the page

After sucessful post for sell, short describtion about adding document to a database is generated in pottom part of form.

After finalizing other main parts of app responsible for user management, we will add column for marking selling by users_id for difrerentiating of the seller. When someone decide to buy any their item, seller must be notified about buy and must fullfil item delivery.

Visual look of the page

Sell item page consist from sell form and list of published item for sell. In the middle part, ist optionaly after succesfull post displayed short info about user action.

Implementation of functionality

Main part of page consist form form part. In this part is insered script for generating available category list obtained from bazaar_category table.

Separate par enable selecting up to three files fortransfer. First screenshot of product is required and can not be ommited. Other two are optional as you can see. Separate Javascript code is responsible for listening file path after selecting them into a dialog field.

Next output show contetnt of the form:

<form enctype=multipart/form-data“ method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“> // because data file transfer enctype must be defined in form tag!!!
      <input type=“hidden“ name=“MAX_FILE_SIZE“ value=“5242880″>
          <div class=“form-group“>
              <label>* Please provide name of selling item:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚name_of_item‘]) ? $name_of_item : “; ?>'“ name=“name_of_item“ class=“form-control“ value=“<?php echo isset($_POST[‚name_of_item‘]) ? $name_of_item : ‚Name for product‘; ?>“>
              

              <label>* Please provide price for item in €:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚price_eur‘]) ? $price_eur : “; ?>'“ name=“price_eur“ class=“form-control“ value=“<?php echo isset($_POST[‚price_eur‘]) ? $price_eur : ‚Price in €‘; ?>“>
              
              <!– slection of category and subcategory –>
              <label>* Select main category-subcategory for proper item listing on bazar pages:</label>
              <input list=“category_subcategory“ name=“category_subcategory“ >
                <datalist id=“category_subcategory“> <!– must be converted in subcategory_id in script – marked with (*) –>
                    <?php // here read data from mysql bazaar_category and display existing category whre subcategory will be nested
                        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

                            // Check connection
                             if($dbc === false){
                                 die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                             };
                         
                         
                            
             
                            // create SELECT query for category names from database
                            $sql = „SELECT DISTINCT category, subcategory FROM bazaar_category ORDER BY category ASC, subcategory ASC„;

                            // execute sql and populate data list with existing category in database
                            if($output = mysqli_query($dbc, $sql)){
                                if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                                    
                                    while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                                    
                                            echo „<option value=“ . $row[‚category‘] .“-„.$row[‚subcategory‘] . „>„;
                                            
                                            
                                    
                                    }
                                    
                                    // Free result set
                                    mysqli_free_result($output);
                                } else{
                                    echo „There is no category in category table. Please wirite one.“; // if no records in table
                                }
                            } else{
                                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                            }

             
                            // Close connection
                            mysqli_close($dbc);
                    ?>
                                     
                </datalist>
                <p> If no proper category-subcategory exist, please contact admin of the pages for creation them for you. </p>

                <!– users_id from session obtaining – for debuging and testing is set as hidden –>
                <input type=“hidden“ name=“users_id“ value=“1″>

              
          </div>
          
          <p> In this part you can select upto 3 pictures of the product. First picture is required! </p>
          <label>* Please select location of your score screenshot from drive – max 5MB!</label>
          <div class=“custom-file“>
          
          <input type=“file“ name=“screenshot1″ class=“custom-file-input“ id=“screenshot1″ lang=“en“ onchange=“getFilename(this)“>
              <label class=“custom-file-label1 custom-file-label“  for=“customFile“>Screenshot1 – required:</label>

            
             
          </div>     

          <div class=“custom-file“>
          <input type=“file“ name=“screenshot2″ class=“custom-file-input“ id=“screenshot2″ lang=“en“ >
              <label class=“custom-file-label2 custom-file-label“ for=“customFile“>Screenshot2 – optional:</label>

             
              
             
          </div>

          <div class=“custom-file“>
          <input type=“file“ name=“screenshot3″ class=“custom-file-input“ id=“screenshot3″ lang=“en“ >
              <label class=“custom-file-label3 custom-file-label“ for=“customFile“>Screenshot3 – optional:</label>
                
                    
              </div>

              <script type=“application/javascript“> // javascript handling chaging filename of selected file
               $(document).ready(function(){
                $(„#screenshot1“).change(function(){
                    //alert(„A file 1 has been selected.“);
                    var thefile1 = document.getElementById(‚screenshot1‘);
                    
                    var fileName1 = thefile1.value;
                    //var fileName1 = „A file 1 has been selected.“;
                    $(‚.custom-file-label1‘).html(fileName1);
                    
                });
                $(„#screenshot2“).change(function(){
                    //alert(„A file 2 has been selected.“);
                    var thefile2 = document.getElementById(‚screenshot2‘);
                    
                    var fileName2 = thefile2.value;
                    //var fileName2 = „A file 2 has been selected.“;
                    $(‚.custom-file-label2‘).html(fileName2);
                });
                $(„#screenshot3“).change(function(){
                    //alert(„A file 3 has been selected.“);
                    var thefile3 = document.getElementById(‚screenshot3‘);
                    
                    var fileName3 = thefile3.value;
                    //var fileName3 = „A file 3 has been selected.“;
                    $(‚.custom-file-label3‘).html(fileName3);
                });
              });
            
              
               
             </script>
            
           

          <br><br>
         
          
          <div class=“form-group“>
            <label>* Item description:</label>  <!– textera for input large text –>
            <textarea id=“item_description“ onfocus=“this.value='<?php echo isset($_POST[‚item_descriptio‘]) ? $item_description : ‚Please provide description of selling item …‘; ?>'“ name=“item_description“ class=“form-control“ rows=“3″ cols=“50″><?php echo isset($_POST[‚item_description‘]) ? $item_description : ‚Description of item for sell goes here …‘; ?></textarea>
          </div>

          

          <!– div class=“form-group“>
            <label>Your message for Guestbook:</label–>  <!– textera for input large text –>
            <!– textarea id=“postmessage“ name=“postmessage“ class=“form-control“ rows=“6″ cols=“50″><?php echo isset($_POST[‚postmessage‘]) ? $postmessage : ‚Your text goes here …‘; ?></textarea>
          </div–>
     
          <button type=“submit“ name=“submit“ class=“btn btn-warning“> Add item for sell </button>
          <button type=“submit“ name=“reset“ class=“btn btn-info“> Reset form </button>
          
          <!– remove comment after implementation
          <button type=“submit“ name=“delete“ class=“btn btn-danger“> Delete recently posted score </button>
          –>
          <button type=“submit“ name=“reset“ class=“btn btn-info“> Reset form </button>
          <br><br>
          

          <?php   //part displaying info after succesfull added subscriber into a mailinglist
                 if ($is_result ) {
                    

                        echo „<br> <br>“;
                        echo “ <table class=\“table table-success\“> „;
                        echo “ <tr>
                               <td><h5> <em> Item for selll: </em> $name_of_item for $price_eur €  </h5> <h5> has been succesfully added to selling list. Item will be visible
                               on bazaar page after admin approval. </h5> „;
                               $image_location = IMAGE_PATH.$screenshot1;
                        echo “ <img src=\“$image_location\“ alt=\“ score image \“  height=\“150\“> „;       
                        
                          
                        echo “     <td>   </tr> „; 
                        echo “ </table> „;
                    
                    //echo “ <input type=“text“ id=“result_field“ name=“result_field“ value=“$result“  >  <br>“ ;
                } ; 
                 ?>
                 <br>
        
      </form>

Part responsible for obtaining data after hitting submit button consist from:

if(filter_has_var(INPUT_POST, ‚submit‘)) {
        // Data obtained from $_postmessage are assigned to local variables
        $name_of_item = htmlspecialchars($_POST[‚name_of_item‘]);
        $price_eur = htmlspecialchars($_POST[‚price_eur‘]);
        $users_id = htmlspecialchars($_POST[‚users_id‘]);
        //echo ‚users_id‘; echo $users_id;
        
        $category_subcategory = htmlspecialchars($_POST[‚category_subcategory‘]); // must be converted to subcategory_id (*)
            // separate category and subcategory with strtok() function 
            $words = explode(‚-‚, $category_subcategory);
            $category=$words[0];
            //echo $category;
            //echo ‚<br>‘;
            $subcategory=$words[1];
            //echo $subcategory;
        
        
        $screenshot1 = htmlspecialchars($_FILES[‚screenshot1‘][‚name‘]);
        $screenshot2 = htmlspecialchars($_FILES[‚screenshot2‘][‚name‘]);
        $screenshot3 = htmlspecialchars($_FILES[‚screenshot3‘][‚name‘]);
        $item_description = htmlspecialchars($_POST[‚item_description‘]);

        // (*) — conversion of category and subcategory into category%id
                    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

                    // Check connection
                    if($dbc === false){
                        die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                    };
                
                    
                    

                    // create SELECT query for category names from database
                    $sql = „SELECT subcategory_id FROM bazaar_category WHERE category = „.“‚$category'“. “ AND subcategory = „.“‚$subcategory'“ ;

                    // execute sql and populate data list with existing category in database
                    if($output = mysqli_query($dbc, $sql)){
                        if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                            while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                                
                                $subcategory_id = $row[‚subcategory_id‘] ;
                                    
                            }
                            
                            
                            // Free result set
                            mysqli_free_result($output);
                        } else {
                            echo „There is no souch category-subcategory in category table. Please correct your error.“; // if no records in table
                        }
                    } else{
                        echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                    }
                    // Close connection
                    mysqli_close($dbc);
        

        // Controll if all required fields was written
        if(!empty($name_of_item) && !empty($price_eur) && !empty($subcategory_id) && !empty($screenshot1)) { // these item identifiers are mandatory and can not be empty
            // If check passed – all needed fields are written
            // Check if E-mail is valid
            

                
                // move image to /images final folder from demporary download location
                $target1 = IMAGE_PATH . $screenshot1;
                $target2 = IMAGE_PATH . $screenshot2;
                $target3 = IMAGE_PATH . $screenshot3;

                // !!! Add entry to the database and redraw all score in chart list descending from highest score

                   // insert into databse 
                      if (move_uploaded_file($_FILES[‚screenshot1‘][‚tmp_name‘], $target1)) {
                            move_uploaded_file($_FILES[‚screenshot2‘][‚tmp_name‘], $target2);
                            move_uploaded_file($_FILES[‚screenshot3‘][‚tmp_name‘], $target3);
                            // make database connection
                            $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
                            // Check connection
                                if($dbc === false){
                                    die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                                }
                            
                            // INSERT new entry
                        
                            $sql = „INSERT INTO bazaar_item (name_of_item, price_eur, subcategory_id, users_id, item_add_date, screenshot1, screenshot2, screenshot3, item_description) 
                            VALUES (‚$name_of_item‘, $price_eur , ‚$subcategory_id‘ , ‚$users_id‘ , now(), ‚$screenshot1‘, ‚$screenshot2‘, ‚$screenshot3‘, ‚$item_description‘ )“;
                            //show added item true
                            $is_result = true; 
                            if(mysqli_query($dbc, $sql)){
                                
                                $msg = ‚New item ‚.$name_of_item. ‚ for ‚. $price_eur. ‚ € succesfully added to sell item – waiting for admin approvall.‘;
                                $msgClass = ‚alert-success‘;
                            } else {
                                
                                $msg = „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc);
                                $msgClass = ‚alert-danger‘;
                            }

                            // end connection
                                mysqli_close($dbc);
                                
            
            
                        } else {
                            // Failed – if not all fields are fullfiled
                            $msg = ‚Please fill in all * marked contactform fields‘;
                            $msgClass = ‚alert-danger‘; // bootstrap format for allert message with red color
                        };
            };              

    };  

Conclusion and other thoughts

Our page must be updated with code displaying its content and menus diferently for loged in user or anonymous users. Next improvement is expanding/ altering code to mark added item by users_id from active session for distinguishing between submitters.

Full code of application in as is current state can be obtained for further study from here.




Bazaar – php example code – part 3 – Manage category script

Article focus on way how we populate category/ subcategory for selling items. Management page contains listing of scucessfully added fileds with removal link as option. Our project will lead from category, trough item, simple login functionality into a editprofile option with more robust user login.

Discuss managecategory.php functionality

Our managecategory.php script must enable these functionalities:

  • create subcategory of item with existing main category
  • if we creating subcategory with non existing man category, we must be able to add them along
  • after all succesfully added category, list of existing category/ subcategory must be displayed with link for removal appropriate category row
  • after preparing parts for login verification, these scripts can be viable only for user with admin role assigned by page admin

Visual content of this page along with removecategory.php script follow:

Visual look of managecategory.php script

Category romoval script confirmation dialog

Implementation of expected functionality

Our page consist from parts for obtain user category and subcategory names. Error messaging, reporting of successfull category addition into bazaar_category table are next parts of our script.

Form obtaining data from user follow next:

 <form  method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>„>
          <div class=“form-group“>
              <label>* Set name for new subcategory:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚subcategory‘]) ? $subcategory : “; ?>'“ name=“subcategory“ class=“form-control“ value=“<?php echo isset($_POST[‚subcategory‘]) ? $subcategory : ‚Please provide name of new subcategory‘; ?>“>
              <br> 
              <label>* Select main category for nesting created subcategory:</label>
              <input list=“category“ name=“category“ >
                <datalist id=“category“>
                    <?php // here read data from mysql bazaar_category and display existing category whre subcategory will be nested
                        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

 

                            // Check connection
                             if($dbc === false){
                                 die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                             };
                         
                         
                            
             
                            // create SELECT query for category names from database
                            $sql = „SELECT DISTINCT category FROM bazaar_category ORDER BY category ASC„;

 

                            // execute sql and populate data list with existing category in database
                            if($output = mysqli_query($dbc, $sql)){
                                if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                                    
                                    while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                                    
                                            echo „<option value=“ . $row[‚category‘] . „>„;
                                                                              
                                    }
                                    
                                    // Free result set
                                    mysqli_free_result($output);
                                } else{
                                    echo „There is no category in category table. Please wirite one.“; // if no records in table
                                }
                            } else{
                                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                            }
 
                            // Close connection
                            mysqli_close($dbc);
                    ?>
                   
                    
                </datalist>
              <br> 
              
              <button type=“submit“ name=“subcategorysubmit“ class=“btn btn-warning“> Create new subcategory </button>
              <input type=“reset“ class=“btn btn-info“ value=“Reset“>             
          </div>
          <hr> 
          </form> 
             
    
          
          
          <br><br>
          
          
          <?php   //part displaying info after succesfull added category into a mailinglist
                 if ($is_result ) {
  
                        echo „<br> <br>“;
                        echo “ <table class=\“table table-success\“> „;
                        echo “ <tr>
                               <td><h5> <em> Category: </em> $category with subcategory $subcategory </h5> <h5> has been succesfully added to category list </h5> „;
                                  
                        
                          
                        echo “     <td>   </tr> „; 
                        echo “ </table> „;
                    
                    //echo “ <input type=“text“ id=“result_field“ name=“result_field“ value=“$result“  >  <br>“ ;
                } ; 
                 ?>
                 <br>
        
      </form>
      <?php

Listening of all items in bazaar_category table is generated by this content of script

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

// Check connection
if($dbc === false){
    die(„ERROR: Could not connect to database – stage of article listing. “ . mysqli_connect_error());
}
    
            
// read all rows (data) from guestbook table in „test“ database
$sql = „SELECT * FROM bazaar_category ORDER BY category ASC, subcategory ASC„; 
/********************************************************************/
/*    Output in Table – listening all category in bazaar_category table       */
/********************************************************************/
// if data properly selected from guestbook database tabele

echo „<h4>List of active categories and subcategories</h4>“;
echo „<br>“;
echo ‚ <button class=“btn btn-secondary btn-lg “ onclick=“location.href=\’admin.php\'“ type=“button“>  admin page -> </button>‘;

echo „<br>“; echo „<br>“;

    if($output = mysqli_query($dbc, $sql)){
        if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
            // create table output
            echo „<table>“; //head of table
                echo „<tr>“;
                    echo „<th>subcategory_id</th>“;
                    echo „<th>category</th>“;
                    echo „<th>subcategory</th>“;
                    echo „<th></th>“;
                    echo „<th>delete category</th>“;
                    
                    
                    
                    
                echo „</tr>“;
            while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                echo “ <div class=\“mailinglist\“> “ ;
                echo „<tr>“;
                    echo „<td>“ . $row[‚subcategory_id‘] . „</td>“;
                    echo „<td>“ . $row[‚category‘] . „</td>“;
                    echo „<td>“ . $row[‚subcategory‘] . „</td>“;
                     // removal line with removing link line
                
                     
                     echo „<td  colspan=\“1\“> Manage entry: </td>“; // description on first line
                         echo ‚<td colspan=“1″><a id=“DEL“ href=“removecategory.php?subcategory_id=‘.$row[‚subcategory_id‘] . ‚&amp;category=‘
                         . $row[‚category‘] . ‚&amp;subcategory=‘. $row[‚subcategory‘] .'“> >> Remove  </a></td></tr>‘; //construction of GETable link
                         // for removecategory.php input
                    
                    
                echo „</tr>“;
                echo “ </div> “ ;
            }
            echo „</table>“;
            // Free result set
            mysqli_free_result($output);
        } else{
            echo „There is no benchmark result in chart. Please wirite one.“; // if no records in table
        }
    } else{
        echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
    }

// Close connection
mysqli_close($dbc);
?>
      

removecategory.php script

Remove category script obtain data from GET associative array ofered from url snipet added to name of invoked page. After reading data, cerate removal confirmation form.

After selecting yes and submitting form, appropriate category/ subcategory row is removed with approrpiate sql query.

Content of the page is in following part:

<!– *************************************************************** –>
<!– PHP „self“ code GET request for remove and POST delete data         –>
<!– *************************************************************** –>
<!– Vrsion: 1.0        Date: 17.10.2020 by CDesigner.eu                                   –>
<!– *************************************************************** –>

 

<?php // leading part of page for simple header securing and basic variable setup
    require_once(‚appvars.php‘); // including variables for database
    session_start(); // start the session – must be added on all pages for session variable accessing – further description will be available in appropriate article in a row of articles focused on bazaar app

 

  // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
  if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
    if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
      $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
      $_SESSION[‚username‘] = $_COOKIE[‚username‘];
    }
   }
   
  // two variables for message and styling of the mesage with bootstrap
  $msg = “;
  $msgClass = “;

 

  // default values of auxiliary variables
  
?>

 

<!– ******************************************* –>
<!– script for appropriate scode removal        –>
<!– ******************************************* –>
<!– obtain GET data from admin.php and trough   –>
<!– POST submit remove data from database       –>
<!– ******************************************* –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar score – remove script </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
  
</head>
<body>
  <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
          <a class=“navbar-brand“ href=“managecategory.php“>Bazaar category manager – part for Bazaar category management</a>
          <a class=“navbar-brand“ href=“index.php“> –> return to main shop page</a>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  
    
      
    <?php if($msg != “): ?> <!– alert showing part –>
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
       
      <br> <!– logo on the center of the page –>
      <h4>Confirmation of deletion selected category removal.</h4>
      <br>

 

      <br> <!– logo on the center of the page –>
        <img id=“calcimage“ src=“./images/delicon.png“ alt=“Calc image“ width=“150″ height=“150″>
      <br>

 

       
            
      <?php // code for GET info about what to remove and submit removing approval

 

        if(isset($_GET[subcategory_id‚]) && isset($_GET[‚category‚])  ){
            // take a data from GET link generated by adminscript
            $subcategory_id = htmlspecialchars($_GET[‚subcategory_id‘]);
            $category = htmlspecialchars($_GET[‚category‘]);
            $subcategory = htmlspecialchars($_GET[‚subcategory‘]);
           

 

        } else if (isset($_POST[‚subcategory_id‘]) && isset($_POST[‚category‘]) && isset($_POST[‚subcategory‘])) { //grab score from POST – different behavior for removal
            $subcategory_id = htmlspecialchars($_POST[‚subcategory_id‘]);
            $category = htmlspecialchars($_POST[‚category‘]);
            $subcategory = htmlspecialchars($_POST[‚subcategory‘]);

 

        }  else  { //error info message
            echo ‚<p class=“alert alert-danger“> Please specify any category for removal. </p>‘;

 

        };

 

        if(isset($_POST[‚submit‚])){
             
            if($_POST[‚confirm‚] == ‚Yes‚ ){ // delete appropriate score post with imagescreenshot
              //delete the screenshotimage from the 
              $subcategory_id = htmlspecialchars($_POST[‚subcategory_id‘]);
              $category  = htmlspecialchars($_POST[‚category ‚]);
              $subcategory = htmlspecialchars($_POST[‚subcategory‘]);
              

 

              // conect to the database
              $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

 

              //Delete score data from the database
              $sql = „DELETE FROM bazaar_category WHERE subcategory_id = $subcategory_id LIMIT 1″;
              // execute SQL
              mysqli_query($dbc, $sql);

 

              // close database connection
              mysqli_close($dbc);

 

              // confirm executed command
              echo ‚<p> The category <strong>‘ . $category . ‚</strong> with id <strong>‘ . $subcategory_id . ‚</strong> was succesfully removed. </p>‘;

 

           
            } else {
                echo  ‚<p class=“alert alert-danger“ > The selected category was not removed. </p>‘; 
            }
        } else if (isset($subcategory_id) && isset($category)  ) {
            echo ‚<h5>Are you sure to delete the next category item from bazaar? </h5>‘; 
            // show short describtion of score for deletion
            echo ‚<p> <strong> subcategory_id: </strong> ‚ . $subcategory_id .  ‚<br> <strong> Category: </strong>‘ . $category .
                 ‚<br> <strong> Subcategory: </strong>‘ . $subcategory .  
                 ‚</p>‘; 
              
            //generating removing confirmation form      
            

 

            echo ‚<form method=“POST“ action=“removecategory.php“>‚;   //not self but direct this script removecategory.php – we dont want include any GET data tahat previously send
            echo ‚<input type=“radio“ name=“confirm“ value=“Yes“ /> Yes   ‚; 
            echo ‚<input type=“radio“ name=“confirm“ value=“No“ checked=“checked“ /> No <br><br>‘;  
            
            echo ‚<input type=“hidden“ name=“subcategory_id“ value=“‚.$subcategory_id.'“  />‘; 
            echo ‚<input type=“hidden“  name=“category“ value=“‚.$category.'“  />‘;
            echo ‚<input type=“hidden“ name=“subcategory“ value=“‚.$subcategory.'“ />‘; 
            echo ‚<input type=“submit“ class=“btn btn-danger“ value=“submit“ name=“submit“ />‚; 
            echo ‚</form>‚; 
      
        };
        echo ‚<br><br>‘;
        echo  ‚<p> <a href = „managecategory.php“> &lt;&lt Back to category management page. </a></p>‘;

 

?>
    
    
    </div>
 
     <div class=“footer“> 
          <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
    </div>
    
      
</body>
</html>

Conclusion and other thoughts

Our code snipets create baseline for required functionality for category management. From final code was omited parts related to user login and loged users persisency. Full bazaar app code can be obtaned from github here.