Php form image value

How To Upload An Image With PHP

In this quick tutorial we set up a basic HTML form to upload images with PHP, we also explore how to secure our PHP script so it can’t be abused by malicious users.

Setting Up An Image Upload Form

We start with a basic form.

The form contains a submit button and has an action attribute. The action attribute points to the page the form will post all its contents to when the submit button is clicked.

form action="upload.php" method="POST"> button type="submit">Uploadbutton> form>

The form posts to a PHP file called upload.php . This file will handle the image upload. We’ll get to that in a minute.

To allow users to select a file we add a file input field.

form action="upload.php" method="POST" enctype="multipart/form-data"> input type="file" name="image" accept="image/*" /> button type="submit">Uploadbutton> form>

At the same time we’ve also added the enctype form attribute and set it to «multipart/form-data» . This is needed if we have a file input field in our form.

Because we’re only uploading images we add the accept attribute to the file input element and set it to image/* telling it to only accept files that have a mimetype that starts with image , like image/jpeg or image/png .

Let’s write the PHP image upload handler next.

Handling the PHP Image Upload

We’ll create a new file called upload.php in the same directory as the page that contains our form.

Next we create a directory called «images» , also in the same directory. This is where our script will store uploaded image files using the move_uploaded_file function.

 // Get reference to uploaded image $image_file = $_FILES["image"]; // Image not defined, let's exit if (!isset($image_file))  die('No file uploaded.'); > // Move the temp image file to the images/ directory move_uploaded_file( // Temp image location $image_file["tmp_name"], // New image location, __DIR__ is the location of the current PHP file __DIR__ . "/images/" . $image_file["name"] );

We’re done. This is all that’s needed to make it work.

Unfortunately not everyone on the internet is a saint. Our script currently allows anyone to upload anything, this is a security risk. We need to make sure people upload valid images and are not trying to harm our server.

Securing The Image Upload Process

We’re going to make extra sure these three things are in order.

  • The file needs to be an image.
  • The file must be smaller than 5MB.
  • The file must have a valid name.

Making Sure The File Is An Image

Let’s start by making sure the uploaded file is indeed an image.

Using exif_imagetype we can get the image mimetype, the function returns false when the file is not an image.

 // Get reference to uploaded image $image_file = $_FILES["image"]; // Exit if no file uploaded if (!isset($image_file))  die('No file uploaded.'); > // Exit if is not a valid image file $image_type = exif_imagetype($image_file["tmp_name"]); if (!$image_type)  die('Uploaded file is not an image.'); > // Move the temp image file to the images/ directory move_uploaded_file( // Temp image location $image_file["tmp_name"], // New image location __DIR__ . "/images/" . $image_file["name"] );

Next we need to stop users from uploading very large files.

Limiting The File Size

In the example below we limit the image file size to 5MB, of course you can choose your own limit, but it’s a good idea to at least cap it at a certain point to prevent users from uploading gigabytes of data in an attempt to DoS attack your server.

In the directory of our upload.php script we create a .htaccess file and set its contents to the following.

The LimitRequestBody prevents a request from exceeding 5MB, note that this includes other fields in the form.

Now let’s make sure users can’t uploading 0 byte files. We use filesize to read out the actual file size instead of rely on the [«size»] reported by $_FILES as that can be modified by the user.

 // Get reference to uploaded image $image_file = $_FILES["image"]; // Exit if no file uploaded if (!isset($image_file))  die('No file uploaded.'); > // Exit if image file is zero bytes if (filesize($image_file["tmp_name"])  0)  die('Uploaded file has no contents.'); > // Exit if is not a valid image file $image_type = exif_imagetype($image_file["tmp_name"]); if (!$image_type)  die('Uploaded file is not an image.'); > // Move the temp image file to the images/ directory move_uploaded_file( // Temp image location $image_file["tmp_name"], // New image location __DIR__ . "/images/" . $image_file["name"] );

Let’s now make sure the file name of the image is valid.

Guarding Against Malicious File Names

Malicious actors can try to upload an image with named ‘../index.php’ , our PHP script would now store this “image” in ‘images/../index.php’ possibly overwriting our own index.php file.

We can try to sanitize the image file name, but a safer approach is to generate our own file name.

We’ll generate some random_bytes and use those as the name for our image.

 // Get reference to uploaded image $image_file = $_FILES["image"]; // Exit if no file uploaded if (!isset($image_file))  die('No file uploaded.'); > // Exit if image file is zero bytes if (filesize($image_file["tmp_name"])  0)  die('Uploaded file has no contents.'); > // Exit if is not a valid image file $image_type = exif_imagetype($image_file["tmp_name"]); if (!$image_type)  die('Uploaded file is not an image.'); > // Get file extension based on file type, to prepend a dot we pass true as the second parameter $image_extension = image_type_to_extension($image_type, true); // Create a unique image name $image_name = bin2hex(random_bytes(16)) . $image_extension; // Move the temp image file to the images directory move_uploaded_file( // Temp image location $image_file["tmp_name"], // New image location __DIR__ . "/images/" . $image_name );

Our last step is to prevent code from being executed in our images directory.

Preventing Code Execution In The Images Directory

In our images directory we create a .htaccess file and set its contents to the following to prevent any uploaded PHP files from being run.

This make sure that PHP code in this folder won’t execute. So if someone still manages to upload a PHP file, for example a PHP file disguised as an image, it still won’t run.

Our file upload process is now secure. 🎉

Conclusion

We’ve written a basic form with file input element, to handle the upload we created a PHP file that moves the uploaded image to a directory on the server. To secure the upload process, we made sure the filename is valid, the file size is not too high, and the uploaded file is actually an image.

If you’re also looking to add image editing functionality to the file upload field you can use the element. This Pintura powered web component automatically opens a powerful image editor when an image is added to the field and enables your users to edit images before upload.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

At PQINA I design and build highly polished web components.

Make sure to check out FilePond a free file upload component, and Pintura an image editor that works on every device.

Источник

Php form image value

I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)

Anyways, here is a fuller example than the sparce one in the documentation above:

foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;

$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);

if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>

Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.

The following example form breaks their codes:

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;

$request = ServerRequestFactory :: fromGlobals ();

if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>

$uploaded_files = $request -> getUploadedFiles ();

if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>

$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];

if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>

$file -> moveTo ( ‘/path/to/new/file’ );

The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.

Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)

Multi-files with HTML array feature —

Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)

[type] => Array
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)

The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.

function normalize_files_array ( $files = [])

foreach( $files as $index => $file )

if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>

foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>

?>

The following is the output from the above method.

Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

Источник

How to upload and validate a image in php

In this tutorial I will explain how to upload a image and how to validate image extension
Create an HTML form with two text field :

  • One is for Image title with input type text.
  • Second one is for upload image with input type file.For file upload input must be file(type=”file”). This input type show the file select control.

HTML form must have following attributes :

  • method=”post”
  • enctype=”multipart/form-data” (The enctype attribute specifies how the form-data should be encoded when submitting it to the server.)

without these attributes , the image upload will not work.

Create a database with name imagesdata. Inside this database we create a table with name tblimages.
SQL Script for tblimages—

Now create a database connection file(config.php)

PHP Script for getting posted values, image validation, move images into directory and insertion data into database

$query = mysqli_query ( $con , «insert into tblimages(ImagesTitle,Image) values(‘$imgtitle’,’$imgnewfile’)» ) ;

How to run this script

  1. Download the zip
  2. Extract zip file and put in the root directory
  3. open phpmyadmin. Create a db imagesdata then import SQL file(given inside the package)

Hi! I am Anuj Kumar, a professional web developer with 5+ years of experience in this sector. I found PHPGurukul in September 2015. My keen interest in technology and sharing knowledge with others became the main reason for starting PHPGurukul. My basic aim is to offer all web development tutorials like PHP, PDO, jQuery, PHP oops, MySQL, etc. Apart from the tutorials, we also offer you PHP Projects, and we have around 100+ PHP Projects for you.

Источник

Читайте также:  Javascript document write asp
Оцените статью