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

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 :

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.

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:

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:

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.

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:

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.

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 Coidng.

Burak Hamdi TUFAN

LEAVE A REPLY

Please enter your comment!
Please enter your name here