Validating files in php

File Validation in PHP

validate file in php

In this tutorial, we will create a Simple Validate File using PHP. This code will validate a file inside your directory if it exists when the user clicks the confirm button. The system uses a PHP POST to initiate a method that certifies a file in your folder by the use of file_exist() by adding the path as a parameter. This is a user-friendly kind of program feel free to modify it.

We will be using PHP as a scripting language and interpreter, which is mainly used on any web server, including xamp, wamp, etc. It is being used on any popular website, and it has a modern technology that can be easily used by the next generation.

Getting Started:

First, you have to download & install XAMPP or any local server that runs PHP scripts. Here’s the link for the XAMPP server https://www.apachefriends.org/index.html .

And, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/ .

Creating The Interface

This is where we will create a simple form for our application. To create the forms, copy and write it into your text editor, then save it as index.php .

        

PHP - Simple Validate File


Note: All files are text format
Validate File here

Creating the Save File Function
This code contains the saving function of the application. This code will store the uploaded file to its respected folder when the form is submitted. To make this just copy and write these block of codes below inside the text editor, then save it as save_file.php

Creating the Main Function

This code contains the main function of the application. This code will validate a file if exist when the button is clicked. To make this just copy and write these block of codes below inside the text editor, then save it as validate.php

File ".$filename." exist!

"; >else< echo "

File ".$filename." does not exist!

"; > > ?>

There you have it we successfully created Simple Validate File using PHP. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

Источник

File Upload Validation in PHP

In this article, you will learn file upload validation using the PHP programming language. While uploading a file, there may be a need to validate the uploaded file type, file size, existence of the uploaded file, and so on. PHP provides HTTP File Upload variables $_FILES, which is an associative array containing uploaded items via the HTTP POST method.

Here is a simple example of how to upload a file and apply all types of file validation using PHP. As file upload involves potential security risks, we have mitigated these risks where possible.

File Upload Validation in PHP

index.php

  File Upload Validation in PHP  action='#' method="post" enctype="multipart/form-data">  type="file" name="uploadedfile" />  type="Submit" value="Submit" />   if($_FILES['uploadedfile']['error'] > 0 )< echo 'There is problem in file upload'; switch($_FILES['uploadedfile']['error']) < case 1: echo 'File exceeded upload_max_filesize'; break; case 2: echo 'File exceeded max_file_size'; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break; > exit; > // Check for right MIME types if($_FILES['uploadedfile']['type'] != 'text/plain')< echo 'File is not plain text'; exit; > //Set file location $uploadedfile = 'upload/'.$_FILES['uploadedfile']['name']; if(is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) < if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadedfile)) < echo 'File does not move to destination directory'; exit; > > else < echo 'File is not uploaded'; exit; > echo 'File uploaded successfully'; //Get the content of uploaded file $fopen = fopen($uploadedfile, 'r'); $contents = fread($fopen, filesize($uploadedfile)); fclose($fopen); $contents = strip_tags($contents); $fopen = fopen($uploadedfile, 'w'); fwrite($fopen, $contents); fclose($fopen); // Print the contents of uploaded file echo '

'; echo $contents; ?>

In the above code, the uploaded file is stored in a superglobal array «$_FILES«, which contains-

$_FILES[‘uploadedfile’][‘error’]- to check the error code.
$_FILES[‘uploadedfile’][‘type’]- to get the uploaded file type.
$_FILES[‘uploadedfile’][‘name’]- to get the uploaded file name.
$_FILES[‘uploadedfile’][‘tmpname’]- As the uploaded file is first stored in a temporary directory, it is used to get the temporary file name.

After that, we checked the uploaded file contents. For this, we first clean out any stray HTML or PHP tags that might be in the file using the strip_tags() function, and then print the uploaded file contents.

Источник

How to upload files with PHP correctly and securely

If you just want the sourcecode — scroll to the end of the page or click here. But I recommend reading the article to understand why I’m doing things as I do and how it works. Hey Guys, in this post, I’ll show you how to upload files to your server using HTML and PHP and validate the files. I hope it’s useful for some of you and now happy coding 🙂

Security information

First of all, the most important thing I want to tell you, the $_FILES variable in PHP (except tmp_name ) can be modified. That means, do not check e.g. the filesize with $_FILES[‘myFile’][‘size’] , because this can be modified by the uploader in case of an attack. In other words, when you validate the upload with this method, attackers can pretend that their file has another file size or type. As you can see, there is a lot we need to take care of. Maybe it’s worth considering to use an already existing service. With Uploadcare you can upload and manage files quickly and easily via their PHP integration. So, let’s move on and create our own, secure, file upload.

