PHP File Upload
Avec PHP, il est possible de télécharger des fichiers sur le serveur.
Créer un formulaire d'upload de fichier-
Pour permettre aux utilisateurs de télécharger des fichiers à partir d'un formulaire peut être très utile.
Regardez le formulaire ci-dessous pour télécharger des fichiers HTML:
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Notez ce qui suit au sujet du formulaire HTML ci-dessus:
- L'attribut enctype de la balise form spécifie le type de contenu à utiliser lors de la soumission du formulaire. "Multipart / form-data" est utilisée lorsque une forme nécessite des données binaires, comme le contenu d'un fichier, pour être transféré
- Le type = "file" attribut de la balise <input> spécifie que l'entrée devrait être traité comme un fichier. Par exemple, lorsqu'il est affiché dans un navigateur, il y aura un parcours-bouton à côté du champ de saisie
Note: Permettre aux utilisateurs de télécharger des fichiers est un gros risque de sécurité.Seulement permettre aux utilisateurs de confiance pour effectuer le téléchargement de fichiers.
Créer Le script d'upload
Le "upload_file.php" fichier contient le code pour télécharger un fichier:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
En utilisant l'échelle mondiale le tableau $ _FILES PHP, vous pouvez télécharger des fichiers depuis un ordinateur client au serveur distant.
Le premier paramètre est le nom sous la forme d'entrée et le second indice peut être soit "nom", "type", "taille", "tmp_name" ou "erreur". Comme ceci:
- $ _FILES ["File"] ["nom"] - le nom du fichier téléchargé
- $ _FILES ["File"] ["type"] - le type du fichier téléchargé
- $ _FILES ["File"] ["size"] - la taille en octets du fichier téléchargé
- $ _FILES ["File"] ["tmp_name"] - le nom de la copie temporaire du fichier stocké sur le serveur
- $ _FILES ["File"] ["error"] - le code d'erreur résultant de l'upload de fichier
Il s'agit d'un moyen très simple de télécharger des fichiers. Pour des raisons de sécurité, vous devriez ajouter des restrictions sur ce que l'utilisateur est autorisé à télécharger.
Restrictions sur Envoyer
Dans ce script, nous ajoutons certaines restrictions à l'upload de fichiers. L'utilisateur ne peut télécharger des images gif ou jpeg et la taille du fichier doit être de moins de 20 ko..:
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
Remarque: Pour IE pour reconnaître les fichiers jpg le type doit être pjpeg, pour FireFox, il doit être jpeg.
Enregistrer le fichier envoyé
Les exemples ci-dessus créer une copie temporaire des fichiers uploadés dans le dossier temp PHP sur le serveur.
Les fichiers temporaires copiés disparaît lorsque le script se termine. Pour stocker le fichier téléchargé nous avons besoin de le copier à un autre endroit:
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Le script ci-dessus vérifie si le fichier existe déjà, si ce n'est pas, il copie le fichier vers le dossier spécifié.
Remarque: Cet exemple enregistre le fichier dans un nouveau dossier appelé "upload"
Fantastic goods from you, man. I've understand your stuff previous to and you are just extremely fantastic. I really like what you've
ReplyDeleteacquired here, certainly like what you are stating and the
way in which you say it. You make it entertaining
and you still care for to keep it wise. I cant
wait to read far more from you. This is actually a tremendous website.
cleaning hardwood floors
Visit my page - hardwood floor refinishing
Asking questions are in fact good thing if you
ReplyDeleteare not understanding something completely, however
this post presents pleasant understanding yet.
Here is my web-site zetaclear nail fungus relief
Thanks for sharing such a good opinion, article is good, thats
ReplyDeletewhy i have read it completely
My blog post - treatment for toenail fungus
Nice weblog here! Additionally your site quite a bit up very fast!
ReplyDeleteWhat web host are you using? Can I get your affiliate hyperlink to your host?
I wish my web site loaded up as quickly as yours lol
my blog post :: cleaning services
I pay a quick visit everyday some web sites and blogs to read
ReplyDeleteposts, but this webpage provides feature based posts.
Also visit my website - zetaclear nail fungus relief
My page :: nail fungus zetaclear
Having read this I thought it was rather enlightening.
ReplyDeleteI appreciate you taking the time and effort to put this article together.
I once again find myself personally spending way too much time both reading and posting comments.
But so what, it was still worthwhile!
Also visit my web-site ... chestfatburner.com
We are a group of volunteers and starting a brand new scheme in our community.
ReplyDeleteYour web site provided us with useful information
to work on. You've performed a formidable job and our entire neighborhood will likely be thankful to you.
my blog post - chestfatburner.com
Really no matter if someone doesn't be aware of afterward its up to other viewers that they will help, so here it takes place.
ReplyDeleteHere is my homepage - What to request an individual doctor before starting gynecomastiasurgical procedure
First off I would like to say fantastic blog! I had a
ReplyDeletequick question which I'd like to ask if you do not mind. I was curious to find out how you center yourself and clear your head before writing. I've had a hard time clearing my mind in getting my ideas out there.
I truly do enjoy writing but it just seems like the first 10
to 15 minutes are generally wasted simply just trying to figure out how to begin.
Any suggestions or tips? Thanks!
Feel free to surf to my webpage chestfatburner.com
I love what you guys are up too. This kind of clever work and reporting!
ReplyDeleteKeep up the wonderful works guys I've incorporated you guys to our blogroll.
Here is my blog: Is there a Cause for " moobs " ?
Heya i'm for the first time here. I came across this board and I find It truly useful & it helped me out much. I hope to provide something again and aid others such as you helped me.
ReplyDeleteHere is my web-site; is gynecomastiathe Curable situation?
Hi there Dear, are you in fact visiting this web page regularly, if so afterward you will absolutely get pleasant experience.
ReplyDeleteAlso visit my website :: Meals reponsible with regard to development of " moobs "
I know this website gives quality dependent posts and additional information,
ReplyDeleteis there any other website which presents such information in quality?
qualified
Also visit my web site :: compare second mortgage rate
I all the time used to study article in news papers but now as I am a user of net
ReplyDeletetherefore from now I am using net for posts, thanks to web.
Have a look at my homepage - www.wonderware.fr
What i don't understood is in fact how you are no longer actually much more neatly-preferred than you may be now. You are so intelligent. You already know thus considerably relating to this matter, made me for my part consider it from numerous varied angles. Its like women and men aren't involved except it's something to do with Girl gaga! Your personal stuffs great. Always maintain it up!
ReplyDeleteMy weblog :: Michael Kors Handbags
I'm impressed, I must say. Rarely do I encounter a blog that's both equally educative and amusing,
ReplyDeleteand let me tell you, you have hit the nail on the head. The
issue is an issue that not enough men and women are speaking intelligently about.
I'm very happy I came across this during my hunt for something concerning this.
My web blog; Gucci Sito Ufficiale Scarpe
It's impressive that you are getting thoughts from this post as well as from our discussion made at this place.
ReplyDeletemy web page Converse Pas Cher
Hey very nice blog!
ReplyDeleteFeel free to visit my web site Abercrombie and Fitch
Hi there this is kind of of off topic but I was wanting to know if
ReplyDeleteblogs 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 advice from someone with experience. Any help would be greatly appreciated!
Here is my blog post - Abercrombie Fitch Belgique
Why viewers still make use of to read news papers when in this technological world everything is accessible on web?
ReplyDeleteTake a look at my web blog: Louis Vuitton Outlet Online
you're actually a just right webmaster. The website loading speed is incredible. It seems that you're doing any distinctive trick.
ReplyDeleteAlso, The contents are masterwork. you have
done a excellent process in this subject!
My page :: Abercrombie and Fitch
Hello friends, how is all, and what you want to say about
ReplyDeletethis article, in my view its truly amazing in support of me.
my blog post :: Air Max Pas Cher
Great article.
ReplyDeletemy page ... Abercrombie Brussel
This paragraph is really a nice one it helps new net viewers,
ReplyDeletewho are wishing in favor of blogging.
my homepage :: Cheap Jerseys
I'll right away snatch your rss feed as I can't to find your email subscription hyperlink or
ReplyDeletenewsletter service. Do you have any? Please let
me know in order that I could subscribe. Thanks.
Also visit my web-site Cheap Jerseys
I loved as much as you will receive carried out right here.
ReplyDeleteThe sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get got an shakiness over that you wish be delivering the following.
unwell unquestionably come further formerly again since exactly the same nearly very often inside case
you shield this hike.
Here is my site Michael Kors Canada
You can certainly see your enthusiasm within the article you write.
ReplyDeleteThe arena hopes for even more passionate writers like you
who are not afraid to say how they believe. All the time follow your heart.
Here is my web page: Michael Kors Bags
Thanks for some other informative website. Where else may just I get that type of
ReplyDeleteinfo written in such an ideal method? I have a project that I am simply now running on,
and I've been on the look out for such info.
Check out my website Abercrombie Pas Cher
Just desire to say your article is as astounding.
ReplyDeleteThe clearness in your post is simply cool and i can assume you're an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please keep up the gratifying work.
Feel free to visit my website; Sidney Crosby Black Jersey
Wow, that's what I was exploring for, what a material! existing here at this weblog, thanks admin of this website.
ReplyDeleteLook at my blog; http://www.explorethecapabilities.com/louisvuittonoutlet.html
With havin so much content and articles do you ever run into any problems of plagorism
ReplyDeleteor copyright infringement? My blog has a lot of unique content I've either written myself or outsourced but it appears a lot of it is popping it up all over the internet without my authorization. Do you know any solutions to help prevent content from being ripped off? I'd definitely appreciate it.
Feel free to surf to my web site; Michael Kors
I am not sure where you're getting your information, but great topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this info for my mission.
ReplyDeleteAlso visit my homepage Gafas Oakley Baratas
I have been browsing online more than 2 hours today, yet I never found any interesting article like yours.
ReplyDeleteIt is pretty worth enough for me. Personally, if all website owners and
bloggers made good content as you did, the internet will be a lot more useful than ever before.
Also visit my web site ... Air Max
Please let me know if you're looking for a author for your site. You have some really good posts and I believe I would be a good asset. If you ever want to take some of the load off, I'd really like to write some content for your blog
ReplyDeletein exchange for a link back to mine. Please
shoot me an email if interested. Regards!
Here is my weblog Air Max