Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 12
  1. #1
    Utente di HTML.it
    Registrato dal
    Mar 2006
    Messaggi
    58

    Non mi funziona le Sessioni in locale

    Ciao a tutti... mi sto esercitando con il PHP/MySQL e sono arrivato a studiare le sessioni. Ho un problema però... mentre per esempio sul mio spazio web (altervis**) le sessioni si memorizzano, in locale (os: Windows XP pro, apache 2.2.9 / php 5.2.6) me ne crea sempre di nuove facendo il refresh della pagina, cosi la cartella di salvataggio sessione che ho specificato in php.ini mi si riempe di file di sessione invece di continuare su un'unico file.

    Vi posto lo script di esempio e la sezione riguardante le sessioni del php.ini....


    19.php
    Codice PHP:
    <?php             // le sessioni             session_start();                          if(isset($_SESSION['counter'])) {                 $_SESSION['counter']++;             } else {                 $_SESSION['counter'] = 1;             }                          var_dump($_SESSION['counter']); echo("
    ");             var_dump(session_id()); echo("
    ");             var_dump(session_name()); echo("
    ");             var_dump(session_get_cookie_params()); echo("
    ");         ?>

    php.ini
    Codice PHP:
    [Session] ; Handler used to store/retrieve datasession.save_handler files  Argument passed to save_handler.  In the case of filesthis is the path where data files are storedNoteWindows users have to change this variable in order to use PHP's session functions. ; ; As of PHP 4.0.1, you can define the path as: ; ;     session.save_path = "N;/path" ; ; where N is an integer.  Instead of storing all the session files in ; /path, what this will do is use subdirectories N-levels deep, and ; store the session data in those directories.  This is useful if you ; or your OS have problems with lots of files in one directory, and is ; a more efficient layout for servers that handle lots of sessions. ; ; NOTE 1: PHP will not create this directory structure automatically. ;         You can use the script in the ext/session dir for that purpose. ; NOTE 2: See the section on garbage collection below if you choose to ;         use subdirectories for session storage ; ; The file storage module creates files using mode 600 by default. ; You can change that by using ; ;     session.save_path = "N;MODE;/path" ; ; where MODE is the octal representation of the mode. Note that this ; does not overwrite the process's umasksession.save_path "C:\Programmi\PHP\tmp"  Whether to use cookiessession.use_cookies 1  ;session.cookie_secure =  ; This option enables administrators to make their users invulnerable to attacks which involve passing session ids in URLsdefaults to 0. session.use_only_cookies 1  Name of the session (used as cookie name). session.name PHPSESSID  Initialize session on request startupsession.auto_start 0  Lifetime in seconds of cookie or, if 0until browser is restartedsession.cookie_lifetime 0  The path for which the cookie is validsession.cookie_path = /  ; The domain for which the cookie is validsession.cookie_domain =   ; Whether or not to add the httpOnly flag to the cookiewhich makes it inaccessible to browser scripting languages such as JavaScriptsession.cookie_httponly =   ; Handler used to serialize data.  php is the standard serializer of PHPsession.serialize_handler php  Define the probability that the 'garbage collection' process is started on every session initialization. ; The probability is calculated by using gc_probability/gc_divisor, ; e.g1/100 means there is a 1chance that the GC process starts on each request.  session.gc_probability 1 session.gc_divisor     1000  After this number of secondsstored data will be seen as 'garbage' and ; cleaned up by the garbage collection processsession.gc_maxlifetime 1440  NOTE: If you are using the subdirectory option for storing session files ;       (see session.save_path above), then garbage collection does *not* ;       happen automatically.  You will need to do your own garbage ;       collection through a shell scriptcron entry, or some other method. ;       For examplethe following script would is the equivalent of ;       setting session.gc_maxlifetime to 1440 (1440 seconds 24 minutes): ;          cd /path/to/sessionsfind -cmin +24 xargs rm  PHP 4.2 and less have an undocumented feature/bug that allows you to to initialize a session variable in the global scopealbeit register_globals is disabled.  PHP 4.3 and later will warn you, if this feature is used. ; You can disable the feature and the warning separatelyAt this time, ; the warning is only displayed, if bug_compat_42 is enabled.  session.bug_compat_42 0 session.bug_compat_warn 1  Check HTTP Referer to invalidate externally stored URLs containing ids. ; HTTP_REFERER has to contain this substring for the session to be considered as validsession.referer_check =  ; How many bytes to read from the filesession.entropy_length 0  Specified here to create the session idsession.entropy_file =  ;session.entropy_length 16  ;session.entropy_file = /dev/urandom  Set to {nocache,private,public,} to determine HTTP caching aspects ; or leave this empty to avoid sending anti-caching headerssession.cache_limiter nocache  Document expires after n minutessession.cache_expire 180  trans sid support is disabled by default. ; Use of trans sid may risk your users security. ; Use this option with caution. ; - User may send URL contains active session ID ;   to other person viaemail/irc/etc. ; - URL that contains active session ID may be stored ;   in publically accessible computer. ; - User may access your site with the same session ID ;   always using URL stored in browser's history or bookmarks. session.use_trans_sid = 0  ; Select a hash function ; 0: MD5   (128 bits) ; 1: SHA-1 (160 bits) session.hash_function = 0  ; Define how many bits are stored in each character when converting ; the binary hash data to something readable. ; ; 4 bits: 0-9, a-f ; 5 bits: 0-9, a-v ; 6 bits: 0-9, a-z, A-Z, "-", "," session.hash_bits_per_character = 5  ; The URL rewriter will look for URLs in a defined set of HTML tags. ; form/fieldset are special; if you include them here, the rewriter will ; add a hidden <input> field with the info which is otherwise appended ; to URLs.  If you want XHTML conformity, remove the form entry. ; Note that all valid entries require a "=", even if no value follows. url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry" 
    Sapete consigliarmi come risolvere??? Spero soprattutto di aver reso l'idea del problema...

    Grazie anticipatamente, ciao!

  2. #2
    Utente di HTML.it L'avatar di gianiaz
    Registrato dal
    May 2001
    Messaggi
    8,027
    Stai usando dei virtual host?

  3. #3
    Utente di HTML.it
    Registrato dal
    Mar 2006
    Messaggi
    58
    sinceramente non lo so... virtual host vorrebbe dire ospitare + domini su un unico ip? se si non credo, quando uso apache/php in locale per vedere i miei file tramite browser scrivo come url "localhost", senza virgolette, e lui mi manda alla directory www che ho specificato sulla configurazione di apache.

  4. #4
    Utente di HTML.it
    Registrato dal
    Mar 2006
    Messaggi
    58
    comunque no non credo, ho visto qui http://httpd.apache.org/docs/2.0/vhosts/examples.html come si impostano i virtualhost e nel mio file di configurazione apache non c'è alcune voce del genere. poi xkè dovrei attivare dei vhost? io apache/php lo uso solo in locale per studiare il linguaggio.

  5. #5
    Utente di HTML.it L'avatar di gianiaz
    Registrato dal
    May 2001
    Messaggi
    8,027
    i virtual host li puoi configurare anche in locale.

    Te l'ho chiesto perchè io li uso in locale, e una volta mi è capitato che per un particolare virtualhost le sessioni venivano ricreate ogni volta. Purtroppo l'unica soluzione che ho trovato è stato dare un nome diverso alll'host.

    In effetti doveva essere proprio un caso particolare, purtroppo non mi sono venute in mente altre soluzioni.

    ciao

  6. #6
    Utente di HTML.it
    Registrato dal
    Mar 2006
    Messaggi
    58
    proverò ad impostare un virtualhost in locale seguendo l'esempio della documentazione apache, grazie della risposta cmq, ciao!

    PS: se qualcuno ha qualche altra soluzione in merito si faccia avanti, grazie.

  7. #7
    Utente di HTML.it L'avatar di gianiaz
    Registrato dal
    May 2001
    Messaggi
    8,027
    per i virtual host questa vecchia discussione potrebbe esserti utile:

    http://forum.html.it/forum/showthrea...hlight=virtual


  8. #8
    Utente di HTML.it
    Registrato dal
    Mar 2006
    Messaggi
    58
    niente ho provato a fare come dicono in quel topic... ma niente.

    Ho editato httpd.conf

    ho levato da commento questo: Include conf/extra/httpd-vhosts.conf , ho salvato...

    poi ho aperto httpd-vhosts.conf ho cancellato le configurazioni di default e ho scritto:

    <VirtualHost *:80>
    ServerAdmin miamail@gmail.com
    DocumentRoot C:\www
    ServerName SitoWWW
    ErrorLog logs\errors.log
    CustomLog logs\access.log common
    </VirtualHost>

    salvo, poi ho modificato il file hosts di windows aggiungendo:

    127.0.0.1 SitoWWW
    salvo...
    ho riavviato apache/php... ma niente.

    sarà qualche impostazione nel php.ini?

  9. #9
    Utente di HTML.it
    Registrato dal
    Mar 2006
    Messaggi
    58
    nessuno sa nulla? vi prego sn disperato

  10. #10
    Utente di HTML.it
    Registrato dal
    Mar 2006
    Messaggi
    58
    Incredibile finalmente dopo 5 giorni di fusione celebrale sono arrivato alla soluzione del problema che riguarda i cookies e le sessioni!

    La soluzione è stata questa (la scrivo cosi magari qualcuno che ha avuto lo stesso problema risolve)...

    Prima il file di host di windows appariva cosi in sostanza:

    127.0.0.1 localhost
    io facevo puntare la document root di apache a C:/www e quando andavo su FF come url scrivevo http://localhost/ e mi portava alla visione web di quella dir dove poi andavo ad eseguire gli script che xò far funzionare sessioni e cookies non ne volevano sapere.

    Cambiando il file host in cosi (aggiungendo una nuova riga)...

    127.0.0.1 localhost
    ***.**.**.** sitodifedezzz.com
    faccio puntare sitodifedezzz.com all'ip interno della rete fastweb, che non è 127.0.0.1 (io ho fastweb, al posto dei numeri nell'ip interno della rete ho messo asterischi per la mia privacy).

    allora quando poi provo a fare lo stesso procedimento di prima xò con l'url http://sitodifedezzz.com sessioni e cookies funzionano! ora finalmente posso andare avanti con lo studio.

    Per quanto riguarda le eccezioni, se ho un file del genere (esempio del libro, ne scrivo solo una funzione della classe, basta quella):


    Codice PHP:
    <?php  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;   } //... il file poi va avanti...
    errors.inc invece è cosi:
    Codice 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 DatabaseErrorException extends Exception {   public function __construct($in_msg)   {     parent::__construct('A database error occurred: '                         $in_msg);   } } 
    Nella funzione createAccount c'è un blocco catch, una volta che sono lanciate delle eccezioni tipo DatabaseErrorException il programma va a finire qui:
    Codice PHP:
    catch (Exception $e)     {       if (isset($conn))         $conn->close();       throw $e;     } 
    no?

    ecco quel
    throw $e;
    dove rimanda?

    Grazie anticipatamente, ciao!

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 © 2024 vBulletin Solutions, Inc. All rights reserved.