HTML Setup

 method="post" action="upload.php" enctype="multipart/form-data">  type="file" name="myFile" />  type="submit" value="Upload">  

That’s it. Note the action=»upload.php» , that’s the PHP script handling the upload. And we use the name myFile to identify the file in PHP.

PHP Validation

Now, let’s validate the file in the upload.php file. First of all, we have to check if there is a file passed to our script. We do this using the $_FILES variable:

if (!isset($_FILES["myFile"]))  die("There is no file to upload."); > 

But remember, for security reasons, we can’t get the filesize using $_FILES . When the user uploads the file, PHP stores it temporarily and you can get the path using $_FILES[‘myFile’][‘tmp_name’] . That’s what we use now to get the real size and type of the file.

$filepath = $_FILES['myFile']['tmp_name']; $fileSize = filesize($filepath); $fileinfo = finfo_open(FILEINFO_MIME_TYPE); $filetype = finfo_file($fileinfo, $filepath); 

Now we have the real information, let’s validate the filesize. We don’t want to allow users to upload empty files, so first, we check if the file size is greater than 0:

if ($fileSize === 0)  die("The file is empty."); > 
if ($fileSize > 3145728)  // 3 MB (1 byte * 1024 * 1024 * 3 (for 3 MB)) die("The file is too large"); > 

Great. But you’ll usually only allow specific types to be uploaded, e.g. .png or .jpg for profile images. For more flexibility, let’s create an array with all allowed file types:
(Thanks to Gary Marriott and Renorram Brandão for pointing me out, we have to store the extensions for each type here in the array so we can append it later to the filename)

$allowedTypes = [ 'image/png' => 'png', 'image/jpeg' => 'jpg' ]; 

You can find a list of MIME-Types here (It’s in german, but there is a great table with all MIME-Types and file extensions). Now let’s check if the type of the file is allowed:

if(!in_array($filetype, array_keys($allowedTypes)))  die("File not allowed."); > 

And we’re done with validating! In the last step, we move the file to our uploads directory (or wherever you want to). For this, I define a variable with my target directory, then grab the current filename and extension and build the new, target file path:

$filename = basename($filepath); // I'm using the original name here, but you can also change the name of the file here $extension = $allowedTypes[$filetype]; $targetDirectory = __DIR__ . "/uploads"; // __DIR__ is the directory of the current PHP file $newFilepath = $targetDirectory . "/" . $filename . "." . $extension; 
if (!copy($filepath, $newFilepath ))  // Copy the file, returns false if failed die("Can't move file."); > unlink($filepath); // Delete the temp file echo "File uploaded successfully :)"; 

That’s it! Now you have a secure file upload where you can strictly define which files can be uploaded and which not!

Full code

  lang="en">  charset="UTF-8">  http-equiv="X-UA-Compatible" content="IE=edge">  name="viewport" content="width=device-width, initial-scale=1.0"> Document    method="post" action="upload.php" enctype="multipart/form-data">  type="file" name="myFile" />  type="submit" value="Upload">   
 if (!isset($_FILES["myFile"]))  die("There is no file to upload."); > $filepath = $_FILES['myFile']['tmp_name']; $fileSize = filesize($filepath); $fileinfo = finfo_open(FILEINFO_MIME_TYPE); $filetype = finfo_file($fileinfo, $filepath); if ($fileSize === 0)  die("The file is empty."); > if ($fileSize > 3145728)  // 3 MB (1 byte * 1024 * 1024 * 3 (for 3 MB)) die("The file is too large"); > $allowedTypes = [ 'image/png' => 'png', 'image/jpeg' => 'jpg' ]; if (!in_array($filetype, array_keys($allowedTypes)))  die("File not allowed."); > $filename = basename($filepath); // I'm using the original name here, but you can also change the name of the file here $extension = $allowedTypes[$filetype]; $targetDirectory = __DIR__ . "/uploads"; // __DIR__ is the directory of the current PHP file $newFilepath = $targetDirectory . "/" . $filename . "." . $extension; if (!copy($filepath, $newFilepath))  // Copy the file, returns false if failed die("Can't move file."); > unlink($filepath); // Delete the temp file echo "File uploaded successfully :)"; 

Источник

Читайте также:  Super apps for java
Оцените статью