File Uploading

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

Un script PHP poate fi folosit in asa fel incat sa permita utilizatorilor upload-ul de fisiere. Initial fisierele sunt uploadate intr-un director temporar si apoi sunt mutate in directorul dorit.

Atentie: Upload-ul de fisiere este periculos! Va recomand sa nu permiteti upload-ul de fisiere php, html, js, etc

Configurare php.ini

In primul rand trebuie sa va asigurati ca upload-ul de fisiere este permis pe serverul vostru. Pentru a face acest lucru verificati optiunea file_uploads din php.ini sa fie setata pe On.

Formularul HTML

Acum trebuie sa facem un formular HTML ce ne va permite sa selectam o imagine pentru upload.

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Selectare Imagine:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload" name="submit">
</form>

</body>
</html>

Ce trebuie sa stii despre formularul de mai sus:

  • asigurati-va ca metoda este POST
  • Pentru upload de fisiere tag-ul <form> trebuie sa aiba atributul enctype=”multipart/form-data”.

Se poate observa rapid ca formularul de  mai sus va procesa upload-ul in fisierul upload.php.Scriptul de UploadFisierul upload.php va contine urmatorul cod:

<?php
$target_dir = "upload_imagini/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "Fisierul este imagine - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "Fisierul nu este imagine.";
        $uploadOk = 0;
    }
}
?>

Explicatii cod:

PHP script explained:

  • $target_dir = “upload_imagini/” – folderul in care sunt salvate imaginile
  • $target_file – este calea unde sunt salvate imaginile
  • $uploadOk=1 folosim mai tarziu
  • $imageFileType – extensia fisierului

Va trebuii sa creati directorul “upload_imagini”

Verificare existenta fisier

Acum, ca am facut baza ar trebuii sa adaugam niste restrictii.

In primul rand trebuie sa verificam daca fisierul deja exista.Daca exista afisam un mesaj de eroare si setam variabila $uploadOk cu valoarea 0.

if (file_exists($target_file)) {
    echo "Fisierul deja exista.";
    $uploadOk = 0;
}

Limitare dimsniune fisierNumele input-ului file din formularul HTML este “fileToUpload”. Acum, dorim sa verificam dimensiunea acestui fisier. Daca este mai mare de 500kb afisam un mesaj de eroare si setam $uploadOk la 0.

if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Fisierul este prea mare.";
    $uploadOk = 0;
}

Verificare tip fisierCodul de mai jos permite upload-ul doar formatelor JPG, JPEG, PNG, si GIF.

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Format interzis.";
    $uploadOk = 0;
}

Scriptul completFisierul upload.phpva avea forma finala:

<?php
$target_dir = "upload_imagini/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "Fisierul este o imagine - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "Fisierul nu este o imagine.";
        $uploadOk = 0;
    }
}
// Verificam daca deha exista
if (file_exists($target_file)) {
    echo "Fisierul deja exista.";
    $uploadOk = 0;
}
// Verificam dimensiunea
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Fisierul este prea mare.";
    $uploadOk = 0;
}
// Verificam formatul
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Format interzis.";
    $uploadOk = 0;
}
// verificam daca $uploadOk este 0
if ($uploadOk == 0) {
    echo "Fisierul nu a putut fi uploadat.";
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Fisierul ". basename( $_FILES["fileToUpload"]["name"]). " a fost uploadat.";
    } else {
        echo "Fisierul nu a putut fi mutat.";
    }
}
?>

 

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

