PHP Image/File Upload Tutorial and Example [FormData and Angular 7 Front-End]

PHP Image/File Upload Tutorial and Example [FormData and Angular 7 Front-End]

In this post we will give you information about PHP Image/File Upload Tutorial and Example [FormData and Angular 7 Front-End]. Hear we will give you detail about PHP Image/File Upload Tutorial and Example [FormData and Angular 7 Front-End]And how to use it also give you demo for it if it is necessary.

In this tutorial, you’ll learn how you can upload files in your PHP web application. We’ll not use any framework but plain PHP.

Next, we’ll see how we can use Angular 7 to create a frontend that provides a form for uploading an image file to the backend using FormData and HttpClient. We’ll be also looking at how to create a reactive form with Angular.

File upload is a common feature that you need to implement in many web applications so in this guide we’ll see step by step how you can create a PHP application that exposes an /upload.php endpoint that accepts POST requests with a multipart/form-data containing the file data.

If you are ready, let’s get started!

Start by creating a folder for your project’s files. Open a new terminal, go to your working directory and create a folder:

$ cd ~$ mkdir php-file-upload

Next, navigate inside your project’s folder and create an upload.php file:

$ cd php-file-upload$ touch upload.php

Using your favorite code editor open the upload.php file and follow the steps to implement file uploading.

When a user sends a file to the /upload.php endpoint, the file gets uploaded to a temporary folder. Also the information about the sent file is stored in the special $_FILES array. You can access the information about your file by using the value assigned to the name attribute of the input field of the sent form i.e <input type='file' name="avatar"> (in this case it’s avatar).

You can also access more information like the name, temporary name and error using the following PHP code:

<?php$avatar_name=$_FILES["avatar"]["name"];$avatar_tmp_name=$_FILES["avatar"]["tmp_name"];$error=$_FILES["avatar"]["error"];?>

After sending the file to your server, It will be uploaded to the temporary folder. You can then use the move_uploaded_file() method to move the file from the temporary location to a chosen location that you use for saving the uploaded files in your server.

Let’s start by adding the following headers to our upload.php file:

header('Content-Type: application/json; charset=utf-8');header("Access-Control-Allow-Origin: *");header("Access-Control-Allow-Methods: PUT, GET, POST");

The first header set the content type as application/json and charset as utf-8.

The second header is used to enable CORS for all domains. This means our server will accept request from any domain. This is not recommended in production, you should only allow code hosted in your domain or a specific domain to send requests to your server.

The last header sets the allowed methods which are PUT, GET and POST.

Next, define the following variables:

$response = array();$upload_dir = 'uploads/';$server_url = 'http://127.0.0.1:8000';
  • The $response variable will hold the HTTP response that will be sent back to the client after uploading a file.
  • The $upload_dir variables contains the folder where the file will be uploaded.
  • The $server_url contains the address of our server.

Next, add an if statement that checks if the $_FILES array contains an object with avatar key which will be available only if the user sends a form with file field named avatar or a FormData object with field named avatar:

if($_FILES['avatar']){    // code will be added here.}else{    $response = array(        "status" => "error",        "error" => true,        "message" => "No file was sent!"    );}echo json_encode($response);

We return the response back to the client after encoding it in JSON format using the json_encode() method.

Next, in the if statement and if the $_FILES['avatar'] is defined, add the code that follows. First define the following variables:

    $avatar_name = $_FILES["avatar"]["name"];    $avatar_tmp_name = $_FILES["avatar"]["tmp_name"];    $error = $_FILES["avatar"]["error"];

Next, check if the $error variable contains a value greater than which indicates that there is an error:

    if($error > 0){        $response = array(            "status" => "error",            "error" => true,            "message" => "Error uploading the file!"        );    }else     {        // The rest of your code will be added here.    }

Finally add the following code if there is no error:

        $random_name = rand(1000,1000000)."-".$avatar_name;        $upload_name = $upload_dir.strtolower($random_name);        $upload_name = preg_replace('/s+/', '-', $upload_name);        if(move_uploaded_file($avatar_tmp_name , $upload_name)) {            $response = array(                "status" => "success",                "error" => false,                "message" => "File uploaded successfully",                "url" => $server_url."/".$upload_name              );        }else        {            $response = array(                "status" => "error",                "error" => true,                "message" => "Error uploading the file!"            );        }

We first, create a new name for the file by concatenating a random number with a hyphen and the origin name. Next, we lowercase the random name and we concatenate with the upload folder path. Next we replace any spaces with the hyphen character. After preparing the full path for the file, we use the move_uploaded_file() to move the temporary name to the uploads directory and save it with the new name. If the move_uploaded_file() returns successfully we create a response object indicating success. Otherwise we create a response object indicating a failure with the Error uploading the file! message.

This is the full content of the file upload script:

Hope this code and post will helped you for implement PHP Image/File Upload Tutorial and Example [FormData and Angular 7 Front-End]. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US