Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Capturing images and videos from the camera of mobile devices using HTML

Collecting and uploading files from the user’s device is a task that most modern web applications need to do every now and then. In such scenarios, the <input> with the file type can be used to handle file uploads.

Now, the file input let the user choose one or more existing files from their device storage. But in some situations, you might want to give the user the ability to open the camera of the device, capture the media and upload it to the server.

Turns out, it’s pretty easy to do this by providing just couple more attributes to the <input> elements with type="file".

The capture and accept attributes

By providing the additional capture and accept attributes to the file input, it’s possible to give the user the ability to capture media from the device’s camera/microphone.

Note: These work better on mobile devices. So, if your device is a desktop computer, you’ll likely get a typical file picker.

The capture attribute takes in the following two string values that specify which camera to use for the capture of image or video data.

  • user - The user-facing camera and/or microphone should be used
  • environment - The outward-facing camera and/or microphone should be used

You can specify what kind of files you want to accept in the accept attribute. Usually, it can be one of these values.

  • image/* - To capture any file with an image/* MIME type.
  • audio/* - To capture any file with an audio/* MIME type.
  • video/* - To capture any file with an video/* MIME type.

Capturing images from the camera

So, if we want the file input to take an image from the device’s camera, here’s how we can do it.

<input type="file" name="photo" capture="user" accept="image/*">

Capturing videos from the camera

To capture a video from the camera, here’s what we can do.

<input type="file" name="video" capture="user" accept="video/*">

Capturing audio from the microphone

And lastly, here’s how to capture an audio from the device’s microphone.

<input type="file" name="audio" capture="user" accept="audio/*">

The demo

I have put together a demo that has all three input combinations. You can try opening this in a browser on the mobile device and see how all these open camera/audio interfaces of the device to capture media.

See the Pen User capture input by Amit Merchant (@amit_merchant) on CodePen.

In action

Watch it in action in this video.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?