Sunday, 29 May 2022

Upload Files On Google Drive Using PHP API

 


Upload Files On Google Drive Using PHP API

-------------------------------

Google Drive API Part 1:-
https://youtu.be/etZFZPKJc_I

Stack Overflow Link :-

https://stackoverflow.com/questions/25707891/google-drive-php-api-simple-file-upload


Subscribe my Channel:- 

http://www.youtube.com/user/SanketRooney?sub_confirmation=1 


Facebook Page:- 

https://www.facebook.com/UnpossibleNS 


Twitter Account:- 

https://twitter.com/UnpossiblePOG 


Blog:- 

https://unpossiblepog.blogspot.com/ 


Website:- 

https://unpossiblepog.com/ 

Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/


-------------------------------

upload-file.php

-------------------------------


<?php

require __DIR__ . '/vendor/autoload.php';


$client = new Google_Client();


// Get your credentials from the console


$client->setClientId('<YOUR_CLIENT_ID>');


$client->setClientSecret('<YOUR_CLIENT_SECRET>');


$client->setRedirectUri('<YOUR_REGISTERED_REDIRECT_URI>');


$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));





session_start();





if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {


if (isset($_GET['code'])) {


$client->authenticate($_GET['code']);


$_SESSION['access_token'] = $client->getAccessToken();


} else


$client->setAccessToken($_SESSION['access_token']);





$service = new Google_Service_Drive($client);





//Insert a file


$file = new Google_Service_Drive_DriveFile();


$file->setName(uniqid().'.jpg');


$file->setDescription('A test document');


$file->setMimeType('image/jpeg');





$data = file_get_contents('a.jpg');





$createdFile = $service->files->create($file, array(


'data' => $data,


'mimeType' => 'image/jpeg',


'uploadType' => 'multipart'


));





print_r($createdFile);





} else {


$authUrl = $client->createAuthUrl();


header('Location: ' . $authUrl);


exit();


}


?>


-------------------------------




In last part, we were able to list files from google drive.


In this part, we shall upload files from our server to google drive.


Let’s jump right into it.


I got a code from stack-overflow, you can copy-paste the code from their link or from my blog. Both links are given in the description.


Create a php file inside a google drive folder which we created last time.


Paste the code inside it within php tags.


We have a vendor folder ready, so remove first 2 lines & import the library.


For client id and client secret. We have to look into credentials.json file.


Also make sure that we first ran quickstart file, the scope was DRIVE.


If not, delete credentials.json file and redo steps again.


Inside json file, we shall find client-id and client-secret.


Copy-paste them inside our code.


In console cloud google site, first select the project.


Then go inside credentials inside APIS & SERVICES.


Select the authentication ID, inside it, add extra URL.


Use the name of newly created php file and save it.


As per code, we shall upload a.png file so change the code accordingly.


Now hit our file in URL.


There is an error.


Change the file path to absolute. Save it.


Add the file path.


After refresh, it will print some array.


And if you go inside your google drive, you will find that image.

Thanks for watching.


Sunday, 24 April 2022

Google Drive API PHP | Display List Of Files From Google Drive On Browser



JQUERY Validator | Move Error Messages Anywhere On Web Page

-------------------------------

http://www.youtube.com/user/SanketRooney?sub_confirmation=1 


Facebook Page:- 
https://www.facebook.com/UnpossibleNS 

Twitter Account:- 
https://twitter.com/UnpossiblePOG 

Blog:- 
https://unpossiblepog.blogspot.com/ 

Website:- 
https://unpossiblepog.com/ 

Gaming Instagram:- (@unpog.gaming)
https://www.instagram.com/unpog.gaming/

-------------------------------

By the end of this video you will be able to get list of files from your google drive using PHP.

Let’s not waste the time, shall we?

Open the google and search “Google Drive API PHP”.

Open the developer.google.com site.

You have to have PHP version greater than 5.4.

Also, if you are using Windows OS, you can download the composer from this link.

For linux user, you have to enter the command “sudo apt install composer”.

