SitePoint Sponsor

User Tag List

Page 5 of 6 FirstFirst 123456 LastLast
Results 101 to 125 of 150
  1. #101
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    Hmm, well the parts I see as being relevant, although I do not fully understand, are as follows:

    session_start();
    $session = session_id
    ();

    if(!isset(
    $_COOKIE['Cookie'
    ])) {
    # no COOKIEs exist so create new one
    #
    setcookie("Cookie", $session, time() + ((3600 * 24) * $cfg['COOKIE_DURATION'
    ]));
    }
    else {
    # found COOKIEs so update
    #
    $session = $_COOKIE["Cookie"
    ];
    setcookie("Cookie", $session, time() + ((3600 * 24) * $cfg['COOKIE_DURATION'
    ]));
    }

    # check for framework SESSIONs
    #
    if(!isset($_SESSION
    )) {
    # no SESSIONs exist so create new one
    #
    $_SESSION['Session']['UserId'
    ];
    $_SESSION['Session']['UserAccess'
    ];

    $_SESSION['Session']['Username'
    ];
    $_SESSION['Session']['Password'
    ];

    $_SESSION['Session']['MenuState'
    ];
    $_SESSION['Session']['MenuCommand'
    ];
    }


    1. I understand I need to implement sessions, fine.
    2. I am not sure if I will need cookies and, therefore, appropriate expiration time-out values?
    3. I am not sure what session variables I will need.. any ideas (username/password etc)?
    4. I'm not sure where this code should go in my structure (detailed below).
    5. However, the first thing I want to do is simply display the form again after submission so the user can correct any errors.
    I can then try and implement an error-count array and utilise that to display the errors in red at the top of the form (somehow), for example.

    Could you advise me how to ammend my structure (below) to accommodate point 5?

    Once that is done, then I can move on to the rest.. bitesize. [img]images/smilies/biggrin.gif[/img]

    Current structure is as follows:
    PHP Code:
    <?php if (isset($_POST['submit'])) { // a new member joins using the form below
    // Form validation
    else { 
    // If validation is all TRUE, then enter a record into DB
    }
    } else { 
    // Drop-down box queries
    ?>
    // Start FORM
    ...
    // End FORM
    <?php
    // end if main if else statement for if the form has been submitted
    ?>
    Thanks.

    Mak [img]images/smilies/smile.gif[/img]

  2. #102
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry...not much time - I was about to log off then I'd seen you posted again so here goes w/ some structures that you may need first before scripting.

    PHP Code:
    if(!isset($_POST['_SubmitForm'])) {
    # FORM not sent so ask user to log in - first time
    }
    else {
    # FORM has been sent so need to look at values
    #
    $Username = (string) $_POST['Username'];
    $Password = (string) $_POST['Password'];
    # get values from FORM user has sent
    # make sure NAME of INPUTs each have
    # Username and Password...
    # or $_POST values will hold nothing
    #
    $ErrorArray = array();
    # I will only check for empty inputs
    # you can check for proper formats yourself
    # though the structure is basically the same (no time at the moment y/see)
    #
    if(empty($Username)) {
    $ErrorArray[] = 'Please Enter your Username.';
    }
    if(empty(
    $Password)) {
    $ErrorArray[] = 'Please Enter your Password.';
    }
    # now array will hold what ever error you want
    # based on user forgetting to enter their
    # Username and/or Password
    #
    # If no errors, then $ErrorArray will be empty
    #
    # Now chech $ErrorArray
    # If empty - i.e. no errors then log user in
    # else re-display FORM again w/ error messages
    #
    if(empty($ErrorArray)) {
    # no errors so log user in....
    # this is where your sessions come in
    # look at script I posted to help you out

    else {
    # found one or more errors
    foreach($ErrorArray as $error) {
    echo(
    '<b>'$error .'</b><br />');
    }
    # now display your FORM here again using
    # same HTML etc - FORM variables and all
    # closing off the else condition if no FORM sent
    # close off function 
    No definite script as such though the method of gathering/printing errors is the standard method used by any number of PHP users and it's generally what you really need to use w/ minimum complications etc. 8)

  3. #103
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question

    Hi

    Quick question.. where abouts in my structure should I start this? i.e. before:

    <?php if (isset($_POST['submit'])) { // a new member joins using the form below

    Or after? Or at a particular point.. if you could indicate that please.

    Thanks.

    Mak

  4. #104
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This part actually checks if a FORM has been sent of not - by looking to see if the variable has been set.

    The variable NAME exists w/in the SUBMIT of the FORM. If the variable isn't set, you display the FORM.

    If this variable is set (ie FORM sent) you then check for input errors by the user, and display them if found... as I earlier described and ALSO re-display your FORM again.

    If no errors found then you go ahead and put their (ie users) inputs into the database or whatever you need to do with them 8)
    PHP Code:
    .
    .
    <
    form type='submit' name='_SubmitForm_' value='Send Form' />
    .

    May I suggest that you use a seperate function to display your FORM ? Thus you can seperate this function from the actual piece of script you have that validates the inputs and deals with the logic procress....

    It'll make your job a lot easier, plus you will have less typing to do 8) Another thing, your script will be a lot easier to read and debug as well....

    -- EDIT --

    You would place this at the top of your page - this is the piece of script that actually kicks things off for you 8)

    Your script logic process HAS to begin with this part, so you know what part of your script is being used....

  5. #105
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    Thanks for your help so far.. much appreciated. [img]images/smilies/biggrin.gif[/img]

    Okay, so far I have:
    PHP Code:
    <?php if(!isset($_POST['_SubmitForm'])) {
    echo 
    "Form not sent, so ask user to log in for the first time";
    }

    else {
    # FORM has been sent so need to look at values
    $Username = (string) $_POST['Username'];
    $Password = (string) $_POST['Password'];
    // (1) DO I DO THE ABOVE FOR *ALL* THE VARIABLES OF THE FORM?
    PHP Code:
     $ErrorArray = array();

    // ------------------- START FORM VALIDATION -------------------

    if (!ereg ("[a-zA-Z]{1,}"$_POST["Forename"])) {
    $ErrorArray[] = "Please enter a Forename consisting of alphabetical characters.";
    ... 
    etc
    // ------------------- END FORM VALIDATION
    if(empty($ErrorArray)) {
    # no errors so log user in....
    # this is where your sessions come in
    }
    else {
    # found one or more errors
    $nerrors count($ErrorArray);
    if(
    $nerrors 0) {
    echo 
    "\n".'<p>'.$nerrors.' error(s) found</p>';
    echo 
    "\n".'<ol>';
    for (
    $i 0$i $nerrors$i++)
    echo 
    "\n".'<li>'.$errors[$i].'</li>';
    echo 
    "\n".'</ol>';
    exit;

    }
    # Now display FORM here again using same HTML, variables and all 
    // Before I had the following here:
    // (2) the PHP part
    PHP Code:
    <?php if (isset($_POST['submit'])) { // a new member joins using the form below
    // (3) Here is where the previous form validation went and then I have..
    PHP Code:
    // generate and execute query
    $query = "INSERT INTO Members SET 
    ...
    // generate and execute query 2
    $query2 = "INSERT INTO Lookup SET
    ...
    }
    } else {
    // ------------START DROP-DOWN BOX QUERIES --------
    ... etc
    // ------------ END drop-down box queries
    <! ------------------- START FORM ------------------- >

    <FORM NAME="mainform" ACTION="<?php echo($_SERVER['PHP_SELF']); ?>" METHOD="POST">

    } # closing off the else condition if no FORM sent
    } # close off function
    1. Do I do (1) above for all the variables?
    2. So should I get rid of (2) and (3) above?
    3. Then where should I start my form? After the drop-down boxes but in the way you suggested?:
    PHP Code:
     <form type='submit' name='_SubmitForm_' value='Send Form' /> 
    Or before the drop-down boxes?

    Thanks.

    Mak [img]images/smilies/smile.gif[/img]

  6. #106
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello, got your PM - you said look at page 5 - though I have the threads in reverse, so you actually meant was to look at page 1 in my case

    But what did I do ? Yes - looked at page 5, page 2 in your case

    point1 : yes, for all form INPUTs that you need to validate user inputs, put the $_POST[] values to variables, and Reg. Exp. them.

    point2 : Keep this part as it's the only way you have to check if the form has been sent of not.

    point2.1 : if not sent, then display the FORM by default. If sent, then check for user input against valid inputs; if okay then insert the user inputs into required database table(s), else if there are errors, you need to display the FORM again, though with the user inputs that were correct, leaving the ones - form INPUT elements w/ bad inputs - blank, and report - ECHO - errors found in the errors array.

    point3 : I would assume that the dropdown SELECT box would be part of the form, no ? At the moment you have it before the FORM so it proberly wouldn't get included w/ the other data sent by the form once the user submitted the form, if you follow ?

    So best bet would be to include the dropdown SELECT box within the <form...>....</form> somewhere convienent.

    Hope this helps you out ? Btw... once you've put the data sent by the user into the database table(s) you'd normally re-direct to another page....

    .... so if the user clicks <back or F5 - refresh - the form isn't submitted a second time - thus you get duplicate data in the database, which you want to avoid.

    Just a tip really, though you don't HAVE to re-direct - which could be any page you want such as a thank you page etc.

  7. #107
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Okay and now..

    Hi

    Okay so after the part:
    PHP Code:
    <?php if (isset($_POST['submit'])) { // a new member joins using the form below
    I was wondering if you could elaborate a bit on how to code point 2.1:

    a. if not sent, then display the FORM by default.

    b. If sent, then check for user input against valid inputs; if okay then insert the user inputs into required database table(s), else if there are errors, you need to display the FORM again, though with the user inputs that were correct, leaving the ones - form INPUT elements w/ bad inputs - blank,

    c. Report - ECHO - errors found in the errors array.

    Thanks.

    Mak [img]images/smilies/smile.gif[/img]

  8. #108
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    point2.1 : if not sent, then display the FORM by default. If sent, then check for user input against valid inputs; if okay then insert the user inputs into required database table(s), else if there are errors, you need to display the FORM again, though with the user inputs that were correct, leaving the ones - form INPUT elements w/ bad inputs - blank, and report - ECHO - errors found in the errors array.
    Okay, here is a more descriptive structured english (as it is known in college nowadays - still is ? I don't know since it's been a while) format for you

    2.1:
    2.1.1: FORM has been submitted ?
    2.1.2: No, so:
    2.1.2.1: Display the FORM
    2.1.3: Yes, so:
    2.1.3.1: Get user INPUTs from $_POST
    2.1.3.2: Create $ErrorArray variable
    2.1.3.3: Check each INPUT from user
    2.1.3.4: Is INPUT value valid ?
    2.1.3.4.1: No, so:
    2.1.3.4.2: Put an error to $ErrorArray

    PHP Code:
    # ie
    $ErrayArray[] = 'Please complete your Email Address.';
    .
    .
    # next INPUT 
    2.1.3.5: Now completed user INPUTs validation
    2.1.3.6: Test to see if $ErrorArray has any values
    2.1.3.6.1: [NOTE] If so then bad INPUTs so DON'T put INPUTs to database
    2.1.3.7: Arrive here so to re-display FORM.

    Okay, this is about the best I can really explain how to do this. Really, it isn't a difficult task to do

    See how you get on with checking for user INPUTs against bad validation first; putting error messages to the $ErrorArray first before you move onto next part.

  9. #109
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    This is what I got..

    Hi

    Okay, that sounds pretty clear. I have attempted to do that and have adjusted the script as follows. However, although the script runs fine without any reported errors, nothing happens!

    Can you see where I am going wrong please?

    Thanks.

    Mak
    PHP Code:
    <?php 
     
    if(!isset($_POST['_SubmitForm'])) {
     
     
    //2.1:
     //2.1.1: FORM has been submitted ?
     //2.1.2: No, so:
     //2.1.2.1: Display the FORM
     
     //  START DROP-DOWN BOX QUERIES 
     // START FORM 
     
    ?>
     <FORM TYPE="SUBMIT" NAME="_SubmitForm_" ACTION="<?php echo($_SERVER['PHP_SELF']); ?>" METHOD="POST">
    <TABLE.... 
    ... etc
    <! ------------------- END FORM  ------------------- >
          
    <?php
     
    }
     
    //2.1.3: Yes, so:
     //2.1.3.1: Get user INPUTs from $_POST
    else {
      
    # FORM has been sent so need to look at values
      
    $Forename   = (string) $_POST['Forename'];
      
    $Surname   = (string) $_POST['Surname'];
    ... 
    etc
     
    //2.1.3.2: Create $ErrorArray variable
      
    $ErrorArray = array();
     
      
    //2.1.3.3: Check each INPUT from user
      // START FORM VALIDATION
     
    if (!ereg ("[a-zA-Z]{1,}"$_POST["Forename"])) {
           
    $ErrorArray[] = "Please enter a Forename consisting of alphabetical characters.";
      }
      
    // Validate Surname
      
    elseif (!ereg ("[a-zA-Z]{1,}"$_POST["Surname"])) {
           
    $ErrorArray[] = "Please enter a Surname consisting of alphabetical characters.";
      }
    ... 
    etc
     
    // END FORM VALIDATION
      //2.1.3.5: Now completed user INPUTs validation
      //2.1.3.6: Test to see if $ErrorArray has any values
      
      
    if(empty($ErrorArray)) {
       
    # no errors so log user in....
       # this is where your sessions come in
     
    // generate and execute query
      
    $query "INSERT INTO Members SET
    ... etc
    $memberID = mysql_insert_id();
     
    // generate and execute query 2

      
    $query2 = "INSERT INTO Lookup SET
    ... etc
     
    $result2 
    mysql_query($query2) or die ("Error in query 2: $query2. " mysql_error());   
      }
      else {
       
    // Found one or more errors
       
    $nerrors count($ErrorArray);
       if(
    $nerrors 0) {
        echo 
    "\n".'<p>'.$nerrors.' error(s) found</p>';
        echo 
    "\n".'<ol>';
        for (
    $i 0$i $nerrors$i++)
         echo 
    "\n".'<li>'.$errors[$i].'</li>';
         echo 
    "\n".'</ol>';
         exit;
        }
       }
      }
    ?>
    </TABLE...

  10. #110
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You have the following in your script:

    PHP Code:
    //2.1.3.3: Check each INPUT from user
      // START FORM VALIDATION
    if (!ereg ("[a-zA-Z]{1,}"$_POST["Forename"])) {
           
    $ErrorArray[] = "Please enter a Forename consisting of alphabetical characters.";
      }
      
    // Validate Surname
      
    elseif (!ereg ("[a-zA-Z]{1,}"$_POST["Surname"])) {
           
    $ErrorArray[] = "Please enter a Surname consisting of alphabetical characters.";
      } 
    Which will not work properly due to the conditioning, what you'd need to do is check the variables independently; as such you should use 2 IF conditions only, for example:

    PHP Code:
    //2.1.3.3: Check each INPUT from user
      // START FORM VALIDATION
    if (!ereg ("[a-zA-Z]{1,}"$_POST["Forename"])) {
           
    $ErrorArray[] = "Please enter a Forename consisting of alphabetical characters.";
      }

      
    // Validate Surname
      
    if (!ereg ("[a-zA-Z]{1,}"$_POST["Surname"])) {
           
    $ErrorArray[] = "Please enter a Surname consisting of alphabetical characters.";
      } 
    As to your problem... I'm still looking

  11. #111
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay you have this:

    PHP Code:
    for ($i 0$i $nerrors$i++)
         echo 
    "\n".'<li>'.$errors[$i].'</li>';
         echo 
    "\n".'</ol>';
         exit; 
    Maybe try this instead:

    PHP Code:
    foreach($nerrors as $error) {
    echo(
    'You have this error:'.$error.' Please correct it.');

    By the look of your script - very end part - you are using another TABLE ?

    First, where is your FORM for the user to correct his/her errors ? Also re-check your condition braces in there again to see if there is one of those out of place - which could stop the FOREACH happening.

  12. #112
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    Okay, I have altered the 'error display' code as suggested.

    At the very end of the script that is:
    PHP Code:
    </TABLE.. 
    i.e. the close of the table that I began at the top.

    I do not have a FORM for the user to correct their errors, where do you advise I put this in the code (or on another re-directed page)? Also, how do I have the 'previously entered but okay' values in their respective fields within this FORM?

    Thanks.

    Mak [img]images/smilies/smile.gif[/img]

  13. #113
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If there are errors then put the FORM script after your section of script which displays the errors.

    As to your other question; looking into it as I type

  14. #114
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    Okay I have ammended it thus:
    PHP Code:
    else {
       // Found one or more errors
       $nerrors = count($ErrorArray);
       foreach($nerrors as $error) {
        echo('You have this error:'.$error.' Please correct it.');
       } 
    ?>
    // FORM same as earlier
    <FORM... etc
    </FORM>
          
          <! ------------------- END FORM  ------------------- >
    <?php   
       
      
    }
    }
    ?>
    Eagerly awaiting your reply as you type

    Thanks.

    Mak

  15. #115
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    ?>
    // FORM same as earlier
    <FORM... etc
    </FORM>
          
          <! ------------------- END FORM  ------------------- >
    <?php
    Can you post the complete FORM ? It'd help so much...


  16. #116
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Doc

    Mailed you the form through SitePoint. Let me know what you think!

    Thanks.

    Mak

  17. #117
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy Nothing happens!

    Hi all

    What I have now is as follows but when submitting the form, nothing actually happens! i.e. No validation/error messages are displayed in regards to submitting a blank form/fields. [img]images/smilies/confused.gif[/img]

    Can anyone else help please?

    Thanks.

    Mak [img]images/smilies/smile.gif[/img]
    PHP Code:
    <?php 
    if(!isset($_POST['_SubmitForm'])) {
    // FORM NOT SUBMITTED SO DISPLAY FORM
    // Drop-down box queries
    // START FORM
    <FORM TYPE="SUBMIT" NAME="_SubmitForm_" ACTION="<?php echo($_SERVER['PHP_SELF']); ?>" METHOD="POST">
    ... 
    etc
    </FORM
    // END FORM
    } else {
    // FORM SUBMITTED

    // Get user inputs from $_POST
    # FORM has been sent so need to look at values
    $Forename = (string) $_POST['Forename'];
    $Surname = (string) $_POST['Surname'];
    ... 
    etc
    // Create ErrorArray Variable
    $ErrorArray = array();
    // Check each input form user
    // START FORM VALIDATION
    if (!ereg ("[a-zA-Z]{1,}"$_POST["Forename"])) {
    $ErrorArray[] = "Please enter a Forename consisting of alphabetical characters.";
    }
    // Validate Surname
    if (!ereg ("[a-zA-Z]{1,}"$_POST["Surname"])) {
    $ErrorArray[] = "Please enter a Surname consisting of alphabetical characters.";
    }
    ... 
    etc
    // END FORM VALIDATION
    // Test to see if ErrorArray has any values
    if(empty($ErrorArray)) {
    # no errors so log user in....
    # this is where sessions come in!!!
    // Enter record into database
    }
    else {
    // Found one or more errors
    $nerrors count($ErrorArray);
    foreach(
    $nerrors as $error) {
    echo(
    'You have this error:'.$error.' Please correct it.');
    }

    // Now display your FORM here again
    ?>
    <FORM TYPE="SUBMIT" NAME="_SubmitForm_" ACTION="<?php echo($_SERVER['PHP_SELF']); ?>" METHOD="POST">
    ... etc
    </FORM>
    <! ------------------- END FORM ------------------- >
    <?php 

    }
    }
    ?>
    Last edited by mak-uk; May 28, 2003 at 16:58.

  18. #118
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi all,

    I have now actually gotten all of the above done.. lotta hard work!

    What I was wondering now is if someone could help me with sessions?

    I have read some tutorials from Sitepoint and I understand that sessions are useful for information which is required to be pesistent throught the users' visit to a website.

    In my case, this mock dating site thing, the obvious things I would need to be persistent are:

    1. Username
    2. Password

    Can anyone think of anything else that I might need?

    Anyway, if anyone can help me out in regards to a start with sessions (in the context of this mock dating site), I really would be grateful.

    Thanks.

    Mak

  19. #119
    blonde.... Sarah's Avatar
    Join Date
    Jul 2001
    Location
    Berkshire, UK
    Posts
    7,442
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Mak,

    well done and I bet that you learn heaps from doing it too

    Anyway check out this articles all about sessions here http://www.sitepoint.com/article/319

    What I would suggest you do is only store the username/password as I think that is all that you need.

    The tutorial is all you need and that script is something that you will include to the top of every page,

    anyway follow the article and then yell when you get stuck

    Sarah
    Regular user

  20. #120
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First of all, create your SESSIONs at the top of your webpage; before any kind of output or you will get an error message;ie
    PHP Code:
    <?php 
    # top of pageif(!isset($_SESSION['Username'])) 
    {
    $_SESSION['Username'] = '';$_SESSION['Password'] = '';} # now created 2 SESSION variables
    The above will create Username and Password SESSION variables if they don't already exist. Next you need to check if a user has logged in ? This is easy;
    PHP Code:
    if($_SESSION['Username'] == (string) '' || $_SESSION['Password'] == (string) '') {# redirect to login pageHeader('location:login.php');}# reach here ? Then continue... 
    This should get you started ? [img]images/smilies/biggrin.gif[/img]

    --EDIT--
    The bloody TEXTAREA for this forum is screwing up the formatting etc. Why ? Think SitePoint had better think about getting another forum builder ?

  21. #121
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy Starting with sessions

    Hi

    Well, firstly, thought I would try Kevin's session tutorial.

    I have the two required includes:
    PHP Code:
    <?php // db.php 
    $dbhost "localhost"
    $dbuser "******"
    $dbpass "******"
    function 
    dbConnect($db="") { 
       global 
    $dbhost$dbuser$dbpass
        
       
    $dbcnx = @mysql_connect($dbhost$dbuser$dbpass
           or die(
    "The site database appears to be down."); 
       if (
    $db!="" and ![email=@mysql_select_db($db]!@mysql_select_db($db[/email])) 
           die(
    "The site database is unavailable."); 
        
       return 
    $dbcnx

    ?>
    PHP Code:
    <?php // common.php 
    function error($msg) { 
       
    ?> 
       <html> 
       <head> 
       <script language="JavaScript"> 
       <!-- 
           alert("<?=$msg?>"); 
           history.back(); 
       //--> 
       </script> 
       </head> 
       <body> 
       </body> 
       </html> 
       <? 
       
    exit; 

    ?>
    Then comes the access control script:
    PHP Code:
    <?php // accesscontrol.php
    session_start();
    include(
    "common.php");
    include(
    "db.php");
     
    if(!isset(
    $uid)) { 
     
    ?> 
     <html> 
     <head> 
     <title> Please Log In for Access </title> 
     </head> 
     <body> 
     <h1> Login Required </h1> 
     <p>You must log in to access this area of the site. If you are 
        not a registered user, <a href="signup.php">click here</a> 
        to sign up for instant access!</p> 
     <p><form method="post" action="<?=$PHP_SELF?>"> 
       User ID: <input type="text" name="uid" size="8"><br> 
       Password: <input type="password" name="pwd" SIZE="8"><br> 
       <input type="submit" value="Log in"> 
     </form></p> 
     </body> 
     </html> 
     <?php 
     
    exit; 
    }
    session_register("uid");
    session_register("pwd");
    dbConnect("sessions"); 
    $sql "SELECT * FROM user WHERE 
           userid = '
    $uid' AND password = PASSWORD('$pwd')"
    $result mysql_query($sql); 
    if (!
    $result) { 
     
    error("A database error occurred while checking your "
           
    "login details.\\nIf this error persists, please "
           
    "contact [email=kevin@sitepoint.com]kevin@sitepoint.com[/email]."); 
    }
    if (
    mysql_num_rows($result) == 0) { 
     
    session_unregister("uid"); 
     
    session_unregister("pwd"); 
     
    ?> 
     <html> 
     <head> 
     <title> Access Denied </title> 
     </head> 
     <body> 
     <h1> Access Denied </h1> 
     <p>Your user ID or password is incorrect, or you are not a 
        registered user on this site. To try logging in again, click 
        <a href="<?=$PHP_SELF?>">here</a>. To register for instant 
        access, click <a href="signup.php">here</a>.</p> 
     </body> 
     </html> 
     <?php 
     
    exit; 
    }
    $username mysql_result($result,0,"fullname");
    ?>
    FINALLY, the actual sign-up script:
    PHP Code:
    <?php // signup.php
    include("common.php");
    include(
    "db.php");
    if (!isset(
    $submitok)): 
       
    // Display the user signup form 
       
    ?> 
        
       <html> 
       <head><title>New User Registration</title></head> 
       <body> 
    <h3>New User Registration Form</h3> 
    <p><font color=orangered size=+1><TT><B>*</B></TT></font> 
      indicates a required field</p> 
    <form method=post action="<?=$PHP_SELF?>"> 
    <table border=0 cellpadding=0 cellspacing=5> 
       <tr> 
           <td align=right> 
               <p>User ID</p> 
           </td> 
           <td> 
               <input name=newid type=text maxlength=100 size=25> 
               <font color=orangered size=+1><TT><B>*</B></TT></font> 
           </td> 
       </tr> 
       <tr> 
           <td align=right> 
               <p>Full Name</p> 
           </td> 
           <td> 
               <input name=newname type=text maxlength=100 size=25> 
               <font color=orangered size=+1><TT><B>*</B></TT></font> 
           </td> 
       </tr> 
       <tr> 
           <td align=right> 
               <p>E-Mail Address</p> 
           </td> 
           <td> 
               <input name=newemail type=text maxlength=100 size=25> 
               <font color=orangered size=+1><TT><B>*</B></TT></font> 
           </td> 
       </tr> 
       <tr valign=top> 
           <td align=right> 
               <p>Other Notes</p> 
           </td> 
           <td> 
               <textarea wrap name=newnotes rows=5 cols=30></textarea> 
           </td> 
       </tr> 
       <tr> 
           <td align=right colspan=2> 
               <hr noshade color=black> 
               <input type=reset value="Reset Form"> 
               <input type=submit name="submitok" value="   OK   "> 
           </td> 
       </tr> 
    </table> 
    </form> 
    </body> 
    </html>
    <?php 
    else: 
       
    // Process signup submission 
       
    dbConnect('sessions');
     if (
    $newid=="" or $newname=="" or $newemail=="") { 
           
    error("One or more required fields were left blank.\\n"
                 
    "Please fill them in and try again."); 
       }
     
     
    // Check for existing user with the new id 
       
    $sql "SELECT COUNT(*) FROM user WHERE userid = '$newid'"
       
    $result mysql_query($sql); 
       if (!
    $result) {   
           
    error("A database error occurred in processing your "
                 
    "submission.\\nIf this error persists, please "
                 
    "contact [email=kevin@sitepoint.com]kevin@sitepoint.com[/email]."); 
       } 
       if (@
    mysql_result($result,0,0)>0) { 
           
    error("A user already exists with your chosen userid.\\n"
                 
    "Please try another."); 
       }
       
       
    $newpass substr(md5(time()),0,6);
       
       
    $sql "INSERT INTO user SET 
                 userid = '
    $newid', 
                 password = PASSWORD('
    $newpass'), 
                 fullname = '
    $newname', 
                 email = '
    $newemail', 
                 notes = '
    $newnotes'"
       if (!
    mysql_query($sql)) 
           
    error("A database error occurred in processing your "
                 
    "submission.\\nIf this error persists, please "
                 
    "contact [email=kevin@sitepoint.com]kevin@sitepoint.com[/email].");
     
    // Email the new password to the person. 
       
    $message "G'Day! 
    Your personal account for the Project Web Site 
    has been created! To log in, proceed to the 
    following address: 
       [url=http://www.theproject.com/]http://www.theproject.com/[/url] 
    Your personal login ID and password are as 
    follows: 
       userid: 
    $newid 
       password: 
    $newpass 
    You aren't stuck with this password! Your can 
    change it at any time after you have logged in. 
    If you have any problems, feel free to contact me at 
    <[email=kevin@sitepoint.com]kevin@sitepoint.com[/email]>. 
    -Kevin Yank 
    Project Webmaster 
    "

       
    mail($newemail,"Your Password for the Project Website"
            
    $message"From:Kevin Yank <[email=kevin@sitepoint.com]kevin@sitepoint.com[/email]>");
    ?> 
       <html> 
       <head><title> Registration Complete </title></head> 
       <body> 
       <p><strong>User registration successful!</strong></p> 
       <p>Your userid and password have been emailed to 
          <strong><?=$newemail?></strong>, the email address 
          you just provided in your registration form. To log in, 
          click <a href="index.php">here</a> to return to the login 
          page, and enter your new personal userid and password.</p> 
       </body> 
       </html> 
       <?php 
    endif; 
    ?>
    Now, I have the DB (called 'sessions) created as well as the table 'user':
    PHP Code:
    CREATE TABLE `user` (
      `
    IDint(11NOT NULL auto_increment,
      `
    useridvarchar(100NOT NULL default '',
      `
    passwordvarchar(16NOT NULL default '',
      `
    fullnamevarchar(100NOT NULL default '',
      `
    emailvarchar(100NOT NULL default '',
      `
    notestext,
      
    PRIMARY KEY  (`ID`),
      
    UNIQUE KEY `userid` (`userid`)
    TYPE=MyISAM AUTO_INCREMENT=
    The sign-up script works in that it loads, however, when I type some details and press 'OK' to submit, nothing actually happens?!

    Can you guys see what I am doing wrong?

    Thanks.

    Mak

  22. #122
    SitePoint Author Kevin Yank's Avatar
    Join Date
    Apr 2000
    Location
    Melbourne, Australia
    Posts
    2,571
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Is register_globals set to Off in your php.ini? Those scripts were written for register_globals On.
    Kevin Yank
    CTO, sitepoint.com
    I wrote: Simply JavaScript | BYO PHP/MySQL | Tech Times | Editize
    Baby’s got back—a hard back, that is: The Ultimate CSS Reference

  23. #123
    SitePoint Addict mak-uk's Avatar
    Join Date
    Dec 2001
    Location
    Midlands, UK
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    Would modern PHP hosts have register_globals off though? If so, how do I modify the scripts accordingly?

    If not, is it just a case of setting the value to 'on'?

    Thanks.

    Mak [img]images/smilies/smile.gif[/img]
    Last edited by mak-uk; Jun 12, 2003 at 15:10.

  24. #124
    SitePoint Author Kevin Yank's Avatar
    Join Date
    Apr 2000
    Location
    Melbourne, Australia
    Posts
    2,571
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Modern PHP hosts will have the setting Off.

    This issue is covered in detail in my article, "Write Secure Scripts with PHP 4.2!" on SitePoint.
    Kevin Yank
    CTO, sitepoint.com
    I wrote: Simply JavaScript | BYO PHP/MySQL | Tech Times | Editize
    Baby’s got back—a hard back, that is: The Ultimate CSS Reference

  25. #125
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Or this article I wrote last summer when the ini setting change was about to take place:
    Coding PHP with register_globals Off
    HTH
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •