2.9. Avatars

I'm taking advantage of the fact that each user must have a unique alphanumeric username. When saving an uploaded graphic for the avatar with the username as the filename, you don't have to worry about overwriting files. If a file does get overwritten, it's because the user is uploading a newer file for his or her avatar. This also spares you from tracking additional information in the database as mentioned earlier.

To upload a file through an HTML form, the form element must have the enctype attribute set to multipart/form-data. Then the user can specify the file through an input element:

<form action=upload_avatar.php" method="post" enctype="multipart/form-data">
 <div>
  <input type="file" name="avatar"/>
  <input type="submit" value="upload"/>
 </div>
</form>

Information about uploaded files is available to PHP in the $_FILES superglobal array. It's a multidimensional array with the name assigned to the HTML form's input element as the first index (useful when uploading multiple files) and the following for the second:

  • name — the original filename

  • tmp_name — the name of the file as it is stored temporarily on the server

  • size — the size of the file (reported in bytes)

  • type — the file's mime-type

  • error — an error code indicating the reason for failure of an upload (the value will be 0 if the upload was successful)

The uploaded file is temporarily stored and will be deleted once the script is done running, so usually it is necessary to copy the file to a permanent location ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.