You can find how to enable API, however sometimes google update this page, so this link won’t always be here.

So to enable the API, follow my steps.

On google, search “console cloud google”.

Go inside the link called “console.cloud.google.com”

From side menu, click on dashboard inside home.

Here, next to Google Cloud Platform, you will see one dropdown, click on it, create a new project.

Give it any random name.

Wait for project to be created.

After that, again click on dropdown and select the project that you recently created.

After that, open the side menu, and in APIs & Services, click on Credentials.

Click on CREATE CREDENTIALS, and OAUTH Client ID.

Initially you will have to configure the project.

Only the EXTERNAL USER TYPE is available, so click on it and click on CREATE.

Give any random APP NAME.

Select your email ID.

Scroll down.

Add any random domain.

You can even add google.com for now.

I have my own website so I am going to add it.

In Developer contact information, add your own email address.

Click on SAVE AND CONTINUE.

Add all the scopes available.

In test users, add your own email address for now.

Click on SAVE AND CONTINUE.

Now, we are ready to create credentials.

Again go to side menu, APIS and SERVICES, Credentials.

Click on CREATE CREDENTIALS, OAUTH CLIENT ID.

Select Web Application.

Give any name.

In Authorized JS Origins, you can add localhost’s IP address.

In, Authorized redirect URIs, you have to add the path which will display list of files in google drive.

I am using XAMPP, so in HTDOCS, I am going to create a folder.

Use the folder name next to ip address and then “quickstart.php”.

We shall later going to create a quickstart PHP file.

Once done, you will see CLIENT ID, click on it’s download icon.

Download the JSON.

Copy-paste that file inside google-drive folder which is inside HTDOCS folder of xampp.

Rename it to credentials.json file as given in code.

Open the command prompt, and reach to the google-drive folder by using CD commands.

Once reached, type the command as shown in document.

Wait for vendor file to download.

After that, create a quickstart.php file in that google-drive folder.

Paste the given code inside that file.

We shall change scope to DRIVE because in next video, we shall upload files from localhost to google drive.

Change the number of files that you want to list.

Go to google cloud platform, click on Library, search GOOGLE DRIVE API.

Enable the API.

Now run the command they provided in same command prompt.

It shall ask for verification code.

Mark the link and right click at the top of CMD, and copy it.

Paste it in browser’s URL.

Login with your email.

Actually I forgot to start XAMPP.

But it doesn’t matter.

Copy the value of CODE in URL up to the “&” before the SCOPE variable.
Paste it and you will see the list of files from google drive.

There is an error of count function which is caused because of the different version of PHP.

I shall fix that later.

First, I shall make it run on browser by starting Apache server from XAMPP.

Hit the URL which ends with quickstart.php

It is not allowing to run it on browser so the comment those lines from file.

You will be able to see files list.

Go to the file where COUNT function is created.

Wrap it’s argument inside an array and now the error is gone.
Like if that works for you, any doubts, comment them down below.
In next video, I am going to upload files from local server to google drive, so make sure to subscribe if you want to.
Thanks for watching.

Wednesday, 23 February 2022

MYSQL Tutorial | Get Week Count Of Month Based On Date

 




Code :-
SELECT employee_id,hire_date, weekday(hire_date) as weekday_count,
WEEKDAY(concat(YEAR(hire_date),'-',MONTH(hire_date),'-01')) as first_day_of_month,
FLOOR((DAYOFMONTH(hire_date)-1 + WEEKDAY(concat(YEAR(hire_date),'-',MONTH(hire_date),'-01')))/7) + 1 as week_of_month
FROM `employees` order by hire_date desc limit 0,10
-------------------------------
MYSQL Tutorial | Get Week Count Of Month Based On Date
-------------------------------
Subscribe my Channel:- 
http://www.youtube.com/user/SanketRooney?sub_confirmation=1 

Facebook Page:- 
https://www.facebook.com/UnpossibleNS 

Twitter Account:- 
https://twitter.com/UnpossiblePOG 

Blog:- 
https://unpossiblepog.blogspot.com/ 

Website:- 
https://unpossiblepog.com/ 

Gaming Instagram:- (@unpog.gaming)
https://www.instagram.com/unpog.gaming/
-------------------------------
While I was experimenting with MYSQL queries, I wondered if I could get week of the month from a give date by using the MYSQL query rather than using backend languages like PHP & JAVA. So I created a query for it.
Here is the simple employees table with more than 200 thousand rows.
And it does have a column called “hire_date” with a data type as date.
What I am going to do is just copy-paste the query that I’ve created.
Of course, you can copy-paste the code from the link given in the description.
Please note that in my case, Monday as a first day and Sunday as a last day of the week.
From FLOOR to WEEK_OF_MONTH is the main formula which will give you exact week count.
Let’s check the output.
The 20th of September 2022 belongs in 4th week. 
The 11th of September 2022 represents 2nd week because it is the Sunday and also the last day of 2nd week. 
You can replace the table and column name with your preferred table and columns to verify it.
Thanks for watching. Like share and subscribe.

Thursday, 20 January 2022

JQUERY Validator | Move Error Messages Anywhere On Web Page

Code :-
-------------------------
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery validation plug-in - main demo</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script>  

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"> </script>  

<script>

$.validator.setDefaults({

submitHandler: function() {

alert("submitted!");

}

});



$().ready(function() {



$("#signupForm").validate({

rules: {

firstname: "required",

lastname: "required",

},

messages: {

firstname: "Please enter your firstname",

lastname: "Please enter your lastname",

}

});



});

</script>

<style>

.error{

color: red;  

}

.manual-error{

display: none;

}

#signupForm {

width: 670px;

}

</style>

</head>

<body>

<h1 id=""> Demo</h1>

<div id="main">

<form class="cmxform" id="signupForm" method="get" action="">

<fieldset>

<legend>Validating a form</legend>

<p>

<label for="firstname">Firstname</label>

<input id="firstname" name="firstname" type="text">

</p>

<p>

<label for="lastname">Lastname</label>

<input id="lastname" name="lastname" type="text">

</p>

<p>

<input class="submit" type="submit" value="Submit">

<br/>

<label id="firstname-error" class="error manual-error" for="firstname"></label>

<br/>

<label id="lastname-error" class="error manual-error" for="lastname"></label>

</p>

</fieldset>

</form>

</div>

</body>

</html>

-------------------------


JQUERY Validator | Move Error Messages Anywhere On Web Page

-------------------------------

Subscribe my Channel:- 

http://www.youtube.com/user/SanketRooney?sub_confirmation=1 




Facebook Page:- 

https://www.facebook.com/UnpossibleNS 




Twitter Account:- 

https://twitter.com/UnpossiblePOG 




Blog:- 

https://unpossiblepog.blogspot.com/ 




Website:- 

https://unpossiblepog.com/ 




Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

-------------------------------

What If I told you that the error messages from JQUERY VALIDATOR can be moved from here to below text field or right next to submit button.

So, here, I have a code which shows an error message.

Below text fields, add BR tag.

Right click on browser, go to inspect elements.

Copy the whole label tag which contains an error.

Paste it below the respective BR tag.

Remove the text inside it.

Add a manual class next to an error class.

Make it hidden by default by using style tag.

And, as you can see, the error is coming below.

You can move error tag anywhere, for example next to a submit button.

You can copy-paste the code from the link given in the description.

Thanks for watching. Like share and subscribe.



Sunday, 12 December 2021

Flutter : Send Data Through API Using DIO | GET & POST Methods On PHP API




Step 1 : Create a new FLUTTER project in ANDROID STUDIO.

-----------------------------

Step 2 : Copy the flutter code from below.

import 'package:flutter/material.dart';

import 'package:dio/dio.dart';

void main() {

  runApp(MyApp());

}

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Flutter Demo',

      theme: ThemeData(

        ),

      home: MyHomePage(title: 'Flutter Demo Home Page'),

    );

  }

}

