Incluziunea fisierelor

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

Puteti includecontinutul unei pagini PHP in alta pagina PHP. PHP ne pune la dispozitie 2 functii folositoare in aceasta directie:

  • include()
  • require()

Cu aceste functii PHP-ul ne ajuta foarte mult sa creeam functii, headere, footere (asta cand discutam de template-uri), sau orice alte elemente pe care le folosim doar in anumite pagini.

Functia include()

Aceasta functie prea tot continutul (text) dintr-un fisier si il copiaza in cel in care a fost folosita functia. Daca exista vre-o problema aceasta functie va genera un warning si va continua executia scriptului.Presupunem urmatorul exemplu, dorim sa facem un meniu pentru site-ul nostru (il numim meniu.php), meniu pe care il vom pune pe urma pe toate paginile:

<ul>
	<li> <a href='http://invata-programare.ro'>Acasa</a> </li>
	<li> <a href='http://invata-programare.ro/toate-lectiile-php'>Cursuri PHP</a> </li>
	<li> <a href='http://invata-programare.ro/toate-lectiile-css'>Cursuri CSS</a> </li>
	<li> <a href='http://invata-programare.ro/toate-lectiile-html'>Cursuri HTML</a> </li>
</ul>

Iar acum in fiecare pagina in care vrem sa fie afisat continutul acestui fisier punem:

<html>
<body>
<?php include("meniu.php"); ?>
<p>Un exemplu de include() in PHP!</p>
</body>
</html>

Functia require()

Aceasta functie este similara cu functia include, preia textul dintr-un fisier dat si-l copiaza in fisier in care a fost apelata. Daca exista vre-o problema aceasta functie genereaza o eroare fatala si opreste scriptul.

Deci nu exista diferenta intre require si include in afara de tipul de eroare generata. Este recomandat sa folosim require in loc de include, pentru ca mai bine este oprit scriptul cand exista o problema, decat sa fie dat un warning.

Nota: Afisarea mesajelor de eroare tin de configurarea serverului PHP.

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

