Jak mnozí jistě vědí, programovací jazyk PHP poskytuje široké možnosti programátorům, kteří programují webové stránky. Od jednoduchých podmínek pro větvení programu, ošetřování výjimek, zpracovávání formulářů, prací s COOKIES a SESSIONS, přes rozesílání emailů, po práci se soubory a hlavičkami dokumentů. A samozřejmě ještě spousta dalších možností. Dnes si ukážeme, jak pomocí PHP skriptu umožnit stahovat nějaký soubor.
Ukázkový skript
<?php
// funkce pro navraceni ocekavaneho content podle pripony souboru
function content_dle_pripony($pripona) {
$ocekavany_content = 'application/octet-stream';
if($pripona == 'doc') {$ocekavany_content = 'application/msword';}
if($pripona == 'exe') {$ocekavany_content = 'application/octet-stream';}
if($pripona == 'pdf') {$ocekavany_content = 'application/pdf';}
if($pripona == 'xls') {$ocekavany_content = 'application/vnd.ms-excel';}
if($pripona == 'pps') {$ocekavany_content = 'application/vnd.ms-powerpoint';}
if($pripona == 'ppt') {$ocekavany_content = 'application/vnd.ms-powerpoint';}
if($pripona == 'tar') {$ocekavany_content = 'application/x-tar';}
if($pripona == 'zip') {$ocekavany_content = 'application/zip';}
if($pripona == 'mp3') {$ocekavany_content = 'audio/mpeg';}
if($pripona == 'wav') {$ocekavany_content = 'audio/x-wav';}
if($pripona == 'bmp') {$ocekavany_content = 'image/bmp';}
if($pripona == 'gif') {$ocekavany_content = 'image/gif';}
if($pripona == 'jpe') {$ocekavany_content = 'image/jpeg';}
if($pripona == 'jpeg') {$ocekavany_content = 'image/jpeg';}
if($pripona == 'jpg') {$ocekavany_content = 'image/jpeg';}
if($pripona == 'ico') {$ocekavany_content = 'image/x-icon';}
if($pripona == 'css') {$ocekavany_content = 'text/css';}
if($pripona == 'htm') {$ocekavany_content = 'text/html';}
if($pripona == 'html') {$ocekavany_content = 'text/html';}
if($pripona == 'mpeg') {$ocekavany_content = 'video/mpeg';}
if($pripona == 'mpg') {$ocekavany_content = 'video/mpeg';}
if($pripona == 'mov') {$ocekavany_content = 'video/quicktime';}
if($pripona == 'qt') {$ocekavany_content = 'video/quicktime';}
if($pripona == 'avi') {$ocekavany_content = 'video/x-msvideo';}
return $ocekavany_content;
}
// nazev souboru (i s cestou) a prevod cesty do pole
$soubor = './kestazeni/soubor.txt';
$cesta_pole = pathinfo($soubor);
// nastaveni pro nektere urcite prohlizece
if(ini_get('zlib.output_compression')) {ini_set('zlib.output_compression', 'Off');}
header("Pragma: public");
header("Expires: 0");
header("Cache-control: private", false);
header("Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Content-Description: File Transfer");
// nejdulezitejsi cast skriptu
header("Content-Disposition: attachment; filename=\"".$cesta_pole[„basename“]."\"");
header("Content-Type: " . content_dle_pripony(strtolower($cesta_pole[„extension“])) . "");
header('Content-Transfer-Encoding: binary');
header("Content-Length: filesize($cesta_nazev)");
// vycistit cache a precist soubor
ob_clean();
flush();
readfile($soubor);
exit;
?>
Popis ukázky
První část kódu je funkce, která po zadání přípony vrátí předpokládaný content souboru. Samozřejmě můžete funkci doplnit o další přípony, jde pouze o ukázku, kde nejsou všechny. Celý kód, který čítá všechny podporované contents, má okolo 200 řádků.
V další části se připraví název souboru. Ten samozřejmě nemusíte získávat napevno, ale například pomocí načtení hodnoty z nějakého formuláře. Potom následuje taková "série různých opatření". Jelikož ne všechny webové prohlížeče mohou pochopit stejnou operaci stejně, je toto opatření na místě. Díky tomuto ošetření by se rozdíly měly snížit na minimum. Snad jen Content-Description je zde navíc, popis není povinný.
No a nyní přichází nejdůležitější část skriptu. Přes Content-Disposition předáme název souboru, přes Content-Type zase content souboru, který nám s výhodou obstará již připravená funkce. Je také dobré nastavit binární kódování (jinak by mohl nastat problém, u mě například s archivy ZIP a jinými formáty) a předpokládanou velikost.
No a úplně poslední částí je vyčištění cache a přečtení souboru. Tímto se obsah souboru naplní do bufferu, který právě stahujete. Kromě readfile je také možné přečíst soubor "po znacích" (typicky cyklem while dokud není konec souboru), ale readfile funguje stejně dobře a je to kratší. Kdybyste namísto readfile nechali vypsat do bufferu třeba nápis "ahoj", tak se Vám nestáhne soubor zadaný přes proměnnou $soubor, ale soubor o daném typu, jehož obsahem bude text "ahoj".
Závěr
Tento příklad by měl být co nejvíce univerzální a snaží se eliminovat rozdíly v chápání různými prohlížeči. Samozřejmě je vhodné funkci rozšířit o další přípony a cestu ke stahovanému souboru si zasílat například přes formulář. A to je pro dnešek vše.
CheapAdultWebcam
I typically find idioms tough to teach, however resources like this one for Crush make my ESL lessons way more effective.
You’ll return from your Varanasi City Tour sensation changed.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
You’ll get lost in spiritual vibes with the help of Varanasi Temple Tours — highly recommend it!
I captured some of my best travel photos during the Varanasi City Tour.
Huge shoutout to the editors behind https://www.youtube.com/@kpopbuzzindo/shorts – the content is super engaging!
Your article helped me a lot, is there any more related content? Thanks! https://www.binance.info/join?ref=P9L9FQKY
Download the total **IPL 2025 Schedule PDF** to remain ahead of match dates and venues.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
If you wish to deal with the best Property Agents In Greater Noida, inspect this platform!
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Comprehending loan forgiveness can be tough, but Student Loan Forgiveness Programs Everything You Need to Know simplify completely.
Finding excellent Uttarakhand food in Bangalore utilized to be tough, but Joshital has solved that issue!
Broaden diagnostic abilities with the advanced Mobile Spotlight. **.
Check your abilities and luck with the interesting bdg win game.
Learn how to develop a structured Technology Roadmap for seamless IT planning and execution.
Your article helped me a lot, is there any more related content? Thanks!
Delight in competitive tournaments and unique promotions at 55-club.
Win huge and improve your abilities on the interesting bdg win game.
Get extra video gaming credits quickly by going into the Goa Games Invite Code.
Take advantage of referral perks by sharing the Diu Win Invite Code.
Get instant lottery results and real-time updates only at Raja Luck.
Participate in TS EARN’s referral program by sharing your Invite Code and enjoy cumulative benefits.
Manage your profile settings and preferences effortlessly via the Goa Games Login interface.
Get going on 82 Lottery with extra benefits by using the official 82 Lottery Invite Code.
Sign up easily with the 82 Lottery Invite Code and get started.
Secure bonus prizes by redeeming the 82 Lottery Invite Code.
Stay entertained anywhere with the feature-packed Raja Luck App.
Discover endless fun and opportunities with the Raja Luck App.
Get assistance in financial decision-making at https://look4.in/resources/finance-additional-information.php.
Explore the fundamentals of saving money at https://look4.in/resources/finance-additional-information.php.
Get access to government college cutoff trends with MBBS Cutoff Of Government Medical Colleges in Uttar Pradesh.
Secure your spot at leading colleges with MBBS Direct Admission in Chhattisgarh.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Explore outstanding opportunities at the Top MBBS Colleges in Orissa, known for academic excellence.
Get clarity on costs with the comprehensive MBBS Fees Structure in Punjab.
Connect with your destiny from anywhere through Online Nadi Astrology, offering trusted and accurate readings.
I’m eagerly awaiting your next piece. Real Madrid News
Your blog is a source of inspiration for me. TamilBlasters Com
I’m always inspired by your words. cg news
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Good
먹튀 관련 정보를 쉽게 찾을 수 있어 좋습니다! 방문하다 먹튀레이더
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your article helped me a lot, is there any more related content? Thanks!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.