class MyHomePage extends StatefulWidget {

  MyHomePage({Key key, this.title}) : super(key: key);

  

  final String title;

  @override

  _MyHomePageState createState() => _MyHomePageState();

}

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;

  FocusNode myFocusNode;

  @override

  void initState() {

    super.initState();

    myFocusNode = FocusNode();

  }

  @override

  void dispose() {

    

    myFocusNode.dispose();

    super.dispose();

  }

  void _incrementCounter() {

    setState(() {

      _counter++;

    });

  }

  var txt_1 = TextEditingController();

  var txt_2 = TextEditingController();

  @override

  Widget build(BuildContext context) {

    TextStyle textStyle = Theme.of(context).textTheme.title;

    

    return Scaffold(

      appBar: AppBar(

        title: Text(widget.title),

      ),

      body: Padding(

          padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),

          child: ListView(

              children: <Widget>[

                Padding(

                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),

                  child: TextField(

                    controller: txt_1,

                    focusNode: myFocusNode,

                    style: textStyle,

                    onChanged: (value) {

                      debugPrint('Something changed in Name Text Field');

                    },

                    decoration: InputDecoration(

                        labelText: 'Name',

                        labelStyle: textStyle,

                        border: OutlineInputBorder(

                            borderRadius: BorderRadius.circular(5.0)

                        )

                    ),

                  ),

                ),

                Padding(

                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),

                  child: TextField(

                    controller: txt_2,

                    style: textStyle,

                    keyboardType: TextInputType.number,

                    onChanged: (value) {

                      debugPrint('Something changed in Address Text Field');

                    },

                    decoration: InputDecoration(

                        labelText: 'Age',

                        labelStyle: textStyle,

                        border: OutlineInputBorder(

                            borderRadius: BorderRadius.circular(5.0)

                        )

                    ),

                  ),

                ),

                

              ]

          )

      ),

      floatingActionButton: FloatingActionButton(

        onPressed: (){

          getHttp();

        },

        tooltip: 'Increment',

        child: Icon(Icons.add),

      ),

    );

  }

  void getHttp() async {

    var formData = FormData.fromMap({

      'name': txt_1.text,

      'age': txt_2.text,

    });

    txt_1.text="";

    txt_2.text="";

    Response response = await Dio().post('http://192.168.56.1/flutter_test/store_data_flutter.php', data: formData);

    print(response.data.toString());

    myFocusNode.requestFocus();

  }

}

-----------------------------

Step 3 : Open pubspec.yaml file, inside the "dependencies" add 2 lines.

http: any

dio: any

-----------------------------

Step 4 : Click on "pub get" link which will appear on ANDROID STUDIO.

-----------------------------

Step 5 : Install XAMPP's latest version.

-----------------------------

Step 6 : Run XAMPP and start APACHE & MySQL.

-----------------------------

Step 7 : On any browser, on URL bar, hit http://127.0.0.1/phpmyadmin/ & create a new database “test”. Go to it’s SQL, in textarea, copy-paste the following query.

CREATE TABLE `flutter_data_check` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `post_data` text NOT NULL,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

-----------------------------

Step 8 : At the folder where the XAMPP is installed, go to “htdocs” folder and create a new folder called “flutter_test”.

-----------------------------

Step 9 : Create a new php file “store_data_flutter.php” and copy-paste the following code.

<?php

if(isset($_POST))

{

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "test";

$data_array=array();

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

//print_r($_POST);

$sql = "INSERT into flutter_data_check(post_data)

VALUES(

'".json_encode($_POST)."'

)

";

$conn->query($sql);

echo json_encode([array(

"new_id"=>$conn->insert_id,

    "title"=>$_POST)]);

}

?>

-----------------------------

Step 10 : Open the command prompt and enter "ipconfig" (to find out the IPv4 address for localhost). Make sure that it is same as  an IP address which is added on the left side of "/flutter_test/store_data_flutter.php". If not, then add the IP address from command prompt. And then run the project.

==================

 Flutter | POST the JSON Data Through API Using Dio | PHP as a Backend

-------------------------------

Install XAMPP Tutorial:-

https://www.youtube.com/watch?v=-f8N4FEQWyY


Download Project:-

https://unpossiblepog.com/projects/FLUTTER+JSON+PHP/Send-JSON-Data-To-API


Subscribe my Channel:- 

http://www.youtube.com/user/SanketRooney?sub_confirmation=1 


Facebook Page:- 

https://www.facebook.com/UnpossibleNS 


Twitter Account:- 

https://twitter.com/UnpossiblePOG 


Blog:- 

https://unpossiblepog.blogspot.com/ 


Website:- 

https://unpossiblepog.com/ 


Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

-------------------------------

In this tutorial, we shall create a project which can send data through API using GET & POST Methods.

We shall be using a PHP as a back-end language for the API and shall store the JSON in database.

We shall be referring a blog which contains steps to approach the task. Link of that blog is giving in the description.

First step is to create an empty Flutter project.

From 2nd step, copy-paste the whole code and paste it in main.dart file.

For 3rd step, open pubspec.yaml file and add those 2 lines under dependencies.

Make sure it is at the same level as flutter, then click on PUB GET to download important libraries.

We completed 4th point, and for the 5th point, we have to install XAMPP which will create a local domain in your computer. This will help us to create an API.

Link for XAMPP installation tutorial is given at the right-top-corner.

I already installed it so I am going to run it.

In 7th step, I shall  create a database table by copy-pasting the SQL query in PHPMYADMIN.

First create a database called “test”. Click on it, and click on SQL tab.

Paste the QUERY there and execute it.

In next step, we have to create a folder called “flutter_test” in htdocs folder and then create an empty PHP file in it. Give it a name as “store_data_flutter.php”

Open that file in any text-editor, and copy-paste the code from step 9.

At last, open a command prompt and type command IPCONFIG.

Search for IPv4.

Choose any one from IPv4 and make sure that it is same an IP in flutter code. If not, then replace IP address to the one shown in your command prompt.

In response, an API returns a JSON which is displayed in console.

And when we go back to phpmyadmin, and check the table data, you will see our entered data there.

To switch from POST to GET, change function name  to get. Also, in PHP code, change $_POST to $_GET.

You can download a whole project from my website.

A download link is given in the description.

Thanks for watching. Like share and subscribe.

Monday, 25 October 2021

External JS Changes Are Not Reflecting | Quick Fix | No Need Of Deleting Cookies & History | No Force Refresh Required


-------------------------------
Convert 
<script src="scripts.js"></script>

To
<script src="scripts.js?version=1"></script>
-------------------------------

Subscribe my Channel:- 
http://www.youtube.com/user/SanketRooney?sub_confirmation=1 

Facebook Page:- 
https://www.facebook.com/UnpossibleNS 

Twitter Account:- 
https://twitter.com/UnpossiblePOG 

Blog:- 
https://unpossiblepog.blogspot.com/ 

Website:- 
https://unpossiblepog.com/ 

Gaming Instagram:- (@unpog.gaming)
https://www.instagram.com/unpog.gaming/
-------------------------------
Have you found the problem where even if you make changes in external javascript file, and try to refresh the page, the older output remains there.
Of course you can force-refresh it or rename the javascript file, or delete cookies, but all of them don’t sound right or are time consuming.
So I have a simple solution for this.
In this example, I am demonstrating using the ANGULAR JS. But for other JS framework or for basic js implementation, the solution also works.
Here, the external JS file calls the data from JSON file and displays it on browser.
I am making changes in JSON file.
But as you can see, the change is not reflecting even after refreshing.
So to solve that, first go to the place where you linked that Javascript file.
Just add any random REQUEST variable after the filename by adding question mark.
And when you refresh the page, new changes will be reflected.
Next time, if the JS is not reflecting after deploy, just change the version number as shown on the screen.
Thanks for watching. Like share and subscribe.