purchase waklert in san francisco # 8 months ago I am really loving the theme/design of your blog. Do you ever run into any web browser compatibility problems? A handful of my blog visitors have complained about my blog not operating correctly in Explorer but looks great in Opera. Do you have any tips to help fix this problem?
Modesto # 5 months ago Hello friends, how is all, and what you would like to say about this post, in my view its in fact amazing designed for me.
Fufsfh # 3 months ago tricor 160mg price <a href="https://fenoficor.com/">order tricor 200mg for sale</a> buy tricor 200mg for sale
aristocort disponible en Alemania # 3 months ago I loved as much as you'll receive carried out right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this increase.
Ykesux # 3 months ago order ketotifen 1 mg for sale <a href="https://geozipin.shop/">doxepin generic</a> tofranil online buy
Hkymta # 3 months ago buy minoxytop solution <a href="https://abcelemax.shop/">purchase tamsulosin sale</a> ed pills otc
Qafxbv # 3 months ago cheap precose <a href="https://micronide.shop/">order generic repaglinide 1mg</a> brand griseofulvin 250 mg
Imvvgd # 3 months ago generic aspirin <a href="https://aminirin.shop/">buy aspirin generic</a> imiquimod canada
Oscar # 3 months ago When some one searches for his vital thing, thus he/she wants to be available that in detail, so that thing is maintained over here.
Lesley # 3 months ago Great site you've got here.. It's hard to find excellent writing like yours nowadays. I seriously appreciate individuals like you! Take care!!
Jflzhh # 3 months ago duphaston 10 mg pill <a href="https://danaterone.shop/">duphaston 10 mg for sale</a> jardiance 10mg over the counter
Gfbrpv # 3 months ago fludrocortisone buy online <a href="https://pravinef.shop/">where to buy florinef without a prescription</a> buy loperamide 2mg without prescription
Xwaxit # 3 months ago generic monograph 600 mg <a href="https://colotazol.com/">order colospa 135 mg</a> order cilostazol 100 mg online
Lbzfdu # 3 months ago buy pyridostigmine online cheap <a href="https://mestien.shop/">feldene 20mg uk</a> buy rizatriptan 5mg without prescription
Cfozud # 2 months ago ferrous 100mg pill <a href="https://fertonel.shop/">risedronate pills</a> sotalol 40 mg drug
tiopepi # 2 months ago <a href="https://www.bonekwani.com/all-white-low-top-air-force-ones-noir-skor">all white low top air force ones noir</a><a href="https://www.bonekwani.com/adidas-duramo-6-mennns-running-sko-vista-grey-skor">adidas duramo 6 mennns running sko vista grey</a><a href="https://www.bonekwani.com/nike-shox-current-hvit-skor">nike shox current hvit</a><a href="https://www.bonekwani.com/adidas-crazylight-boost-2015-marina-militare-skor">adidas crazylight boost 2015 marina militare</a> <a href=https://www.caspigas.com/nike-air-parace-1-low-brown-negro-shoesen>nike air parace 1 low brown negro</a><a href=https://www.caspigas.com/nike-air-huarache-noir-pure-platinum-shoesen>nike air huarache noir pure platinum</a><a href=https://www.caspigas.com/nike-mercurial-vapor-12-indoor-blanc-shoesen>nike mercurial vapor 12 indoor blanc</a><a href=https://www.caspigas.com/balenciaga-shoes-light-up-blanc-shoesen>balenciaga shoes light up blanc</a> <a href="https://www.cpsmath.com/stockx-yeezy-450-dark-slate-skom6">stockx yeezy 450 dark slate</a> <a href="https://www.kosmax.net/sb-shane-shippingro">sb shane</a> <a href=https://www.makersfinds.com/mohamed-salah-egypt-national-team-jersey-nflf3>mohamed salah egypt national team jersey</a><a href=https://www.makersfinds.com/neymar-football-kit-junior-nflf3>neymar football kit junior</a><a href=https://www.makersfinds.com/chelsea-team-shirt-nflf3>chelsea team shirt</a><a href=https://www.makersfinds.com/trae-young-shirt-jersey-nflf3>trae young shirt jersey</a> <a href=https://www.contiendas.com/blue-flowy-dress-short-dressdk>blue flowy dress short</a><a href=https://www.contiendas.com/traditional-chinese-kimono-dress-dressdk>traditional chinese kimono dress</a><a href=https://www.contiendas.com/enza-costa-ribbed-dress-dressdk>enza costa ribbed dress</a><a href=https://www.contiendas.com/red-and-black-ball-gown-wedding-dress-dressdk>red and black ball gown wedding dress</a> [url=http://www.tiopepi.net/]tiopepi[/url]
Iwqaka # 2 months ago purchase vasotec online cheap <a href="https://casosin.com/">order bicalutamide 50mg pills</a> lactulose price
Bwveab # 2 months ago latanoprost for sale <a href="https://aexeloda.com/">oral capecitabine 500 mg</a> rivastigmine online
Wkrpih # 2 months ago telmisartan 80mg cost <a href="https://molnenil.com/">order hydroxychloroquine 200mg sale</a> buy molnunat 200mg pill
Vjktve # 2 months ago cenforce drug <a href="https://enapocen.com/">order cenforce sale</a> order chloroquine 250mg for sale
Xtcgwh # 2 months ago buy omnicef without prescription <a href="https://chlodinir.shop/">buy cefdinir 300mg online cheap</a> buy generic lansoprazole 30mg
Nkgqom # 2 months ago order atorvastatin 20mg generic <a href="https://anoronix.com/">amlodipine pills</a> buy norvasc medication
Hoemgd # 2 months ago best casino slot games <a href="https://furocheap.online/">online roulette game</a> brand furosemide
Uzkcmr # 2 months ago online casino usa <a href="https://avenonline.com/">ventolin price</a> buy ventolin inhalator online cheap
Smwitm # 2 months ago blackjack for money <a href="https://gauinonline.com/">purchase amoxiclav online</a> buy levothyroxine generic
Tdocgh # 2 months ago brand symmetrel 100mg <a href="https://atenulfon.shop/">purchase aczone generic</a> dapsone drug
Ibelha # 2 months ago clomid 50mg for sale <a href="https://synorbide.shop/">imdur 20mg drug</a> buy imuran 50mg for sale
Oexecq # 2 months ago buy generic medrol <a href="https://arisceon.com/">order aristocort 10mg generic</a> triamcinolone 4mg sale
Buulpv # 2 months ago order vardenafil 20mg online cheap <a href="https://lanoedra.shop/">buy digoxin 250 mg online cheap</a> generic tizanidine
Bmeteb # 1 month ago buy dilantin without prescription <a href="https://cycopan.shop/">buy oxybutynin 2.5mg online cheap</a> order oxybutynin 5mg generic
Xtcsrf # 1 month ago buy coversum no prescription <a href="https://claegra.shop/">buy fexofenadine 180mg online cheap</a> buy allegra tablets
Geygpf # 1 month ago loratadine price <a href="https://loraitace.shop/">altace price</a> order priligy 30mg for sale
Jiifbc # 1 month ago baclofen pills <a href="https://alenolac.com/">buy toradol online cheap</a> how to get toradol without a prescription
Nxtfwf # 1 month ago alendronate 70mg oral <a href="https://macroicine.shop/">order nitrofurantoin 100mg for sale</a> furadantin 100 mg uk
Uynkxq # 1 month ago inderal 20mg generic <a href="https://propofen.shop/">buy cheap generic ibuprofen</a> purchase clopidogrel online cheap
Urcvrk # 1 month ago order pamelor 25 mg <a href="https://nortogrel.shop/">how to get pamelor without a prescription</a> buy paracetamol cheap
Hfpnyy # 1 month ago glimepiride 1mg uk <a href="https://daporide.shop/">order glimepiride without prescription</a> arcoxia 60mg drug
Hpcyvg # 1 month ago buy warfarin cheap <a href="https://wafetine.shop/">order paxil 20mg pill</a> order metoclopramide 20mg pill
Exqlik # 1 month ago order pepcid 20mg <a href="https://cozolimus.shop/">buy tacrolimus paypal</a> order generic tacrolimus
Rmcned # 1 month ago order azelastine 10ml <a href="https://acypapro.shop/">buy generic avapro 300mg</a> buy irbesartan online
Cklktw # 1 month ago sumatriptan 25mg tablet <a href="https://avastede.com/">buy cheap generic dutasteride</a> dutasteride drug
Ppwgxf # 1 month ago purchase zyloprim generic <a href="https://allovatep.shop/">buy temovate generic</a> buy crestor 10mg generic
Aqyzfa # 1 month ago buspar 5mg generic <a href="https://ezetdarone.com/">cost zetia 10mg</a> order amiodarone without prescription
Tmylaa # 1 month ago how to get domperidone without a prescription <a href="https://domedilol.shop/">order carvedilol 6.25mg pills</a> buy tetracycline 500mg pill
Fuzehm # 1 month ago buy cheap spironolactone <a href="https://vaclorex.com/">buy valacyclovir 500mg online cheap</a> proscar oral
Jixpnh # 1 month ago buy thesis paper <a href="https://essayawonline.com/">essay for you</a> research paper website
Waakky # 1 month ago order diflucan 200mg sale <a href="https://ampacitim.com/">ampicillin order</a> buy ciprofloxacin pills for sale
Vrmtml # 1 month ago order aurogra sale <a href="https://auroafil.com/">purchase aurogra online cheap</a> estrace 1mg drug
Wdusnn # 4 weeks ago metronidazole buy online <a href="https://bacptra.com/">buy generic sulfamethoxazole</a> buy cephalexin 250mg online cheap
Zyxsfo # 3 weeks ago cleocin 300mg us <a href="https://aperytxpro.com/">cheap erythromycin 250mg</a> erection pills online
Spoamr # 3 weeks ago buy retin cream online cheap <a href="https://retretol.com/">oral tretinoin</a> where to buy avanafil without a prescription
Inxssl # 3 weeks ago where can i buy tamoxifen <a href="https://batanine.com/">betahistine 16 mg canada</a> rhinocort allergy nasal spray
?????? # 3 weeks ago 외침 : "Duke Qi, 암살자를 조심하십시오!", <a href="https://www.slotmr.com/yggdrasil">무료 슬롯</a> <a href="https://www.slotmr.com/cq9-gaming">씨큐나인슬롯</a> 홀 전체가 갑자기 끓었고 모두가 소식을 애타게 기다리기 시작했습니다. https://www.slotmr.com/nolimit-city https://www.slotmr.com/pg-soft 탕인이 미처 반응하기도 전에 종아리에서 날카로운 통증이 느껴졌다. <a href=https://www.slotmr.com/boongo>부운고슬롯</a> <a href=https://www.slotmr.com/playn-go>플레이앤고슬롯</a> 그러니 간단하게 항아리를 부수고 완고한 반역자를 놓으십시오.
Unqnts # 3 weeks ago ceftin 500mg us <a href="https://aromocar.com/">order generic robaxin</a> methocarbamol usa
Rijtef # 3 weeks ago purchase tadacip sale <a href="https://bindacin.com/">indocin 50mg drug</a> purchase indocin generic
????? # 3 weeks ago Hongzhi 황제는 Fang Jifan을 응시했습니다. "말해봐, 무슨 일이야?" <a href="https://www.slotmr.com/pragmatic">프라그마틱 슬롯</a> <a href="https://www.slotmr.com/habanero">하바네슬롯</a> Zhu Houzhao는 오늘 매우 용감했고 같은 방식으로 Hongzhi 황제를 응시했습니다. https://www.slotmr.com/yggdrasil https://www.slotmr.com/nolimit-city 이때 곤녕궁에서 고기 냄새가 강하게 풍긴다는 것을 누가 알았겠습니까? <a href=https://www.slotmr.com/pragmatic>프라그마틱 슬롯</a> ???<a href=https://www.slotmr.com/>슬롯MR</a> "선장님의 축복이 있기를." Wang Xizuo는 아첨하는 미소를 지었습니다.
Rjvbxw # 2 weeks ago aspirin 75 mg without prescription <a href="https://msgameonline.com/">slots games</a> online slots real money
Zzqvox # 2 weeks ago buy dissertation online <a href="https://abessonline.com/">english homework help</a> suprax 100mg uk
xjcpnopij # 2 weeks ago 말할 것도 없이 그곳 사람들이 어떤 종류의 야만인인지는 신만이 아신다. <a href="https://gazelle-agency.com/" title="超 電磁 砲 パチンコ"><strong>超 電磁 砲 パチンコ</strong></a> <a href="https://pdi-al.com/" title="魔法少女まどか☆マギカ"><strong>魔法少女まどか☆マギカ</strong></a> <a href="https://totosago.com/" title="온라인 슬롯"><strong>온라인 슬롯</strong></a> Hongzhi 황제는 Liu Jian과 다른 사람들을 쳐다 보았습니다. "당신은 어떻게 생각하십니까?" https://viagrazett.com/ https://thewritingessay.com/ Fang Jifan은 마음이 행복했고 이렇게 만 자신의 가치를 보여주었습니다. <a href=https://orientirbg.com/>ほくと の けん 天井</a> <a href=https://viavigra.com/>データ サイト セブン</a> <a href=https://blackhatroyalty.com/>버팔로 슬롯</a> 한숨에 포탄처럼 가격을 하나씩 말했다.
Vtnfol # 2 weeks ago order calcitriol online cheap <a href="https://rocatrion.com/">rocaltrol 0.25 mg cheap</a> cheap tricor 200mg
Qjxocf # 2 weeks ago amoxicillin sale <a href="https://arimlanas.com/">arimidex 1mg tablet</a> biaxin buy online
Juleee # 2 weeks ago zinplex pills side effects <a href="https://trilazepl.com/">buy oxcarbazepine 600mg</a> trileptal uk
Zcadfu # 2 weeks ago buy clonidine 0.1mg pill <a href="https://spirtiobol.com/">buy tiotropium bromide 9 mcg online</a> order spiriva 9mcg generic
?????? # 1 week ago <a href="https://peakchoiceketo.com/">인터넷카지노</a> 결국 과학 아카데미가 가르치는 것은 과학과 기술뿐입니다.
Xivlta # 1 week ago alfuzosin 10mg cost <a href="https://antiaciditytrt.com/">dangers of heartburn medication</a> how to use peppermint oil for acid reflux
Vruyms # 1 week ago buy minocin 50mg online cheap <a href="https://amrenirol.com/">requip drug</a> requip 2mg for sale
Nalboh # 1 week ago sleeping pills prescription online <a href="https://zybopim.com/">dutasteride prescription for hair loss</a> approved drugs for weight loss
BVZ_Moskva_m # 1 week ago Быстро возводимые здания: бизнес-польза в каждом элементе! В сегодняшнем обществе, где моменты - финансы, скоростройки стали реальным спасением для экономической сферы. Эти новейшие строения комбинируют в себе надежность, эффективное расходование средств и ускоренную установку, что придает им способность превосходным выбором для разнообразных коммерческих задач. <a href=https://bystrovozvodimye-zdanija-moskva.ru/>Построить быстровозводимое здание</a> 1. Скорость строительства: Моменты - наиважнейший аспект в коммерции, и скоро возводимые строения обеспечивают существенное уменьшение сроков стройки. Это чрезвычайно полезно в сценариях, когда актуально оперативно начать предпринимательство и получать доход. 2. Бюджетность: За счет улучшения производственных процедур элементов и сборки на объекте, цена скоростроительных зданий часто уменьшается, по сопоставлению с традиционными строительными задачами. Это дает возможность сэкономить деньги и добиться более высокой доходности инвестиций. Подробнее на <a href=https://bystrovozvodimye-zdanija-moskva.ru/>https://scholding.ru/</a> В заключение, скоро возводимые строения - это превосходное решение для коммерческих задач. Они объединяют в себе скорость строительства, финансовую выгоду и твердость, что придает им способность первоклассным вариантом для деловых лиц, желающих быстро начать вести бизнес и обеспечивать доход. Не упустите возможность сократить затраты и время, превосходные экспресс-конструкции для вашего предстоящего предприятия!
Cyerzf # 1 week ago champix for quitting smoking <a href="https://stopsmokingots.com/">free meds to quit smoking</a> online doctor consultation pain prescription
??????? # 1 week ago Hongzhi 황제는 평소와 같이 Nuan Pavilion에서 여러 장로를 소환했습니다. <a href="https://www.slotmr.com/nolimit-city">노리밋시티슬롯</a>
Vbhxqw # 1 week ago provera 10mg ca <a href="https://provrogesten.com/">medroxyprogesterone 5mg price</a> buy hydrochlorothiazide without a prescription
Vetvee # 1 week ago herpes medication online without script <a href="https://bsasthmaps.com/">can you buy inhalers online</a> new diabetes drugs list
BVZ_Moskva_m # 1 week ago Моментально возводимые здания: финансовая выгода в каждом блоке! В современной сфере, где время равно деньгам, экспресс-конструкции стали истинным спасением для коммерции. Эти прогрессивные сооружения обладают надежность, экономическую эффективность и скорость монтажа, что придает им способность наилучшим вариантом для разных коммерческих начинаний. <a href=https://bystrovozvodimye-zdanija-moskva.ru/>Быстровозводимые здания</a> 1. Скорость строительства: Минуты - важнейший фактор в коммерции, и быстровозводимые здания позволяют существенно сократить время монтажа. Это значительно ценится в постановках, когда необходимо оперативно начать предпринимательскую деятельность и начать прибыльное ведение бизнеса. 2. Финансовая выгода: За счет совершенствования производственных операций по изготовлению элементов и монтажу на площадке, бюджет на сооружения быстрого монтажа часто бывает ниже, по отношению к обычным строительным проектам. Это позволяет сократить затраты и добиться более высокой доходности инвестиций. Подробнее на <a href=https://bystrovozvodimye-zdanija-moskva.ru/>http://scholding.ru</a> В заключение, моментальные сооружения - это оптимальное решение для коммерческих задач. Они обладают быстроту монтажа, финансовую выгоду и повышенную надежность, что сделало их лучшим выбором для предпринимателей, готовых к мгновенному началу бизнеса и получать деньги. Не упустите возможность сократить издержки и сэкономить время, оптимальные моментальные сооружения для вашей будущей задачи!
Nfugld # 1 week ago buy cyproheptadine cheap <a href="https://nizinazole.com/">ketoconazole 200mg over the counter</a> ketoconazole 200mg price
Obnlwm # 6 days ago fungus clear reviews vitality health <a href="https://rebloodpressure.com/">five worst blood pressure meds</a> alpha 1 blockers list
Hjyhex # 5 days ago duodenitis without bleeding means <a href="https://amenahealthp.com/">boots online doctor service</a> best online uti treatment
?? ?? # 4 days ago Fang Jifan을 따랐기 때문에 그것은 '나쁜'것이되었고 점점 더 성리학에 위배되었습니다. <a href="https://www.geinoutime.com/">에그슬롯</a>
brahmi en línea sin receta en España # 3 days ago Excellent post. I was checking continuously this blog and I'm impressed! Extremely useful info specifically the last part : ) I care for such information a lot. I was looking for this particular information for a long time. Thank you and good luck.
Uotenr # 3 days ago order promethazine 25mg <a href="https://prostmecl.com/">buy generic stromectol 12mg</a> ivermectin tablets uk
Eqxein # 3 days ago contraceptives covered by insurance <a href="https://awomenahealthp.com/">birth control samples online free</a> ways of preventing premature ejaculation
Qlzwwh # 1 day ago best otc med for indigestion <a href="https://antdistentionp.com/">old fart pills</a> stomach pain smelly farts
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.