work from home for beginners # 6 months ago pharmacy affiliate website design successful health blog income streams natural supplements affiliate networks herbal supplement affiliate marketing guide
Hermelinda # 6 months ago side businesses for therapists part-time pharmacist jobs in canada side jobs for doctors to earn extra money part-time medical writing jobs for doctors
Electrolyte Supplement # 5 months ago Why people still use to read news papers when in this technological globe the whole thing is available on net?
what to do when you suddenly lose your job # 5 months ago I think the admin of this web site is genuinely working hard in support of his web site, since here every material is quality based material.
Yvette # 2 months ago you are really a just right webmaster. The website loading speed is incredible. It sort of feels that you're doing any unique trick. Also, The contents are masterpiece. you've performed a magnificent process in this matter!
mebendazole disponible en Alemania # 1 month ago I for all time emailed this web site post page to all my contacts, as if like to read it next my friends will too.
grisefuline sans prescription médicale # 1 month ago Nice replies in return of this issue with real arguments and telling the whole thing on the topic of that.
indicación de chrisale en venta en Quito # 1 month ago I am actually pleased to read this weblog posts which includes plenty of valuable facts, thanks for providing these kinds of data.
vente en ligne de prednisolone en France # 1 month ago At this time it looks like Drupal is the top blogging platform available right now. (from what I've read) Is that what you are using on your blog?
Medikamente ohne Risiko kaufen # 1 month ago I do not even know how I ended up here, but I thought this post was great. I do not know who you are but certainly you are going to a famous blogger if you are not already ;) Cheers!
Bgksbp # 1 month ago fenofibrate drug <a href="https://fenoficor.com/">tricor 160mg tablet</a> tricor 160mg uk
finasterax en vente libre # 1 month ago That is a very good tip particularly to those new to the blogosphere. Short but very precise info… Thanks for sharing this one. A must read article!
¿dónde comprar caziant de forma segura? # 1 month ago Ahaa, its good conversation concerning this piece of writing at this place at this website, I have read all that, so now me also commenting here.
Swtxnz # 1 month ago zaditor 1 mg price <a href="https://flixitorp.shop/">brand ketotifen</a> tofranil us
Vkfgtl # 1 month ago order minoxytop sale <a href="https://abcelemax.shop/">buy flomax 0.4mg online cheap</a> buy cheap generic ed pills
Epyfin # 1 month ago buy acarbose 50mg <a href="https://dipyxcin.com/">buy griseofulvin 250mg online cheap</a> buy griseofulvin without a prescription
Nvimkl # 4 weeks ago order aspirin generic <a href="https://aminirin.shop/">cheap aspirin 75mg</a> buy imiquad for sale
Michelle # 4 weeks ago This information is invaluable. When can I find out more?
Reinaldo # 4 weeks ago My relatives every time say that I am killing my time here at web, but I know I am getting experience all the time by reading thes pleasant articles.
bestellen semaglutide België # 3 weeks ago I have been surfing on-line more than 3 hours nowadays, yet I never discovered any attention-grabbing article like yours. It's beautiful price sufficient for me. Personally, if all webmasters and bloggers made good content as you probably did, the web can be much more helpful than ever before.
Cyril # 3 weeks ago Hello There. I found your blog using msn. This is a really well written article. I'll be sure to bookmark it and return to read more of your useful info. Thanks for the post. I'll definitely return.
Davida # 3 weeks ago I like reading through a post that can make people think. Also, thank you for permitting me to comment!
Iinekb # 3 weeks ago purchase dydrogesterone pills <a href="https://janozin.shop/">dapagliflozin 10 mg sale</a> empagliflozin 25mg uk
Alta # 3 weeks ago Asking questions are genuinely fastidious thing if you are not understanding anything fully, but this piece of writing offers nice understanding even.
Alexandria # 3 weeks ago It's a shame you don't have a donate button! I'd most certainly donate to this brilliant blog! I suppose for now i'll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this site with my Facebook group. Chat soon!
Brittney # 3 weeks ago Does your site have a contact page? I'm having problems locating it but, I'd like to shoot you an e-mail. I've got some suggestions for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it grow over time.
Psuovo # 3 weeks ago fludrocortisone for sale <a href="https://pravinef.shop/">order florinef 100mcg for sale</a> purchase imodium for sale
Clay # 3 weeks ago Hello there, just became aware of your blog through Google, and found that it is really informative. I'm gonna watch out for brussels. I'll be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!
Rrlukm # 3 weeks ago buy generic etodolac for sale <a href="https://colotazol.shop/">cilostazol canada</a> pletal 100 mg price
Georgina # 2 weeks ago If some one wishes to be updated with newest technologies afterward he must be pay a quick visit this web site and be up to date all the time.
Udjzmu # 2 weeks ago prasugrel online buy <a href="https://thoramine.shop/">dimenhydrinate 50 mg us</a> tolterodine 1mg price
Katharina # 2 weeks ago Way cool! Some very valid points! I appreciate you penning this article and also the rest of the website is also really good.
Nfwlno # 2 weeks ago buy ferrous sulfate 100mg pills <a href="https://detorbic.shop/">buy cheap generic ascorbic acid</a> sotalol online
Knzwvg # 2 weeks ago buy mestinon pills for sale <a href="https://mestien.shop/">piroxicam 20mg sale</a> order generic rizatriptan
Wo kann ich capecitabin in Österreich kaufen? # 2 weeks ago If you are going for best contents like I do, only pay a visit this website all the time since it gives feature contents, thanks
Fgeblk # 1 week ago enalapril online buy <a href="https://duphstine.com/">order duphalac for sale</a> duphalac bottless
Vrkcpl # 1 week ago order xalatan eye drops <a href="https://aelimax.shop/">purchase xalatan generic</a> order rivastigmine 6mg for sale
Spencer # 1 week ago Howdy! Do you use Twitter? I'd like to follow you if that would be ok. I'm definitely enjoying your blog and look forward to new posts.
Waylon # 1 week ago When I originally commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on each time a comment is added I get four emails with the same comment. Is there a way you can remove me from that service? Thanks!
Yaudiv # 1 week ago oral betahistine 16mg <a href="https://haloatan.com/">order haloperidol sale</a> buy generic probenecid 500 mg
congest en vente libre en Suisse # 1 week ago Awesome post.
Xctlsh # 1 week ago oral telmisartan 80mg <a href="https://atizordis.shop/">buy telmisartan without a prescription</a> buy molnunat 200mg sale
Kauf von meclizine in Europa # 6 days ago Howdy this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I'm starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!
Aaqpzp # 5 days ago order generic cenforce <a href="https://chlodinir.com/">buy aralen without prescription</a> buy chloroquine 250mg sale
Realiza la compra de prempro en línea # 5 days ago Hello, this weekend is nice designed for me, because this moment i am reading this fantastic educational article here at my home.
Jerrod # 4 days ago Hey there! I could have sworn I've been to this site before but after browsing through some of the post I realized it's new to me. Anyhow, I'm definitely glad I found it and I'll be book-marking and checking back frequently!
czy mo?na zdoby? famciclovir bez recepty w Szczecinie? # 3 days ago Wonderful web site. Lots of useful info here. I'm sending it to some pals ans additionally sharing in delicious. And of course, thank you on your sweat!
puedo comprar cyklokapron sin receta en Perú # 2 days ago I constantly spent my half an hour to read this weblog's articles every day along with a cup of coffee.
aankoop van slaapmiddelen albenza # 6 minutes ago Hi there, yeah this post is genuinely pleasant and I have learned lot of things from it regarding blogging. thanks.
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.