Stefanescu Mihai 2 years ago PHP
Acest articol face parte din cursul Toate lectiile PHP. Te poti inscrie la acest curs aici!

Alta metoda de a face datele accesibile pe mai multe paginile unui website este folosirea de Sessions.

Session creaza un fisier temporar pe server unde sunt inregistrate variabilele (avem din nou perechi nume-valoare) sesiunii. Aceste date sunt valabile pe toate paginile site-ului doar in timpul unei vizite.

Locatia acestui fisier temporar este determinata de php.ini in setarea numite session.save_path. Inainte de a seta session asiguirati-va ca aceasta optiune este setata.Cand o sesiune este deschisa se intampla urmatoarele:

  • PHP creaza un numar de identificare unic pentru fiecare sesiune care este de fapt un string hexazecimal de 32 de caractere (ex: 3c7foj34c3jj973hjkop2fc937e3445).Un cookie numit PHPSESSID ce contine acel sir de caractere de 32 de caractere este salvat pe calculatorul utilizatoruluiUn fisier este creat automat pe server in care este salvat id-ul unic (cel de 32 de caractere).

Cand un script PHP doreste informatii dintr-o variabila de sesiune, PHP-ul in mod automat preia id-ul unic din PHPSESSID si-l cauta in fisierele temporare salvate pe server pentru a-l valida.

O sesiune se termina atunci cand un utilizator inchide browserul, serverul sterge sesiunea dupa o perioada predefinita de timp (in  general 30 min).

Deschiderea unei sesiuni PHP

O sesiune PHP poate fi deschisa foarte usor cu ajutorul functiei session_start(). Aceasta functie verifica daca o sesiune a fost deschisa deja si daca nu a fost deschide una. Este recomandat sa apelati aceasta functie la inceputul paginii PHP.

Variabilele sesiunii sunt stocate intr-un array asociativ numit $_SESSION[]. Aceste sesiuni pot fi accesate pe toata durata de viata a sesiunii.

In urmatorul exemplu am sa va invat sa porniti o sesiune numita contor care se va incrementa de fiecare data cand pagina este vizitata in timp ce sesiunea este deschisa.

Putem folosi functia isset() pentru a verifica daca variabila a fost setata.

Presupunem ca avem un fisier test.php:

   if( isset( $_SESSION['contor'] ) )
      $_SESSION['contor'] += 1;
      $_SESSION['contor'] = 1;
   $msg = "Aceasta pagina a fost vizitata de ". $_SESSION['contor']." ori";
<title>Sesiunile PHP</title>
<?php  echo ( $msg ); ?>

Stegerea unei sesiuni

O sesiune PHP poate fi stearsa folosind functia session_destroy(). Aceasta functie nu necesita argumente, o simpla apelare si sesiunea este stearsa. Daca doresti sa stergi o singura variabila atunci puteti folosi functiaunset().

iata un exemplu de stergere a sesiunii cu unset:


Acum un exemplu cu functia session_destroy():


Auto Session

