React Native and PHP - How to upload image to web server - Part 2

React Native and PHP - How to upload image to web server - Part 2

Hi every one in this article we are going to talk about image or a file uploading from a mobile app (I have developed it with react native) and getting this with PHP web service. This is the second part of article.

Firstly you can reach at the First part of this article from here.

Now We can start to code. SHOW TIME :)

First we need to get datas that sent from our mobile app. We have sent the three datas. These are id, session and fileToUpload named datas. I have sent the id and session as singular datas. This means there is no attached data onto these datas. So we can get these two datas with $_POST['...'] GLOBALS. We can get these two datas as below code block :


$id      = isset($_POST['id']) ? $_POST['id'] : "";
$session = isset($_POST['session']) ? $_POST['session'] : "";

$id = $mysqli->real_escape_string($id);
$session = $mysqli->real_escape_string($session);

You can do whatever you want with session and id datas. I will just to use the id variable for naming our image for every user.

Now we must get the fileToUpload data and attached on this variable. We are going to use $_FILES['...'] GLOBAL. Below word will used for this purpose.


$_FILES["fileToUpload"]

Now we need to make our checks to upload our image. We can check the size of the image and the file is really image. Lets do this:


// Check if image file is a actual image or fake image
        if(isset($_POST["submit"])) {
            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
            if($check !== false) {
                $uploadOk = 1;
            } else {
                $result = array('result' => 'res_code' ,'msg' => 'File is not an image file' , 'session' => $session );
                echo json_encode($result);
                $uploadOk = 0;
            }
        }

        // Check file size
        if ($_FILES["fileToUpload"]["size"] > 30000000) {
            $result = array('result' => 'res_code' ,'msg' => 'Dosya Boyutu Çok Büyük...' , 'session' => $session );
            echo json_encode($result);
            $uploadOk = 0;
        }

In the first part of code we have getimagesize function. This function will try to get images size and if it returns false this file is not an image. It is another type of file. With this ( $_FILES["fileToUpload"]["tmp_name"] ) variable we are getting the file with name and the getimagesize function is checking this file's size if it is an image. Else returns false.

In the second part of the code we are checking the size of the file. We need to prevent oversized files to be upload. It will probably be bad our server. I am here checking the file is under 3MB. Else return an error code to the client program.

If they are okay we need to specify two variables. These are the target_file and the target_dir. Below code block will show how to do this:


$target_dir = "images/user_avatar/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
//Here we are getting the file extension if you want, you can use this code
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

NOTE: If you want to remove the old file you can check the file is exist and use unlink function. Below code section will do this.


if(file_exists($target_file)) {
      chmod($target_file , 0755); //Change the file permissions if allowed
      unlink($target_file); //remove the file
  }

Now we are ready to upload our image data. Let's do this. below code section will upload the image inside the specified directory. I will tell the code block after sharing my code:


$url_api_base = "thecodeprogram.com/images/";
$new_file_path = $target_file . '.jpg';

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_file_path )) {

                $new_file_path = $url_api_base . $target_file . '.jpg';

                //if you want you can change the user profile image
                $iupdate = $mysqli->query("UPDATE " . $table_Members . " SET avatar='$new_file_path' where id='$id' ");
                if($iupdate){
                    $result = array('result' => '1' ,'msg' => 'Your profile image was updated succesfully...' , 'ipath' => $url_api_base . $new_file_path );
                    echo json_encode($result);
                }else {
                    $result = array('result' => '2' ,'msg' => 'Updating profile image failed...' ,'ipath' => realpath( $new_file_path)  );
                    echo json_encode($result);
                }

                
            } else {
                $result = array('result' => '237' ,'msg' => 'Updating profile image failed...' );
                echo json_encode($result);
            }

Here first I have move_uploaded_file function here. This function will take the file from the memory and move inside the specifien folder. Here we are setting the target file as the below code.


$new_file_path = $url_api_base . $target_file . '.jpg';

Then we are changing the values of the account on the database. This action is optional. I will do this to change account profile image. So I have made the changing from the database. I will not tell the MySQL commands in this article.

Now we uploaded the image from mobile phone.

Thanks for the reading my article.

Have a Nice Coding.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...