Visualizzazione dei risultati da 1 a 4 su 4
  1. #1

    autenticazione degli utenti

    ciao a tutti ho da poco inziato a studiare il php con il libro "sviluppare applicazioni web con php e mysql" al capitolo 20 c' è un esempio di autenticazione utente che mi da:
    Fatal error: Cannot redeclare class InvalidArgumentException in C:\www\Chapter20\errors.inc on line 9


    il codice è il seguente:

    newuser_form.php

    <?php session_start(); ?>

    <html>
    <head>
    <title>New User Form</title>
    </head>
    <body>
    <p align='center'>
    Please Enter your User Information:
    </p>
    <form action='create_user.php' method='post'>
    <table align='center' width='100%' border='0'>
    <tr>
    <td width='30%'>User Name:</td>
    <td>
    <input type='text' size='30' name='username'/>
    </td>
    </tr>
    <tr>
    <td width='30%'>Password:</td>
    <td>
    <input type='password' size='30' name='password1'/>
    </td>
    </tr>
    <tr>
    <td width='30%'>Password (confirm):</td>
    <td>
    <input type='password' size='30' name='password2'/>
    </td>
    </tr>
    <tr>
    <td width='30%'>Full Name:</td>
    <td>
    <input type='text' size='30' name='fullname'/>
    </td>
    </tr>
    <tr>
    <td width='30%'>Email Address:</td>
    <td>
    <input type='text' size='30' name='emailaddr'/>
    </td>
    </tr>
    <tr>
    <td width='30%'>Birth Date:</td>
    <td>
    Year: <select name='year'>
    <option value='--'> --
    <option value='1999'>1999
    <option value='1998'>1998
    <option value='1997'>1997
    <option value='1996'>1996
    <option value='1995'>1995
    <option value='1994'>1994
    <option value='1993'>1993
    <option value='1992'>1992
    <option value='1991'>1991
    <option value='1990'>1990
    <option value='1989'>1989
    <option value='1988'>1988
    <option value='1987'>1987
    <option value='1986'>1986
    <option value='1985'>1985
    <option value='1984'>1984
    <option value='1983'>1983
    <option value='1982'>1982
    <option value='1981'>1981
    <option value='1980'>1980
    <option value='1979'>1979
    <option value='1978'>1978
    <option value='1977'>1977
    <option value='1976'>1976
    <option value='1975'>1975
    <option value='1974'>1974
    <option value='1973'>1973
    <option value='1972'>1972
    <option value='1971'>1971
    <option value='1970'>1970
    <option value='1969'>1969
    <option value='1968'>1968
    <option value='1967'>1967
    <option value='1966'>1966
    <option value='1965'>1965
    <option value='1964'>1964
    <option value='1963'>1963
    <option value='1962'>1962
    <option value='1961'>1961
    <option value='1960'>1960
    <option value='1959'>1959
    <option value='1958'>1958
    <option value='1957'>1957
    <option value='1956'>1956
    <option value='1955'>1955
    <option value='1954'>1954
    <option value='1953'>1953
    <option value='1952'>1952
    <option value='1951'>1951
    <option value='1950'>1950
    <option value='1949'>1949
    <option value='1948'>1948
    <option value='1947'>1947
    <option value='1946'>1946
    <option value='1945'>1945
    <option value='1944'>1944
    <option value='1943'>1943
    <option value='1942'>1942
    <option value='1941'>1941
    <option value='1940'>1940
    <option value='1939'>1939
    <option value='1938'>1938
    <option value='1937'>1937
    <option value='1936'>1936
    <option value='1935'>1935
    <option value='1934'>1934
    <option value='1933'>1933
    <option value='1932'>1932
    <option value='1931'>1931
    <option value='1930'>1930
    </select>
    Month: <select name='month'>
    <option value='--'> --
    <option value='01'>01
    <option value='02'>02
    <option value='03'>03
    <option value='04'>04
    <option value='05'>05
    <option value='06'>06
    <option value='07'>07
    <option value='08'>08
    <option value='09'>09
    <option value='10'>10
    <option value='11'>11
    <option value='12'>12
    </select>
    Day: <select name='day'>
    <option value='--'> --
    <option value='01'>01
    <option value='02'>02
    <option value='03'>03
    <option value='04'>04
    <option value='05'>05
    <option value='06'>06
    <option value='07'>07
    <option value='08'>08
    <option value='09'>09
    <option value='10'>10
    <option value='11'>11
    <option value='12'>12
    <option value='13'>13
    <option value='14'>14
    <option value='15'>15
    <option value='16'>16
    <option value='17'>17
    <option value='18'>18
    <option value='19'>19
    <option value='20'>20
    <option value='21'>21
    <option value='22'>22
    <option value='23'>23
    <option value='24'>24
    <option value='25'>25
    <option value='26'>26
    <option value='27'>27
    <option value='28'>28
    <option value='29'>29
    <option value='30'>30
    <option value='31'>31
    </select>
    </td>
    </tr>
    </table>



    <input type='submit' value='Create Account'/>
    </p>
    </form>
    </body>
    </html>

    create_user.php

    <?php

    require_once('user_manager.inc');
    require_once('errors.inc');

    //
    // 1. in the interest of brevity, we're going
    // to omit a few of the security features suggested in
    // Chapter 15: "Cookies and Sessions".
    //
    session_start();

    //
    // 2. Validate full input.
    //
    $uname = isset($_POST['username']) ? $_POST['username'] : '';
    $pw1 = isset($_POST['password1']) ? $_POST['password1'] : '';
    $pw2 = isset($_POST['password2']) ? $_POST['password2'] : '';
    $fname = isset($_POST['fullname']) ? $_POST['fullname'] : '';
    $email = isset($_POST['emailaddr']) ? $_POST['emailaddr'] : '';
    $year = isset($_POST['year']) ? intval($_POST['year']) : 0;
    $month = isset($_POST['month']) ? intval($_POST['month']) : 0;
    $day = isset($_POST['day']) ? intval($_POST['day']) : 0;

    //
    // a. mandatory values.
    //
    if ($uname == '' or $fname == '' or $pw1 == '' or $pw2 == '')
    {
    throw new InvalidInputException();
    }

    //
    // b. values are sane.
    //
    $usermgr = new UserManager();
    if (!$usermgr->isValidUserName($uname))
    {
    throw new InvalidInputException();
    }


    // are passwords the same?
    if ($pw1 != $pw2)
    {
    throw new InvalidInputException();
    }

    // is date sane-ish?
    if (!checkdate($month, $day, $year))
    {
    throw new InvalidInputException();
    }

    // data are okay!

    //
    // 3. Create the Account
    //
    $usermgr = new UserManager();
    $usermgr->createAccount($uname, $pw1, $fname,
    $year, $month, $day);

    //
    // 4. redirect user to login page.
    //
    header('Location: login.php');

    ?>

  2. #2
    user_manager.inc

    <?php

    require_once('dbinfo.inc');
    require_once('errors.inc');


    class UserManager
    {
    //
    // verifies that this user name doesn't have any invalid
    // characters in it. please see Chapter 17: "Data
    // Validation with Regular Expressions" for a discussion
    // of the ereg function.
    //
    public function isValidUserName($in_user_name)
    {
    if ($in_user_name == ''
    or ereg('[^[:alnum:] _-]', $in_user_name) === TRUE)
    return FALSE;
    else
    return TRUE;
    }

    //
    // - get connection
    // - make sure the user name does not already exist.
    // - add record to users table.
    //
    public function createAccount
    (
    $in_uname,
    $in_pw,
    $in_fname,
    $in_email,
    $in_year,
    $in_month,
    $in_day
    )
    {
    //
    // 0. quick input validation
    //
    if ($in_pw == '' or $in_fname == ''
    or !$this->isValidUserName($in_uname))
    {
    throw new InvalidArgumentException();
    }

    //
    // 1. get a database connection with which to work.
    // throws on failure.
    //
    $conn = $this->getConnection();

    try
    {
    //
    // 2. make sure user name doesn't already exist.
    //
    $exists = FALSE;
    $exists = $this->userNameExists($in_uname, $in_conn);
    if ($exists === TRUE)
    throw new UserAlreadyExistsException();

    //
    // 3a. make sure the parameters are safe for insertion
    // and encrypt the password for storage.
    //
    $uname = $this->super_escape_string($in_uname, $conn);
    $fname = $this->super_escape_string($in_fname, $conn);
    $email = $this->super_escape_string($in_email, $conn);
    $pw = md5($in_pw);

    //
    // 3b. create query to insert new user.
    //
    $qstr = <<<EOQUERY
    INSERT INTO Users
    (user_name,password,full_name,user_email,birthdate )
    VALUES ('$uname', '$pw', '$fname', '$email',
    '$in_year-$in_month-$in_day')
    EOQUERY;

    //
    // 3c. insert new user
    //
    $results = @$conn->query($qstr);
    if ($results === FALSE)
    throw new DatabaseErrorException($conn->error);

    //
    // we want to return the newly created user id.
    //
    $user_id = $conn->insert_id;
    }
    catch (Exception $e)
    {
    if (isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // clean up and exit
    //
    $conn->close();
    return $user_id;
    }

    //
    // - validate input
    // - get connection
    // - execute query
    // - see if we found an existing record or not.
    // - clean up connection IF necessary.
    //
    public function userNameExists
    (
    $in_uname,
    $in_db_conn = NULL
    )
    {
    //
    // 0. simple validation.
    //
    if ($in_uname == '')
    throw new InvalidArgumentException();

    //
    // 1. make sure we have a database connection.
    //
    if ($in_db_conn === NULL)
    $conn = $this->getConnection();
    else
    $conn = $in_db_conn;

    try
    {
    //
    // 2. prepare and execute query.
    //
    $name = $this->super_escape_string($in_uname, $conn);
    $qstr = <<<EOQUERY
    SELECT user_name FROM Users WHERE user_name = '$name'
    EOQUERY;

    $results = @$conn->query($qstr);
    if ($results === FALSE)
    throw new DatabaseErrorException($conn->error);

    //
    // 3. see if we found an existing record or not
    //
    $user_exists = FALSE;
    while (($row = @$results->fetch_assoc()) !== NULL)
    {
    if ($row['user_name'] == $in_uname)
    {
    $user_exists = TRUE;
    break;
    }
    }

    }
    catch (Exception $e)
    {
    //
    // clean up and re-throw the exception.
    //
    if ($in_db_conn === NULL and isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // only clean up what we allocated.
    //
    $results->close();
    if ($in_db_conn === NULL)
    $conn->close();
    return $user_exists;
    }


    //
    // - get db connection
    // - verify user name and password are valid
    // - clear out existing login information for user. (if any)
    // - log user into table (associate SID with user name).
    //
    public function processLogin($in_user_name, $in_user_passwd)
    {
    //
    // 1. internal arg checking.
    //
    if ($in_user_name == '' || $in_user_passwd == '')
    throw new InvalidArgumentException();

    $sessionid = session_id();

    //
    // 2. get a database connection with which to work.
    //
    $conn = $this->getConnection();

    try
    {
    //
    // 3. we will merge these two steps into one function
    // (and one query) so that we will not help people learn
    // whether it was the user name or password that was the
    // problem on failure.
    //
    // Note that this function will also validate that the
    // user name and password are secure and are not
    // attempts at SQL injection attacks ...
    //
    // This function will throw an InvalidLoginException if
    // the username or password are not valid.
    //
    $userid = $this->confirmUserNamePasswd($in_user_name,
    $in_user_passwd,
    $conn);

    //
    // 4. clear out existing entries in the login table.
    //
    $this->clearLoginEntriesForUser($userid);

    //
    // 5. log the user into the table.
    //
    $query = <<<EOQUERY
    INSERT INTO LoggedInUsers(user_id, session_id, last_access)
    VALUES('$userid', '$session_id', NOW())
    EOQUERY;

    $result = @$conn->query($query);
    if ($result === FALSE)
    throw new DatabaseErrorException($conn->error);
    }
    catch (Exception $e)
    {
    if (isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // our work here is done. clean up and exit.
    //
    $conn->close();
    }


    public function processLogout()
    {
    $this->clearLoginEntriesForSessionID(session_id());
    }


    public function sessionLoggedIn($in_sid)
    {
    //
    // 0. internal arg checking.
    //
    if ($in_sid == '')
    throw new InvalidArgumentException();

    //
    // 1. get a database connection with which to work.
    //
    $conn = $this->getConnection();

    try
    {
    //
    // 2. execute a query to find the given session_id
    //
    $sess_id = $this->super_escape_string($in_sid, $conn);
    $query = <<<EOQUERY
    SELECT * FROM LoggedInUsers WHERE session_id = '$sess_id'
    EOQUERY;

    $result = @$conn->query($query);
    if ($result === FALSE)
    {
    throw new DatabaseErrorException($conn->error);
    }
    else
    {
    //
    // 3. look through results for the given session id
    //
    $user_id = -1;
    while (($row = @$results->fetch_assoc()) !== NULL)
    {
    if ($row['session_id'] == $in_sess_id)
    {
    $this->updateSessionActivity($in_sess_id, $conn);
    $_SESSION['user_name'] = $row['user_name'];
    $user_id = $row['user_id'];
    break;
    }
    }
    }
    }
    catch (Exception $e)
    {
    if (isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // our work here is done. clean up and exit.
    //
    $result->close();
    $conn->close();
    return $user_id;
    }


    //
    // - check args
    // - get database connection
    // - logout user if they're logged in
    // - delete account.
    //
    public function deleteAccount($in_userid)
    {
    //
    // 0. verify parameters
    //
    if (!is_int($in_userid))
    throw new InvalidArgumentException();

    //
    // 1. get a database connection with which to work.
    //
    $conn = $this->getConnection();
    try
    {
    //
    // 2. make sure user is logged out.
    //
    $this->clearLoginEntriesForSessionID(session_id());

    //
    // 3. create query to delete given user and execute!
    //
    $qstr = "DELETE FROM Users WHERE user_id = $in_userid";
    $result = @$conn->query($qstr);
    if ($result === FALSE)
    throw new DatabaseErrorException($conn->error);
    }
    catch (Exception $e)
    {
    if (isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // clean up and go home!
    //
    $conn->close();
    }



    //
    //=----------------------=
    // private functions next
    //=----------------------=
    //



    private function getConnection()
    {
    $conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PW, DB_DB);
    if (mysqli_connect_errno() !== 0)
    throw new DatabaseErrorException(mysqli_connect_error());
    return $conn;
    }

    private function super_escape_string($in_string, $in_conn)
    {
    $str = $in_this->real_escape_string($in_string);
    return ereg_replace('([%;])', '\\\1', $in_string);
    }

    private function confirmUserNamePasswd
    (
    $in_uname,
    $in_user_passwd,
    $in_db_conn = NULL
    )
    {
    //
    // names are case insensitive, and by default, info is bad
    //
    $in_user_name = strtolower($in_user_name);

    //
    // make sure we have a database connection.
    //
    if ($in_db_conn == NULL)
    $conn = $this->getConnection();
    else
    $conn = $in_db_conn;

    try
    {
    //
    // make sure incoming user name is safe for queries.
    //
    $uname = $this->super_escape_string($in_uname, $conn);

    // get the record with this user name
    $querystr = <<<EOQUERY
    SELECT * FROM Users
    WHERE user_name = '$uname'
    EOQUERY;

    $results = @$conn->query($querystr);
    if ($results === FALSE)
    throw new DatabaseErrorException($conn->error);

    //
    // re-confirm the name matches and the passwords do too.
    //
    $login_ok = FALSE;
    while (($row = @$results->fetch_assoc()) !== NULL)
    {
    $db_name = strtolower($row['user_name']);
    if (strcmp($db_name, $in_user_name) == 0)
    {
    //
    // good, name matched. does password?
    //
    if (md5($in_user_passwd) == $row['password'])
    {
    $login_ok = TRUE;
    $userid = $row['user_id'];
    }
    else
    $login_ok = FALSE;
    break;
    }
    }
    $results->close();

    }
    catch (Exception $e)
    {
    if ($in_db_conn === NULL and isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // only clean up what we allocated.
    //
    if ($in_db_conn === NULL)
    $conn->close();

    //
    // throw on failure, or return the user id on success.
    //
    if ($login_ok === FALSE)
    throw new InvalidLoginException();

    return $userid;
    }


    private function clearLoginEntriesForUser
    (
    $in_userid,
    $in_db_conn = NULL
    )
    {
    if (!is_int($in_userid))
    throw new InvalidArgumentException();

    //
    // make sure we have a database connection.
    //
    if ($in_db_conn == NULL)
    $conn = $this->getConnection();
    else
    $conn = $in_db_conn;

    try
    {
    //
    // delete any rows for this user in the LoggedInUsers
    // table.
    $querystr = <<<EOQUERY
    DELETE FROM LoggedInUsers WHERE user_id = $in_userid
    EOQUERY;

    $results = @$conn->query($querystr);
    if ($results === FALSE)
    throw new DatabaseErrorException($conn->error);
    }
    catch (Exception $e)
    {
    if ($in_db_conn === NULL and isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // clean up and return.
    //
    if ($in_db_conn === NULL)
    $conn->close();
    }


    private function clearLoginEntriesForSessionId
    (
    $in_sid,
    $in_db_conn = NULL
    )
    {
    //
    // make sure we have a database connection.
    //
    if ($in_db_conn == NULL)
    $conn = $this->getConnection();
    else
    $conn = $in_db_conn;

    //
    // Create and execute the query to do the cleanup!
    //
    try
    {
    $sessid = $this->super_escape_string($in_sid, $conn);
    $query = <<<EOQ

  3. #3
    DELETE FROM LoggedInUsers WHERE session_id ='$sessid'
    EOQ;
    $results = @$conn->query($query);
    if ($results === FALSE or $results === NULL)
    throw new DatabaseErrorException($conn->error);
    }
    catch (Exception $e)
    {
    if ($in_db_conn === NULL and isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // clean up and return.
    //
    if ($in_db_conn === NULL)
    $conn->close();
    }

    private function updateSessionActivity
    (
    $in_sessid,
    $in_db_conn
    )
    {
    //
    // make sure we have a database connection.
    //
    if ($in_db_conn == NULL)
    $conn = $this->getConnection();
    else
    $conn = $in_db_conn;

    try
    {
    //
    // update the row for this session.
    //
    $sessid = $this->super_escape_string($in_sessid, $conn);
    $querystr = <<<EOQUERY
    UPDATE LoggedInUsers SET last_update = NOW()
    WHERE session_id = $sessid
    EOQUERY;

    $results = @$conn->query($querystr);
    if ($results === FALSE)
    throw new DatabaseErrorException($conn->error);
    }
    catch (Exception $e)
    {
    if ($in_db_conn === NULL and isset($conn))
    $conn->close();
    throw $e;
    }

    //
    // clean up and return.
    //
    if ($in_db_conn === NULL)
    $conn->close();
    }
    }

    ?>


    errors.inc

    <?php

    class InvalidArgumentException extends Exception
    {
    public function __construct()
    {
    parent::__construct('The function was called with an invalid parameter');
    }
    }

    class UserAlreadyExistsException extends Exception
    {
    public function __construct()
    {
    parent::__construct('A user with the given name already exists.');
    }
    }

    class NoSuchUserException extends Exception
    {
    public function __construct()
    {
    parent::__construct('No Such User exists');
    }
    }

    class InvalidLoginException extends Exception
    {
    public function __construct()
    {
    parent::__construct('The username and password supplied are incorrect.');
    }
    }



    class DatabaseErrorException extends Exception
    {
    public function __construct($in_msg)
    {
    parent::__construct('A database error occurred: '
    . $in_msg);
    }
    }


    class InvalidInputException extends Exception
    {
    public function __construct()
    {
    parent::__construct('The form input was incorrect');
    }
    }



    ?>


    dbinfo.inc

    <?php

    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'mbuser');
    define('DB_PW', 'mbuser');
    define('DB_DB', 'MessageBoard');

    ?>
    vi ringrazio anticipatamente per qualunque aiuto mi potrete dare

  4. #4
    grazie lo stesso mi sono aiutato da solo
    http://chipmunkninja.com/PHP-Book-Addenda-I-b@@
    ecco ilnk che mi ha salvato
    l' errore Cannot redeclare class InvalidArgumentException in C:\www\Chapter20\errors.inc on line 9 era causato dal fatto che la versione di php che uso la 5.2.6 ha gia una classe InvalidArgumentException e andava in conflitto con quella della libreria errors.in usata nell' esempio, cambiando il nome in MyInvalidArgumentException ho risolto tutto

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.