Nu trebuie sa apelati functia start_session() de fiecare data cand un vizitator intra pe site, puteti pur si simplu sa setati variabila session.auto_start din php.ini la 1.Session fara CookiePoate fi cazul ca un utilizator sa nu permita stocarea cookie-urilor pe computerul lor. In acest caz exista alta metoda de a trimite session id-ul catre browser.In mod alternativ, puteti folosi constanta SID ce ne spune daca sesiunea a fost pornita. Daca clientul nu a atrimis un session cookie valid va return un string gol, altfel va returna session_name=session_id.


   if (isset($_SESSION['contor'])) {
      $_SESSION['contor'] = 1;
   } else {
To continue  click following link <br />
<a  href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">


Programator de ~8 ani, am lucrat la proiecte din mai multe industrstrii, de la eCommerce la telecomunicatii la automatizari. In acest timp am folosi diferite tehnologii, de la PHP, MySQL, PostgreSql, RabbitMq, Redis, Memcached si altele.

Get in touch
Pentru nelamuriri, dubii, comentarii si chestii de pe suflet ne putem auzi pe Discord, Reddit sau poti deschide o discutie noua pe forum

??????????? # 1 month ago Just wish too say your articlke iss ass surprising. The clearness iin your poost iis jusat nnice annd i ccan think you aree knowledgeable onn this subject. Fine aloong with your permission llet me to grab yiur RSS feed to stay updated wifh forthcoming post. Thankk youu one million and pleawse cointinue the enjoyable work.
Bosfud # 1 month ago buy tricor pills for sale <a href="">buy tricor 160mg generic</a> buy fenofibrate 160mg sale
Nvabtr # 1 month ago ketotifen 1 mg pill <a href="">buy tofranil 25mg generic</a> how to get imipramine without a prescription
Jgvqws # 1 month ago mintop for sale <a href="">tamsulosin online</a> best over the counter ed pills
Rhkilt # 1 month ago buy acarbose 50mg online <a href="">precose where to buy</a> griseofulvin 250mg cheap
Yftedg # 4 weeks ago buy aspirin 75 mg pills <a href="">order eukroma without prescription</a> generic imiquimod
Ola # 4 weeks ago whoah this weblog is great i like reading your articles. Keep up the great work! You know, many people are looking around for this info, you could help them greatly.
Tfbbtg # 3 weeks ago order dydrogesterone <a href="">pill sitagliptin</a> buy jardiance 10mg without prescription
Brodie # 3 weeks ago Simply desire to say your article is as amazing. The clarity on your post is simply excellent and i can suppose you are an expert in this subject. Well along with your permission allow me to snatch your feed to keep up to date with forthcoming post. Thanks a million and please carry on the gratifying work.
Alfredo # 3 weeks ago magnkficent put up, very informative. I'm wondering why thee opposite expert of this sedtor doo nott rrealize this. You mustt continue your writing. I am confident, youu hae a grerat readers' baqse already!
Randolph # 3 weeks ago Hmm is anyone else encountering problems with the pictures on this blog loading? I'm trying to find out if its a problem on my end or if it's the blog. Any suggestions would be greatly appreciated.
osteluc zonder voorschrift in Martinique # 3 weeks ago Hello everyone, it's my first go to see at this site, and paragraph is genuinely fruitful for me, keep up posting these types of content.
Bavqwk # 3 weeks ago order generic monograph <a href="">purchase mebeverine online</a> buy cilostazol 100mg pills
Jfyqsd # 3 weeks ago order prasugrel 10 mg pills <a href="">how to buy chlorpromazine</a> cost tolterodine
marge simpson thong # 3 weeks ago I like thee valuable informwtion you provire in ylur articles. I ill boolkmark your blog and check agfain here frequently. I amm quiute sure I willl learn plenty off new stff right here! Goood lick for thee next!
thick legged naked women # 2 weeks ago Hmm it appears like your bloog atee my first commejt (it wwas extremely long) sso I guess I'll just ssum iit upp whhat I submifted andd say, I'm thoroughly enjoying our blog. I aas well am ann aspirihg blog blogger but I'm still neew tto thee whole thing. Do you have any recommenndations for first-time blog writers? I'd really appreciate it.
Widemu # 2 weeks ago order ferrous sulfate 100 mg online cheap <a href="">order risedronate 35mg online cheap</a> order sotalol 40 mg pills
Lmngkr # 2 weeks ago pyridostigmine drug <a href="">feldene online</a> rizatriptan 5mg without prescription
amen zonder medisch voorschrift in Rotterdam # 2 weeks ago Hey there, I think your website might be having browser compatibility issues. When I look at your blog site in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, very good blog!
Wlxeov # 2 weeks ago order vasotec sale <a href="">doxazosin 2mg usa</a> duphalac for sale
aankoop van albuterol in Italië # 1 week ago Your style is very unique compared to other folks I have read stuff from. Thank you for posting when you have the opportunity, Guess I will just book mark this site.
tokensci # 1 week ago <a href="">bifold michael kors wallet</a><a href="">carmen small saffiano leather belted satchel</a><a href="">michael kors extra small cece</a><a href="">michael kors burgundy crossbody bag</a> <a href="">air max 90 essential olive verde</a> <a href="">nike kd viii black and red</a> <a href=>cute clothing boutiques</a><a href=>dip hem dress boohoo</a><a href=>new years dress near me</a><a href=>baby girl gown</a> <a href="">red bottoms open toe</a> <a href="">deshaun watson panthers jersey</a><a href="">fc barcelona track jacket</a><a href="">euro england football shirt</a><a href="">nike training kits football</a> [url=]tokensci[/url]
Fmihle # 1 week ago zovirax for sale online <a href="">buy latanoprost</a> brand rivastigmine 6mg
kaufe isotretinoin 20 in Italien # 1 week ago This information is priceless. How can I find out more?
Orysxj # 1 week ago betahistine us <a href="">buy haloperidol pills</a> benemid sale
donde comprar noroxin sin prescripción médica # 1 week ago Excellent blog here! Also your website lots up fast! What host are you using? Can I am getting your affiliate link for your host? I desire my web site loaded up as quickly as yours lol
indication du cetirizine en vente au Maroc # 1 week ago Its such as you read my thoughts! You appear to grasp so much approximately this, like you wrote the book in it or something. I believe that you can do with a few % to force the message house a bit, however instead of that, that is fantastic blog. An excellent read. I will definitely be back.
aankoop symmetrel België online # 1 week ago Simply desire to say your article is as surprising. The clarity in your post is just great and i can assume you're an expert on this subject. Fine with your permission let me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please carry on the gratifying work.
Hhygcn # 1 week ago purchase telmisartan pill <a href="">buy generic molnunat</a> where to buy molnupiravir without a prescription
Hassie # 1 week ago If you want to obtain a good deal from this article then you have to apply such strategies to your won blog.
Ctfvzy # 6 days ago purchase cenforce pill <a href="">buy naprosyn 500mg online cheap</a> buy aralen pills for sale
acheter cycrin en ligne # 6 days ago These are actually wonderful ideas in on the topic of blogging. You have touched some fastidious points here. Any way keep up wrinting.
singulair betaalbaar in Santiago # 5 days ago Hello! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a extraordinary job!
erectalis zonder receptprijs in Charleroi # 5 days ago Hello, just wanted to mention, I liked this article. It was funny. Keep on posting!
Online-Kauf von Medikamenten # 3 days ago Hello! Quick question that's completely off topic. Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my iphone. I'm trying to find a theme or plugin that might be able to resolve this problem. If you have any suggestions, please share. With thanks!
verifica il prezzo di doxepin con prescrizione medica a Torino # 2 days ago Hi, after reading this amazing article i am also glad to share my know-how here with friends.
Club-ul este dedicat membrilor si ofera access la mai multe zone ale website-ului.
Login Register

🔖 Bookmarks
✨ Pentru a sustine aceasta comunitate am sa te rog sa te autentifici sau sa te inregistrezi!

🌪️ Discord
Back to top
Folosim cookie-uri pentru a oferi functionalitatile critice ale aplicatiei Invata-Programare. Folosim cookie-uri si pentru a analiza traficul, pentru care e nevoie de consimtamantul dvs. explicit.