downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Utiliser des codes anciens avec les nouvelles versions de PHP> <Trucs pratiques
[edit] Last updated: Fri, 10 Feb 2012

view this page in

Utiliser un formulaire

L'un des points forts de PHP est sa capacité à gérer les formulaires. Le concept de base qui est important à comprendre est que tous les champs d'un formulaire seront automatiquement disponibles dans le script PHP d'action. Lisez le chapitre du manuel concernant les variables depuis des sources externes à PHP pour plus d'informations et d'exemples sur la façon d'utiliser les formulaires. Voici un exemple de formulaire HTML :

Exemple #1 Un simple formulaire HTML

<form action="action.php" method="post">
 <p>Votre nom : <input type="text" name="nom" /></p>
 <p>Votre âge : <input type="text" name="age" /></p>
 <p><input type="submit" value="OK"></p>
</form>

Il n'y rien de particulier dans ce formulaire. Il est en HTML pur, sans aucune configuration particulière. Lorsque le visiteur remplit le formulaire, et clique sur le bouton OK, le fichier action.php est appelé. Dans ce fichier, vous pouvez écrire le script suivant :

Exemple #2 Afficher des données issues d'un formulaire

Bonjour, <?php echo htmlspecialchars($_POST['nom']); ?>.
Tu as <?php echo (int)$_POST['age']; ?> ans.

Voici le résultat que vous pourriez obtenir, selon les valeurs que vous avez saisies :

Bonjour Jean.
Tu as 29 ans.

Mise à part les parties htmlspecialchars() et (int), ce script ne fait que des choses évidentes. htmlspecialchars() s'assure que tous les caractères spéciaux HTML sont proprement encodés afin d'éviter des injections de balises HTML et de Javascript dans vos pages. Pour l'âge, vu que nous savons que c'est un entier, vous pouvez le convertir en un entier. Vous pouvez également demander à PHP de le faire automatiquement à votre place en utilisant l'extension filter. Les variables $_POST['nom'] et $_POST['age'] sont automatiquement créées par PHP. Un peu plus tôt dans ce tutoriel, nous avons utilisé la variable $_SERVER, une superglobale. Maintenant, nous avons introduit une autre superglobale $_POST qui contient toutes les données envoyées par la méthode POST. Notez que dans notre formulaire, nous avons choisi la méthode POST. Si vous avions utilisé la méthode GET alors notre formulaire aurait placé ces informations dans la variable $_GET, une autre superglobale. Vous pouvez aussi utiliser la variable $_REQUEST, si vous ne souhaitez pas vous embarrasser de la méthode utilisée. Elle contient un mélange des données de GET, POST, COOKIE et FILE. Voyez aussi la fonction import_request_variables().

Vous pouvez également utiliser des champs XForms dans PHP, même si vous vous sentez bien avec l'utilisation des formulaires HTML. Bien que le travail avec XForms ne soit pas fait pour les débutants, vous pourriez être intéressé par cette technologie. Nous avons également une courte introduction sur le traitement des données reçues par XForms dans notre section sur les fonctionnalités.



add a note add a note User Contributed Notes Utiliser un formulaire
Johann Gomes (johanngomes at gmail dot com) 11-Oct-2010 09:20
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
arnel_milan at hotmail dot com 29-Mar-2008 10:27
I was so shocked that some servers have a problem regarding the Submit Type Name and gives a "Not Acceptable error" or Error 406.

Consider the example below :

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
   
    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submit_btn" id="Submit_btn" value="Send">
      </td>
    </tr> 
  </table>
</form>

This very simple code triggers the "Not Acceptable Error" on
PHP Version 5.2.5 and Apache 1.3.41 (Unix) Server.

However to fix this below is the right code:

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
   
    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submitbtn" id="Submit_btn" value="Send">
      </td>
    </tr> 
  </table>
</form>

The only problem that took me hours to find out is the "_" in the Submit Button.

Hope this help!
SvendK 08-Nov-2006 09:02
As Seth mentions, when a user clicks reload or goes back with the browser button, data sent to the server, may be sent again (after a click on the ok button).

It might be wise, to let the server handle whatever there is to handle, and then redirect (a redirect is not visible in the history and thus not reachable via reload or "back".

It cannot be used in this exact example, but as Seth also mentions, this example should be using GET instead of POST
yasman at phplatvia dot lv 05-May-2005 02:18
[Editor's Note: Since "." is not legal variable name PHP will translate the dot to underscore, i.e. "name.x" will become "name_x"]

Be careful, when using and processing forms which contains
<input type="image">
tag. Do not use in your scripts this elements attributes `name` and `value`, because MSIE and Opera do not send them to server.
Both are sending `name.x` and `name.y` coordiante variables to a server, so better use them.
sethg at ropine dot com 01-Dec-2003 01:55
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything.  For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.

 
show source | credits | sitemap | contact | advertising | mirror sites