Showing posts with label Bootstrap. Show all posts
Showing posts with label Bootstrap. Show all posts

Friday, 4 February 2022

Bootstrap 5 Select Dropdown with Search Box using Vanilla JavaScript PHP MySQL


This is one more post of Bootstrap 5 Library with pure JavaScript and under this post, we will show you how to add Search box filter in the Bootstrap 5 Select Dropdown box by using JavaScript. In this tutorial we will adding Search bar in Bootstrap 5 Select Dropdown box by using JavaScript. So with the help of this tutorial, you can able to make Search Searchable Select box in Bootstrap 5 by using JavaScript. So if you are looking for tutorial on How to Adding a Search Functionality in Bootstrap 5 Select Dropdown options by using Vanilla JavaScript. Here you can find the example of Bootstrap 5 Select Dropdown with Search and you can learn how to implement and customize the search filter in the Bootstrap 5 Select box.

In this post, we have not use any jQuery plugin for convert simple Bootstrap 5 dropdown to Advance dropdown with Search filter, but here we have use pure JavaScript dSelect library for make Select box with Search option in Bootstrap 5 library. This dselect JavaScript library is fully compatible with Bootstrap 5 library and with the help of this library, we can easily implement Search feature in Bootstrap 5 Select Dropdown. So after implementing Search filter in Bootstrap 5 select box, User can easily filter options by type keyword in search box.

Below you can find the complete source code of How to Create Bootstrap 5 Select Dropdown with Search Box by using JavaScript with PHP and MySQL Database.


Bootstrap 5 Select Dropdown with Search Box using Vanilla JavaScript PHP MySQL





Database


For create dynamic dropdown select box, first we need data. So for dynamic data, we have to run following .sql script in your database and this script will create apps_countries table with sample data in your local database.


--
-- Database: `testing`
--

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

--
-- Table structure for table `apps_countries`
--

CREATE TABLE `apps_countries` (
  `id` int(11) NOT NULL,
  `country_code` varchar(2) NOT NULL DEFAULT '',
  `country_name` varchar(100) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `apps_countries`
--

INSERT INTO `apps_countries` (`id`, `country_code`, `country_name`) VALUES
(1, 'AF', 'Afghanistan'),
(2, 'AL', 'Albania'),
(3, 'DZ', 'Algeria'),
(4, 'DS', 'American Samoa'),
(5, 'AD', 'Andorra'),
(6, 'AO', 'Angola'),
(7, 'AI', 'Anguilla'),
(8, 'AQ', 'Antarctica'),
(9, 'AG', 'Antigua and Barbuda'),
(10, 'AR', 'Argentina'),
(11, 'AM', 'Armenia'),
(12, 'AW', 'Aruba'),
(13, 'AU', 'Australia'),
(14, 'AT', 'Austria'),
(15, 'AZ', 'Azerbaijan'),
(16, 'BS', 'Bahamas'),
(17, 'BH', 'Bahrain'),
(18, 'BD', 'Bangladesh'),
(19, 'BB', 'Barbados'),
(20, 'BY', 'Belarus'),
(21, 'BE', 'Belgium'),
(22, 'BZ', 'Belize'),
(23, 'BJ', 'Benin'),
(24, 'BM', 'Bermuda'),
(25, 'BT', 'Bhutan'),
(26, 'BO', 'Bolivia'),
(27, 'BA', 'Bosnia and Herzegovina'),
(28, 'BW', 'Botswana'),
(29, 'BV', 'Bouvet Island'),
(30, 'BR', 'Brazil'),
(31, 'IO', 'British Indian Ocean Territory'),
(32, 'BN', 'Brunei Darussalam'),
(33, 'BG', 'Bulgaria'),
(34, 'BF', 'Burkina Faso'),
(35, 'BI', 'Burundi'),
(36, 'KH', 'Cambodia'),
(37, 'CM', 'Cameroon'),
(38, 'CA', 'Canada'),
(39, 'CV', 'Cape Verde'),
(40, 'KY', 'Cayman Islands'),
(41, 'CF', 'Central African Republic'),
(42, 'TD', 'Chad'),
(43, 'CL', 'Chile'),
(44, 'CN', 'China'),
(45, 'CX', 'Christmas Island'),
(46, 'CC', 'Cocos (Keeling) Islands'),
(47, 'CO', 'Colombia'),
(48, 'KM', 'Comoros'),
(49, 'CG', 'Congo'),
(50, 'CK', 'Cook Islands'),
(51, 'CR', 'Costa Rica'),
(52, 'HR', 'Croatia (Hrvatska)'),
(53, 'CU', 'Cuba'),
(54, 'CY', 'Cyprus'),
(55, 'CZ', 'Czech Republic'),
(56, 'DK', 'Denmark'),
(57, 'DJ', 'Djibouti'),
(58, 'DM', 'Dominica'),
(59, 'DO', 'Dominican Republic'),
(60, 'TP', 'East Timor'),
(61, 'EC', 'Ecuador'),
(62, 'EG', 'Egypt'),
(63, 'SV', 'El Salvador'),
(64, 'GQ', 'Equatorial Guinea'),
(65, 'ER', 'Eritrea'),
(66, 'EE', 'Estonia'),
(67, 'ET', 'Ethiopia'),
(68, 'FK', 'Falkland Islands (Malvinas)'),
(69, 'FO', 'Faroe Islands'),
(70, 'FJ', 'Fiji'),
(71, 'FI', 'Finland'),
(72, 'FR', 'France'),
(73, 'FX', 'France, Metropolitan'),
(74, 'GF', 'French Guiana'),
(75, 'PF', 'French Polynesia'),
(76, 'TF', 'French Southern Territories'),
(77, 'GA', 'Gabon'),
(78, 'GM', 'Gambia'),
(79, 'GE', 'Georgia'),
(80, 'DE', 'Germany'),
(81, 'GH', 'Ghana'),
(82, 'GI', 'Gibraltar'),
(83, 'GK', 'Guernsey'),
(84, 'GR', 'Greece'),
(85, 'GL', 'Greenland'),
(86, 'GD', 'Grenada'),
(87, 'GP', 'Guadeloupe'),
(88, 'GU', 'Guam'),
(89, 'GT', 'Guatemala'),
(90, 'GN', 'Guinea'),
(91, 'GW', 'Guinea-Bissau'),
(92, 'GY', 'Guyana'),
(93, 'HT', 'Haiti'),
(94, 'HM', 'Heard and Mc Donald Islands'),
(95, 'HN', 'Honduras'),
(96, 'HK', 'Hong Kong'),
(97, 'HU', 'Hungary'),
(98, 'IS', 'Iceland'),
(99, 'IN', 'India'),
(100, 'IM', 'Isle of Man'),
(101, 'ID', 'Indonesia'),
(102, 'IR', 'Iran (Islamic Republic of)'),
(103, 'IQ', 'Iraq'),
(104, 'IE', 'Ireland'),
(105, 'IL', 'Israel'),
(106, 'IT', 'Italy'),
(107, 'CI', 'Ivory Coast'),
(108, 'JE', 'Jersey'),
(109, 'JM', 'Jamaica'),
(110, 'JP', 'Japan'),
(111, 'JO', 'Jordan'),
(112, 'KZ', 'Kazakhstan'),
(113, 'KE', 'Kenya'),
(114, 'KI', 'Kiribati'),
(115, 'KP', 'Korea, Democratic People\'s Republic of'),
(116, 'KR', 'Korea, Republic of'),
(117, 'XK', 'Kosovo'),
(118, 'KW', 'Kuwait'),
(119, 'KG', 'Kyrgyzstan'),
(120, 'LA', 'Lao People\'s Democratic Republic'),
(121, 'LV', 'Latvia'),
(122, 'LB', 'Lebanon'),
(123, 'LS', 'Lesotho'),
(124, 'LR', 'Liberia'),
(125, 'LY', 'Libyan Arab Jamahiriya'),
(126, 'LI', 'Liechtenstein'),
(127, 'LT', 'Lithuania'),
(128, 'LU', 'Luxembourg'),
(129, 'MO', 'Macau'),
(130, 'MK', 'Macedonia'),
(131, 'MG', 'Madagascar'),
(132, 'MW', 'Malawi'),
(133, 'MY', 'Malaysia'),
(134, 'MV', 'Maldives'),
(135, 'ML', 'Mali'),
(136, 'MT', 'Malta'),
(137, 'MH', 'Marshall Islands'),
(138, 'MQ', 'Martinique'),
(139, 'MR', 'Mauritania'),
(140, 'MU', 'Mauritius'),
(141, 'TY', 'Mayotte'),
(142, 'MX', 'Mexico'),
(143, 'FM', 'Micronesia, Federated States of'),
(144, 'MD', 'Moldova, Republic of'),
(145, 'MC', 'Monaco'),
(146, 'MN', 'Mongolia'),
(147, 'ME', 'Montenegro'),
(148, 'MS', 'Montserrat'),
(149, 'MA', 'Morocco'),
(150, 'MZ', 'Mozambique'),
(151, 'MM', 'Myanmar'),
(152, 'NA', 'Namibia'),
(153, 'NR', 'Nauru'),
(154, 'NP', 'Nepal'),
(155, 'NL', 'Netherlands'),
(156, 'AN', 'Netherlands Antilles'),
(157, 'NC', 'New Caledonia'),
(158, 'NZ', 'New Zealand'),
(159, 'NI', 'Nicaragua'),
(160, 'NE', 'Niger'),
(161, 'NG', 'Nigeria'),
(162, 'NU', 'Niue'),
(163, 'NF', 'Norfolk Island'),
(164, 'MP', 'Northern Mariana Islands'),
(165, 'NO', 'Norway'),
(166, 'OM', 'Oman'),
(167, 'PK', 'Pakistan'),
(168, 'PW', 'Palau'),
(169, 'PS', 'Palestine'),
(170, 'PA', 'Panama'),
(171, 'PG', 'Papua New Guinea'),
(172, 'PY', 'Paraguay'),
(173, 'PE', 'Peru'),
(174, 'PH', 'Philippines'),
(175, 'PN', 'Pitcairn'),
(176, 'PL', 'Poland'),
(177, 'PT', 'Portugal'),
(178, 'PR', 'Puerto Rico'),
(179, 'QA', 'Qatar'),
(180, 'RE', 'Reunion'),
(181, 'RO', 'Romania'),
(182, 'RU', 'Russian Federation'),
(183, 'RW', 'Rwanda'),
(184, 'KN', 'Saint Kitts and Nevis'),
(185, 'LC', 'Saint Lucia'),
(186, 'VC', 'Saint Vincent and the Grenadines'),
(187, 'WS', 'Samoa'),
(188, 'SM', 'San Marino'),
(189, 'ST', 'Sao Tome and Principe'),
(190, 'SA', 'Saudi Arabia'),
(191, 'SN', 'Senegal'),
(192, 'RS', 'Serbia'),
(193, 'SC', 'Seychelles'),
(194, 'SL', 'Sierra Leone'),
(195, 'SG', 'Singapore'),
(196, 'SK', 'Slovakia'),
(197, 'SI', 'Slovenia'),
(198, 'SB', 'Solomon Islands'),
(199, 'SO', 'Somalia'),
(200, 'ZA', 'South Africa'),
(201, 'GS', 'South Georgia South Sandwich Islands'),
(202, 'ES', 'Spain'),
(203, 'LK', 'Sri Lanka'),
(204, 'SH', 'St. Helena'),
(205, 'PM', 'St. Pierre and Miquelon'),
(206, 'SD', 'Sudan'),
(207, 'SR', 'Suriname'),
(208, 'SJ', 'Svalbard and Jan Mayen Islands'),
(209, 'SZ', 'Swaziland'),
(210, 'SE', 'Sweden'),
(211, 'CH', 'Switzerland'),
(212, 'SY', 'Syrian Arab Republic'),
(213, 'TW', 'Taiwan'),
(214, 'TJ', 'Tajikistan'),
(215, 'TZ', 'Tanzania, United Republic of'),
(216, 'TH', 'Thailand'),
(217, 'TG', 'Togo'),
(218, 'TK', 'Tokelau'),
(219, 'TO', 'Tonga'),
(220, 'TT', 'Trinidad and Tobago'),
(221, 'TN', 'Tunisia'),
(222, 'TR', 'Turkey'),
(223, 'TM', 'Turkmenistan'),
(224, 'TC', 'Turks and Caicos Islands'),
(225, 'TV', 'Tuvalu'),
(226, 'UG', 'Uganda'),
(227, 'UA', 'Ukraine'),
(228, 'AE', 'United Arab Emirates'),
(229, 'GB', 'United Kingdom'),
(230, 'US', 'United States'),
(231, 'UM', 'United States minor outlying islands'),
(232, 'UY', 'Uruguay'),
(233, 'UZ', 'Uzbekistan'),
(234, 'VU', 'Vanuatu'),
(235, 'VA', 'Vatican City State'),
(236, 'VE', 'Venezuela'),
(237, 'VN', 'Vietnam'),
(238, 'VG', 'Virgin Islands (British)'),
(239, 'VI', 'Virgin Islands (U.S.)'),
(240, 'WF', 'Wallis and Futuna Islands'),
(241, 'EH', 'Western Sahara'),
(242, 'YE', 'Yemen'),
(243, 'ZR', 'Zaire'),
(244, 'ZM', 'Zambia'),
(245, 'ZW', 'Zimbabwe');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `apps_countries`
--
ALTER TABLE `apps_countries`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `apps_countries`
--
ALTER TABLE `apps_countries`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=246;





index.php


In this file, first we have need to include Bootstrap 5 library link and dselect library link at the header of this web page. This both file you can find with the source code of this tutorial.

After this, we have to create one HTML Select box and for fill this select box with dynamic data, here we have to write PHP script for fetch data from apps_countries table and fill this select box with dynamic data.

And next we want to initialize dselect library, so by using dselect() method it will initialize dselect library and for add search filter, we have to add search option with true value, so after adding this library it will make Bootstrap 5 Select Dropdown with Search box.


<?php 

//index.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$query = "
    SELECT country_name FROM apps_countries 
    ORDER BY country_name ASC
";

$result = $connect->query($query);



?>

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="library/bootstrap-5/bootstrap.min.css" rel="stylesheet" />
        <script src="library/bootstrap-5/bootstrap.bundle.min.js"></script>
        <script src="library/dselect.js"></script>

        <title>Bootstrap 5 Select Dropdown with Search Box using JavaScript with PHP</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-2 mb-3 text-center text-primary">Bootstrap 5 Select Dropdown with Search Box using JavaScript with PHP</h1>
            <div class="row">
                <div class="col-md-3">&nbsp;</div>
                <div class="col-md-6">
                    <select name="select_box" class="form-select" id="select_box">
                        <option value="">Select Country</option>
                        <?php 
                        foreach($result as $row)
                        {
                            echo '<option value="'.$row["country_name"].'">'.$row["country_name"].'</option>';
                        }
                        ?>  
                    </select>
                </div>
                <div class="col-md-3">&nbsp;</div>
            </div>      
            <br />
            <br />
        </div>
    </body>
</html>

<script>

    var select_box_element = document.querySelector('#select_box');

    dselect(select_box_element, {
        search: true
    });

</script>


So after follow above source code you can able to add Search box filter in Bootstrap 5 Select dropdown box by using JavaScript with PHP and MySQL Database. Below you can find source code link and online demo of this tutorial. So in source code you can get the complete source code with required files also and by click on demo link you can also check live demo of this Bootstrap 5 Select dropdown with Search filter.





Wednesday, 31 March 2021

Toast Notification for Check Internet Connection with Bootstrap 4 & javascript


In this post, you will learn how to make a Toast Notification for Detect Internet Connection status using javascript, HTML and Bootstrap 4 Toast component. In this tutorial, we will use javascript and Bootstrap 4 library for display internet connection status. In web development display of push notification regarding Internet connection status feature is very useful, because in this middle of surfing website and suddenly internet connection lost, then at that time this push toast notification is very effective for display of internet connection status on web page.

Under this Toast Notification for check Internet connection status post, and under this we page, we will write light weight javascript code with Bootstrap 4 Toast component. So based on Internet connection status like online or offline then it will change its icon, text color and text according to status of internet connection. Here we have use Bootstrap 4 Toast component, so this component has some build in animation, so when internet connection status changes then it will display push toast notification at right side top of the web page, so user can see internet connection has lost or not.

For build this detection of Internet connection under this post, we have use simple javascript navigator.onLine code, This code has return true if internet connection is online and if it return false that means internet connection is offline. So based on this value toast notification icon, text and color will be change and it will display pust toast notification on web page. This push notification will display on web page, when internet connection status will be change. For implement this feature in your web application, you have to copy below code in your web based application and you can implement this how to display internet connection status on web page by using push notification which has been build with javascript and Bootstrap 4 Toast component.

Toast Notification for Check Internet Connection with Bootstrap 4 & javascript





Source Code






<!DOCTYPE html>
<html>
  	<head>
    	<title>Toast Notification for Check Internet Connection with Bootstrap 4 & javascript</title>
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
      	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  		<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
  	</head>
  	<body>
  		<div class="container">
  			<br />
  			<br />
    		<h1 align="center">Toast Notification for Check Internet Connection with Bootstrap 4 & javascript</h1>
    		<br />    		
    	</div>
    	
  	</body>
</html>

<div class="toast" style="position: absolute; top: 25px; right: 25px;">
    <div class="toast-header">
        <i class="bi bi-wifi"></i>&nbsp;&nbsp;&nbsp;
        <strong class="mr-auto"><span class="text-success">You're online now</span></strong>
        <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="toast-body">
        Hurray! Internet is connected.
    </div>
</div>

<script>

var status = 'online';
var current_status = 'online';

function check_internet_connection()
{
    if(navigator.onLine)
    {
        status = 'online';
    }
    else
    {
        status = 'offline';
    }

    if(current_status != status)
    {
        if(status == 'online')
        {
            $('i.bi').addClass('bi-wifi');
            $('i.bi').removeClass('bi-wifi-off');
            $('.mr-auto').html("<span class='text-success'>You are online now</span>");
            $('.toast-body').text('Hurray! Internet is connected.');
        }
        else
        {
            $('i.bi').addClass('bi-wifi-off');
            $('i.bi').removeClass('bi-wifi');
            $('.mr-auto').html("<span class='text-danger'>You are offline now</span>");
            $('.toast-body').text('Opps! Internet is disconnected.')
        }

        current_status = status;

        $('.toast').toast({
            autohide:false
        });

        $('.toast').toast('show');
    }
}

check_internet_connection();

setInterval(function(){
    check_internet_connection();
}, 1000);

</script>

Friday, 24 July 2020

Make Social Networking Sites in PHP Mysql using Ajax

Make Social Networking Sites in PHP Mysql using Ajax


Hi, Are you looking for tutorial on How to build a social network websites from scratch by using PHP language with Mysql Database & Ajax, then you have land on right place because here we are going to learn How to make social social networking sites in PHP with Mysql database and Ajax jQuery. On the web most of the social networking sites like twitter, Facebook are made with PHP language. For this we are also want to make one tutorial on creating social networking websites in PHP.

Due to Social networking sites we have seen it has changed the lifestyles of millions of people on earth. Most of the person have been stay online with their favorite social networking sites like Facebook, Twitter, YouTube LinkedIn etc with different devices like Desktop computer, Laptop, Tablet or even with Mobile phone. So, we have to build Social Networking sites that can be easily open any web devices which can access internet. We have seen most of the Social networking sites have been do process on web page that means if we have share something on social networking sites then it has been process our data without refresh of web page, because most of the social networking sites have been used Ajax jQuery and CSS3 for front end operation and it has been increase user experience. Now in your mind how Ajax increase user experience of your websites, then suppose user has upload their profile picture then image will be uploaded without refresh of web page. So without refresh whole page data it will upload image on server and it will increase feel of each web page of social networking sites.

This tutorial we have mainly made for PHP learner who want to learn how can we building a social networking sites in PHP language. Even final student who want to search project idea about their project then they can also use this tutorial for their college purpose also. This is because here they can get complete step by step guide for how to build social network website from scratch in PHP using Mysql database. Here they can also get complete source code with every module video tutorial also.

In this tutorial, for login and signup feature, we have use complete source code of our previous tutorial on how to make User Login and Registration system with email verification by using OTP method in PHP. So if you not seen that tutorial, so first check that tutorial for login and signup module, because in this tutorial we will not cover again login and sign up process. So for Login and Registration process you have to follow our previous tutorial.




Features


  1. User can sign up with Email Verification using OTP
  2. User can resend Email Verification Email
  3. User can Login using OTP Authentication
  4. User can Reset Password using OTP Method
  5. User Initial Avatar Generate
  6. User can edit Profile data
  7. AutoComplete Friends Search Box
  8. Display Friends Search using Ajax with Pagination
  9. User can send Friend request
  10. Restrict User to send Multiple Friend Request to single User
  11. Display Number of Unseen Friend Request Notification at the header
  12. Load Friends Request Notification at Header notification tab
  13. Remove Friends Request Notification Alert
  14. Accept Friend Request
  15. List Friends on web page
  16. Add Search Filter in Friends List
  17. Share Simple Text Post
  18. Fetch Content from URL Like Facebook while sharing of Post
  19. Facebook Style Upload multiple image with Thumbnail Generation
  20. Load Uploaded Multiple Images in Facebook style Photo Grid Layout

Software Requirement


Front End


  1. Ajax Technology
  2. jQuery Library
  3. Bootstrap Library
  4. Javascript
  5. Bootstrap DatePicker Plugin
  6. CSS3
  7. HTML 5

Back-end


  1. PHP 5.6
  2. Mysql Database
  3. PHP PDO Extension




Mysql Database


First you have to create one database in your local PHPMyAdmin and then after you have to run following sql script for create initial table for this social networking sites. This is only initial table, we will add another table after creating video tutorial on that topic. So on every publish of tutorial you have to check this mysql database section also for new table or new field in table.


--
-- Database: `testing`
--

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

--
-- Table structure for table `login_data`
--

CREATE TABLE `login_data` (
  `login_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `login_otp` int(6) NOT NULL,
  `last_activity` datetime NOT NULL,
  `login_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- Table structure for table `register_user`
--

CREATE TABLE `register_user` (
  `register_user_id` int(11) NOT NULL,
  `user_name` varchar(250) NOT NULL,
  `user_email` varchar(250) NOT NULL,
  `user_password` varchar(250) NOT NULL,
  `user_activation_code` varchar(250) NOT NULL,
  `user_email_status` enum('not verified','verified') NOT NULL,
  `user_otp` int(11) NOT NULL,
  `user_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `user_avatar` varchar(100) NOT NULL,
  `user_birthdate` date NOT NULL,
  `user_gender` enum('Male','Female') NOT NULL,
  `user_address` text NOT NULL,
  `user_city` varchar(250) NOT NULL,
  `user_zipcode` varchar(30) NOT NULL,
  `user_state` varchar(250) NOT NULL,
  `user_country` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `login_data`
--
ALTER TABLE `login_data`
  ADD PRIMARY KEY (`login_id`);

--
-- Indexes for table `register_user`
--
ALTER TABLE `register_user`
  ADD PRIMARY KEY (`register_user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `login_data`
--
ALTER TABLE `login_data`
  MODIFY `login_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;

--
-- AUTO_INCREMENT for table `register_user`
--
ALTER TABLE `register_user`
  MODIFY `register_user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;
  
--
-- Table structure for table `friend_request`
--

CREATE TABLE `friend_request` (
  `request_id` int(11) NOT NULL,
  `request_from_id` int(11) NOT NULL,
  `request_to_id` int(11) NOT NULL,
  `request_status` enum('Pending','Confirm','Reject') NOT NULL,
  `request_notification_status` enum('No','Yes') NOT NULL,
  `request_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `friend_request`
--
ALTER TABLE `friend_request`
  ADD PRIMARY KEY (`request_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `friend_request`
--
ALTER TABLE `friend_request`
  MODIFY `request_id` int(11) NOT NULL AUTO_INCREMENT;
  
--
-- Table structure for table `posts_table`
--

CREATE TABLE `posts_table` (
  `posts_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `post_content` text NOT NULL,
  `post_code` varchar(100) NOT NULL,
  `post_datetime` datetime NOT NULL
  `post_status` enum('Publish', 'Draft') NOT NULL
  `post_type` enum('Text', 'Media') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `posts_table`
--
ALTER TABLE `posts_table`
  ADD PRIMARY KEY (`posts_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `posts_table`
--
ALTER TABLE `posts_table`
  MODIFY `posts_id` int(11) NOT NULL AUTO_INCREMENT;
  
--
-- Table structure for table `media_table`
--

CREATE TABLE `media_table` (
  `media_id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `media_path` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `media_table`
--
ALTER TABLE `media_table`
  ADD PRIMARY KEY (`media_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `media_table`
--
ALTER TABLE `media_table`
  MODIFY `media_id` int(11) NOT NULL AUTO_INCREMENT;









Source Code


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


index.php



<?php

//index.php

//error_reporting(E_ALL);

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

include('function.php');

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

$message = '';
$error_user_name = '';
$error_user_email = '';
$error_user_password = '';
$user_name = '';
$user_email = '';
$user_password = '';

if(isset($_POST["register"]))
{
 if(empty($_POST["user_name"]))
 {
  $error_user_name = "<label class='text-danger'>Enter Name</label>";
 }
 else
 {
  $user_name = trim($_POST["user_name"]);
  $user_name = htmlentities($user_name);
 }

 if(empty($_POST["user_email"]))
 {
  $error_user_email = '<label class="text-danger">Enter Email Address</label>';
 }
 else
 {
  $user_email = trim($_POST["user_email"]);
  if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
  {
   $error_user_email = '<label class="text-danger">Enter Valid Email Address</label>';
  }
 }

 if(empty($_POST["user_password"]))
 {
  $error_user_password = '<label class="text-danger">Enter Password</label>';
 }
 else
 {
  $user_password = trim($_POST["user_password"]);
  $user_password = password_hash($user_password, PASSWORD_DEFAULT);
 }

 if($error_user_name == '' && $error_user_email == '' && $error_user_password == '')
 {
  $user_activation_code = md5(rand());

  $user_otp = rand(100000, 999999);

  $data = array(
   ':user_name'  => $user_name,
   ':user_email'  => $user_email,
   ':user_password' => $user_password,
   ':user_activation_code' => $user_activation_code,
   ':user_email_status'=> 'not verified',
   ':user_otp'   => $user_otp
  );

  $query = "
  INSERT INTO register_user 
  (user_name, user_email, user_password, user_activation_code, user_email_status, user_otp)
  SELECT * FROM (SELECT :user_name, :user_email, :user_password, :user_activation_code, :user_email_status, :user_otp) AS tmp
  WHERE NOT EXISTS (
      SELECT user_email FROM register_user WHERE user_email = :user_email
  ) LIMIT 1
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($connect->lastInsertId() == 0)
  {
   $message = '<label class="text-danger">Email Already Register</label>';
  } 
  else
  {
   $user_avatar = make_avatar(strtoupper($user_name[0]));

   $query = "
   UPDATE register_user 
   SET user_avatar = '".$user_avatar."' 
   WHERE register_user_id = '".$connect->lastInsertId()."'
   ";

   $statement = $connect->prepare($query);

   $statement->execute();

   //print_r(error_get_last());
   
   //echo ("hi");


   require 'class/class.phpmailer.php';
   $mail = new PHPMailer;
   $mail->IsSMTP();
   $mail->Host = 'smtpout.secureserver.net';
   $mail->Port = '80';
   $mail->SMTPAuth = true;
   $mail->Username = 'xxxxx';
   $mail->Password = 'xxxxx';
   $mail->SMTPSecure = '';
   $mail->From = 'tutorial@webslesson.info';
   $mail->FromName = 'Webslesson';
   $mail->AddAddress($user_email);
   $mail->WordWrap = 50;
   $mail->IsHTML(true);
   $mail->Subject = 'Verification code for Verify Your Email Address';

   $message_body = '
   <p>For verify your email address, enter this verification code when prompted: <b>'.$user_otp.'</b>.</p>
   <p>Sincerely,</p>
   <p>Webslesson.info</p>
   ';
   $mail->Body = $message_body;

   if($mail->Send())
   {
    echo '<script>alert("Please Check Your Email for Verification Code")</script>';

    header('location:email_verify.php?code='.$user_activation_code);
   }
   else
   {
    $message = $mail->ErrorInfo;
   }
  }

 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Resend Email Verification OTP in PHP Registration</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Resend Email Verification OTP in PHP Registration</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Registration</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Name</label>
       <input type="text" name="user_name" class="form-control" />
       <?php echo $error_user_name; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="user_email" class="form-control" />
       <?php echo $error_user_email; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Password</label>
       <input type="password" name="user_password" class="form-control" />
       <?php echo $error_user_password; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-success" value="Click to Register" />&nbsp;&nbsp;&nbsp;
       <a href="resend_email_otp.php" class="btn btn-default">Resend OTP</a>
       &nbsp;&nbsp;&nbsp;
       <a href="login.php">Login</a>
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>





email_verify.php



<?php

//email_verify.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$error_user_otp = '';
$user_activation_code = '';
$message = '';

if(isset($_GET["code"]))
{
 $user_activation_code = $_GET["code"];

 if(isset($_POST["submit"]))
 {
  if(empty($_POST["user_otp"]))
  {
   $error_user_otp = 'Enter OTP Number';
  }
  else
  {
   $query = "
   SELECT * FROM register_user 
   WHERE user_activation_code = '".$user_activation_code."' 
   AND user_otp = '".trim($_POST["user_otp"])."'
   ";

   $statement = $connect->prepare($query);

   $statement->execute();

   $total_row = $statement->rowCount();

   if($total_row > 0)
   {
    $query = "
    UPDATE register_user 
    SET user_email_status = 'verified' 
    WHERE user_activation_code = '".$user_activation_code."'
    ";

    $statement = $connect->prepare($query);

    if($statement->execute())
    {
     header('location:login.php?register=success');
    }
   }
   else
   {
    $message = '<label class="text-danger">Invalid OTP Number</label>';
   }
  }
 }
}
else
{
 $message = '<label class="text-danger">Invalid Url</label>';
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Resend Email Verification OTP in PHP Registration</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Resend Email Verification OTP in PHP Registration</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Enter OTP Number</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="POST">
      <div class="form-group">
       <label>Enter OTP Number</label>
       <input type="text" name="user_otp" class="form-control" />
       <?php echo $error_user_otp; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-success" value="Submit" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


login.php



<?php

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Login with OTP Authentication</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">How to Make Initial Avatar Image in PHP After Registration</h3>
   <br />

   <?php
   if(isset($_GET["register"]))
   {
    if($_GET["register"] == 'success')
    {
     echo '
     <h1 class="text-success">Email Successfully verified, Registration Process Completed...</h1>
     ';
    }
   }

   if(isset($_GET["reset_password"]))
   {
    if($_GET["reset_password"] == 'success')
    {
     echo '<h1 class="text-success">Password change Successfully, Now you can login with your new password</h1>';
    }
   }
   ?>

   <div class="row">
    <div class="col-md-3">&nbsp;</div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Login</h3>
      </div>
      <div class="panel-body">
       <form method="POST" id="login_form">
        <div class="form-group" id="email_area">
         <label>Enter Email Address</label>
         <input type="text" name="user_email" id="user_email" class="form-control" />
         <span id="user_email_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="password_area" style="display:none;">
         <label>Enter password</label>
         <input type="password" name="user_password" id="user_password" class="form-control" />
         <span id="user_password_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="otp_area" style="display:none;">
         <label>Enter OTP Number</label>
         <input type="text" name="user_otp" id="user_otp" class="form-control" />
         <span id="user_otp_error" class="text-danger"></span>
        </div>
        <div class="form-group" align="right">
         <input type="hidden" name="action" id="action" value="email" />
         <input type="submit" name="next" id="next" class="btn btn-primary" value="Next" />
        </div>
       </form>
      </div>
     </div>
     <div align="center">
      <b><a href="forget_password.php?step1=1">Forgot Password</a></b>
     </div>
    </div>
   </div>
   
  </div>
  <br />
  <br />
 </body>
</html>

<script>

$(document).ready(function(){
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  var action = $('#action').val();
  $.ajax({
   url:"login_verify.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#next').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#next').attr('disabled', false);
    if(action == 'email')
    {
     if(data.error != '')
     {
      $('#user_email_error').text(data.error);
     }
     else
     {
      $('#user_email_error').text('');
      $('#email_area').css('display', 'none');
      $('#password_area').css('display', 'block');
     }
    }
    else if(action == 'password')
    {
     if(data.error != '')
     {
      $('#user_password_error').text(data.error);
     }
     else
     {
      $('#user_password_error').text('');
      $('#password_area').css('display', 'none');
      $('#otp_area').css('display', 'block');
     }
    }
    else
    {
     if(data.error != '')
     {
      $('#user_otp_error').text(data.error);
     }
     else
     {
      window.location.replace("home.php");
     }
    }

    $('#action').val(data.next_action);
   }
  })
 });
});

</script>


login_verify.php



<?php

//login_verify.php



$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

session_start();

$error = '';

$next_action = '';

sleep(2);

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'email')
 {
  if($_POST["user_email"] != '')
  {
   $data = array(
    ':user_email' => $_POST["user_email"]
   );

   $query = "
   SELECT * FROM register_user 
   WHERE user_email = :user_email
   ";

   $statement = $connect->prepare($query);

   $statement->execute($data);

   $total_row = $statement->rowCount();

   if($total_row == 0)
   {
    $error = 'Email Address not found';
    $next_action = 'email';
   }
   else
   {
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
     if($row["user_email_status"] == 'verified')
     {
      $_SESSION['register_user_id'] = $row['register_user_id'];
      $_SESSION['user_name'] = $row['user_name'];
      $_SESSION['user_email'] = $row['user_email'];
      $_SESSION['user_password'] = $row['user_password'];
      $next_action = 'password';
     }
     else
     {
      $error = 'Email Address is not verified, first verify your email address';
      $next_action = 'email';
     }
    }    
   }
  }
  else
  {
   $error = 'Email Address is Required';

   $next_action = 'email';
  }
 }

 if($_POST["action"] == 'password')
 {
  if($_POST["user_password"] != '')
  {
   if(password_verify($_POST["user_password"], $_SESSION["user_password"]))
   {
    $login_otp = rand(100000,999999);

    $data = array(
     ':user_id'  => $_SESSION["register_user_id"],
     ':login_otp' => $login_otp,
     ':last_activity'=> date('d-m-y h:i:s')
    );

    $query = "
    INSERT INTO login_data 
    (user_id, login_otp, last_activity) 
    VALUES (:user_id, :login_otp, :last_activity)
    ";

    $statement = $connect->prepare($query);

    if($statement->execute($data))
    {
     $_SESSION['login_id'] = $connect->lastInsertId();
     $_SESSION['login_otp'] = $login_otp;

     require 'class/class.phpmailer.php';

     $mail = new PHPMailer;

     $mail->IsSMTP();

     $mail->Host = 'smtpout.secureserver.net';

     $mail->Port = '80';

     $mail->SMTPAuth = true;

     $mail->Username = 'xxxxxxxxx';
     $mail->Password = 'xxxxxxxxx';

     $mail->SMTPSecure = '';

     $mail->From = 'tutorial@webslesson.info';

     $mail->FromName = 'Webslesson';

     $mail->AddAddress($_SESSION["user_email"]);

     $mail->WordWrap = 50;

     $mail->IsHTML(true);

     $mail->Subject = 'Verification code for Login';

     $message_body = '
     <p>For verify your login details, enter this verification code when prompted: <b>'.$login_otp.'</b>.</p>
     <p>Sincerely,</p>
     <p>Webslesson.info</p>
     ';

     $mail->Body = $message_body;

     if($mail->Send())
     {
      $next_action = 'otp';
     }
     else
     {
      $error = '<label class="text-danger">'.$mail->ErrorInfo.'</label>';
      $next_action = 'password';
     }
    }
   }
   else
   {
    $error = 'Wrong Password';
    $next_action = 'password';
   }
  }
  else
  {
   $error = 'Password is Required';
   $next_action = 'password';
  }
 }

 if($_POST["action"] == "otp")
 {
  if($_POST["user_otp"] != '')
  {
   if($_SESSION['login_otp'] == $_POST["user_otp"])
   {
    $_SESSION['user_id'] = $_SESSION['register_user_id'];
    unset($_SESSION["register_user_id"]);
    unset($_SESSION["user_email"]);
    unset($_SESSION["user_password"]);
    unset($_SESSION["login_otp"]);
   }
   else
   {
    $error = 'Wrong OTP Number';
    $next_action = 'otp';
   }
  }
  else
  {
   $error = 'OTP Number is required';
   $next_action = 'otp';
  }
 }





 $output = array(
  'error'   => $error,
  'next_action' => $next_action
 );

 echo json_encode($output);
}


?>


logout.php



<?php

//logout.php

session_start();

session_destroy();

header("location:login.php");

?>


resend_email_otp.php



<?php

//resend_email_otp.php

include('database_connection.php');

$message = '';

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

if(isset($_POST["resend"]))
{
 if(empty($_POST["user_email"]))
 {
  $message = '<div class="alert alert-danger">Email Address is required</div>';
 }
 else
 {
  $data = array(
   ':user_email' => trim($_POST["user_email"])
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_email = :user_email
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if($row["user_email_status"] == 'verified')
    {
     $message = '<div class="alert alert-info">Email Address already verified, you can login into system</div>';
    }
    else
    {
     require 'class/class.phpmailer.php';
     $mail = new PHPMailer;
     $mail->IsSMTP();
     $mail->Host = 'smtpout.secureserver.net';
     $mail->Port = '80';
     $mail->SMTPAuth = true;
     $mail->Username = 'xxxxxxx';
     $mail->Password = 'xxxxxxx';
     $mail->SMTPSecure = '';
     $mail->From = 'tutorial@webslesson.info';
     $mail->FromName = 'Webslesson';
     $mail->AddAddress($row["user_email"]);
     $mail->WordWrap = 50;
     $mail->IsHTML(true);
     $mail->Subject = 'Verification code for Verify Your Email Address';
     $message_body = '
     <p>For verify your email address, enter this verification code when prompted: <b>'.$row["user_otp"].'</b>.</p>
     <p>Sincerely,</p>
     ';
     $mail->Body = $message_body;

     if($mail->Send())
     {
      echo '<script>alert("Please Check Your Email for Verification Code")</script>';
      echo '<script>window.location.replace("email_verify.php?code='.$row["user_activation_code"].'");</script>';
     }
     else
     {

     }
    }
   }
  }
  else
  {
   $message = '<div class="alert alert-danger">Email Address not found in our record</div>';
  }
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Resend Email Verification OTP in PHP Registration</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Resend Email Verification OTP in PHP Registration</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Resend Email Verification OTP</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="email" name="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="resend" class="btn btn-success" value="Send" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>





forget_password.php



<?php

//forget_password.php

include('database_connection.php');

$message = '';

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

if(isset($_POST["submit"]))
{
 if(empty($_POST["user_email"]))
 {
  $message = '<div class="alert alert-danger">Email Address is required</div>';
 }
 else
 {
  $data = array(
   ':user_email' => trim($_POST["user_email"])
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_email = :user_email
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   $result = $statement->fetchAll();

   foreach($result as $row)
   {
    if($row["user_email_status"] == 'not verified')
    {
     $message = '<div class="alert alert-info">Your Email Address is not verify, so first verify your email address by click on this <a href="resend_email_otp.php">link</a></div>';
    }
    else
    {
     $user_otp = rand(100000, 999999);

     $sub_query = "
     UPDATE register_user 
     SET user_otp = '".$user_otp."' 
     WHERE register_user_id = '".$row["register_user_id"]."'
     ";

     $connect->query($sub_query);

     require 'class/class.phpmailer.php';

     $mail = new PHPMailer;

     $mail->IsSMTP();

     $mail->Host = 'smtpout.secureserver.net';

     $mail->Port = '80';

     $mail->SMTPAuth = true;

     $mail->Username = 'tutorial@webslesson.info';

     $mail->Password = 'password';

     $mail->SMTPSecure = '';

     $mail->From = 'tutorial@webslesson.info';

     $mail->FromName = 'Webslesson';

     $mail->AddAddress($row["user_email"]);

     $mail->IsHTML(true);

     $mail->Subject = 'Password reset request for your account';

     $message_body = '
     <p>For reset your password, you have to enter this verification code when prompted: <b>'.$user_otp.'</b>.</p>
     <p>Sincerely,</p>
     ';

     $mail->Body = $message_body;

     if($mail->Send())
     {
      echo '<script>alert("Please Check Your Email for password reset code")</script>';

      echo '<script>window.location.replace("forget_password.php?step2=1&code=' . $row["user_activation_code"] . '")</script>';
     }
    }
   }
  }
  else
  {
   $message = '<div class="alert alert-danger">Email Address not found in our record</div>';
  }
 }
}

if(isset($_POST["check_otp"]))
{
 if(empty($_POST["user_otp"]))
 {
  $message = '<div class="alert alert-danger">Enter OTP Number</div>';
 }
 else
 {
  $data = array(
   ':user_activation_code'  => $_POST["user_code"],
   ':user_otp'     => $_POST["user_otp"]
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_activation_code = :user_activation_code 
  AND user_otp = :user_otp
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   echo '<script>window.location.replace("forget_password.php?step3=1&code=' . $_POST["user_code"] . '")</script>';
  }
  else
  {
   $message = '<div class="alert alert-danger">Wrong OTP Number</div>';
  }
 }
}

if(isset($_POST["change_password"]))
{
 $new_password = $_POST["user_password"];
 $confirm_password = $_POST["confirm_password"];

 if($new_password == $confirm_password)
 {
  $query = "
  UPDATE register_user 
  SET user_password = '".password_hash($new_password, PASSWORD_DEFAULT)."' 
  WHERE user_activation_code = '".$_POST["user_code"]."'
  ";

  $connect->query($query);

  echo '<script>window.location.replace("login.php?reset_password=success")</script>';
 }
 else
 {
  $message = '<div class="alert alert-danger">Confirm Password is not match</div>';
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Forgot Password script in PHP using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Forgot Password script in PHP using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Forgot Password script in PHP using OTP</h3>
    </div>
    <div class="panel-body">
     <?php

     echo $message;

     if(isset($_GET["step1"]))
     {
     ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-success" value="Send" />
      </div>
     </form>
     <?php
     }
     if(isset($_GET["step2"], $_GET["code"]))
     {
     ?>
     <form method="POST">
      <div class="form-group">
       <label>Enter OTP Number</label>
       <input type="text" name="user_otp" class="form-control" />
      </div>
      <div class="form-group">
       <input type="hidden" name="user_code" value="<?php echo $_GET["code"]; ?>" />
       <input type="submit" name="check_otp" class="btn btn-success" value="Send" />
      </div>
     </form>
     <?php
     }

     if(isset($_GET["step3"], $_GET["code"]))
     {
     ?>
     <form method="post">
      <div class="form-group">
       <label>Enter New Password</label>
       <input type="password" name="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Confirm Password</label>
       <input type="password" name="confirm_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="hidden" name="user_code" value="<?php echo $_GET["code"]; ?>" />
       <input type="submit" name="change_password" class="btn btn-success" value="Change" />
      </div>
     </form>
     <?php 
     }
     ?>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


header.php



<?php

//header.php

session_start();

if(!isset($_SESSION["user_id"]))
{
	header('location:login.php');
}

include('database_connection.php');

include('function.php');


if(isset($_POST["searchBtn"]))
{
	$search_query = preg_replace("#[^a-z 0-9?!]#i", "", $_POST["searchbar"]);

	header('location:search.php?query='.urlencode($search_query).'');
}


?>
<!DOCTYPE html>
<html>
	<head>
		<title>Make Social Network System in PHP Mysql using Ajax jQuery</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<!--<script src="asset/js/jquery.js"></script>!-->
		<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    	<script src="asset/js/bootstrap.min.js"></script>
    	<link rel="stylesheet" href="asset/css/bootstrap.min.css">
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    	
    	<script src="asset/js/bootstrap-datepicker.js"></script>
    	<script src="asset/js/bootstrap-datepicker.en-GB.min.js"></script>
    	<link rel="stylesheet" href="asset/css/bootstrap-datepicker.css">
    	<link rel="stylesheet" href="asset/css/images-grid.css">
    	<script src="asset/js/images-grid.js"></script>
    	<style>

    		.wrapper-preview
    		{
    			padding: 50px;
			    background: #fff;
			    box-shadow: 0 1px 4px rgba(0,0,0,.25);
			    border-radius: 10px;
			    text-align:center;
    		}

    		.wrapper-box
    		{
    			padding: 20px;
			    margin-bottom: 20px;
			    background: #fff;
			    box-shadow: 0 1px 4px rgba(0,0,0,.25);
			    border-radius: 10px;
    		}

    		.wrapper-box-title
    		{
    			font-size: 20px;
			    line-height: 100%;
			    color: #000;
			    padding-bottom: 8px;
    		}

    		.wrapper-box-description
    		{
    			font-size: 14px;
			    line-height: 120%;
			    color: #000;
    		}

    		#friend_request_list li
    		{
    			padding:10px 12px;
    			border-bottom: 1px solid #eee;
    		}

    		.nopadding {
			   padding: 0 !important;
			   margin: 0 !important;
			}

    	</style>
	</head>
	<body vlink="#385898" alink="#385898" style="background-color: #f5f6fa">
		<nav class="navbar navbar-default">
		  	<div class="container-fluid">
			    <div class="navbar-header">
			      	<a class="navbar-brand" href="home.php">Webslesson</a>
			    </div>
			    
			    <form class="navbar-form navbar-left" method="post">
			    	<div class="input-group">
			    		<input type="text" class="form-control" id="searchbar" name="searchbar" placeholder="Search" autocomplete="off" />
			    		<div class="input-group-btn">
			    			<button class="btn btn-default" type="submit" name="searchBtn" id="searchBtn">
			    				<i class="glyphicon glyphicon-search"></i>
			    			</button>
			    		</div>
			    	</div>

			    	<div class="countryList" style="position: absolute;width: 235px;z-index: 1001;"></div>
			    </form>

			    <ul class="nav navbar-nav navbar-right">

			    	<li class="dropdown">
			    		<a href="#" class="dropdown-toggle" data-toggle="dropdown" id="friend_request_area">
			    			<span id="unseen_friend_request_area"></span>
			    			<i class="fa fa-user-plus fa-2" aria-hidden="true"></i>
			    			<span class="caret"></span>
			    		</a>
			    		<ul class="dropdown-menu" id="friend_request_list" style="width: 300px; max-height: 350px;">

			    		</ul>
			    	</li>

			    	<li><a href="profile.php?action=view"><?php echo Get_user_avatar($_SESSION["user_id"], $connect); ?> <b>Profile</b></a></li>
			    	<li><a href="logout.php"><span class="glyphicon glyphicon-log-in"></span> Logout</a></li>
			    </ul>
		  	</div>
		</nav>
		<div class="container">


home.php



<?php

//home.php

include('header.php');

?>
<style>
[contenteditable] {
  outline: 0px solid transparent;
  min-height:100px;
  height: auto;
  cursor: auto;
}

[contenteditable]:empty:before {
    content: attr(placeholder);
    color:#ccc;
    cursor: auto;
}

[placeholder]:empty:focus:before {
    content: "";
}

#temp_url_content a
{
	text-decoration: none;
}
#temp_url_content a:hover
{
	text-decoration: none;
}
#temp_url_content h3, #temp_url_content p
{
	padding:0 16px 16px 16px;
}

.fileinput-button input {
	    position: absolute;
	    top: 0;
	    right: 0;
	    margin: 0;
	    height: 100%;
	    opacity: 0;
	    filter: alpha(opacity=0);
	    font-size: 200px !important;
	    direction: ltr;
	    cursor: pointer;
	}
</style>
			<div class="row">
				<div class="col-md-8">
					<div class="panel panel-default">
						<div class="panel-heading">
							<div class="row">
		    					<div class="col-md-6">
									<h3 class="panel-title">Create Post</h3>
								</div>
								<div class="col-md-6 text-right">
									<span class="btn btn-success btn-xs fileinput-button">
										<span>Add Files...</span>
										<input type="file" name="files[]" id="multiple_files" multiple />
									</span>
								</div>
							</div>
						</div>
						<div class="panel-body">
							<div id="content_area" contenteditable="true" placeholder="Write Something...."></div>
						</div>
						<div class="panel-footer" align="right">
							<button type="button" name="share_button" id="share_button" class="btn btn-primary btn-sm">Post</button>
						</div>
					</div>
					<br />
					<div id="timeline_area"></div>
				</div>
				<div class="col-md-4">
					<div class="panel panel-default">
						<div class="panel-heading">
							<div class="row">
								<div class="col-xs-6">
									<h3 class="panel-title">Friends</h3>
								</div>
								<div class="col-xs-6">
									<input type="text" name="search_friend" id="search_friend" class="form-control input-sm" placeholder="Search" />
								</div>
							</div>
						</div>
						<div class="panel-body pre-scrollable">
							<div id="friends_list"></div>
						</div>
					</div>
				</div>
			</div>
<?php

include('footer.php');

?>


profile.php



<?php

//profile.php

include('header.php');

$message = '';

if(isset($_POST["edit"]))
{
 if(empty($_POST["user_name"]))
 {
  $message = '<div class="alert alert-danger">Name is required</div>';
 }
 else
 {
  if(isset($_FILES["user_avatar"]["name"]))
  {
   if($_FILES["user_avatar"]["name"] != '')
   {
    $image_name = $_FILES["user_avatar"]["name"];

    $valid_extensions = array('jpg', 'jpeg', 'png');

    $extension = pathinfo($image_name, PATHINFO_EXTENSION);

    if(in_array($extension, $valid_extensions))
    {
     $upload_path = 'avatar/' . time() . '.' . $extension;
     if(move_uploaded_file($_FILES["user_avatar"]["tmp_name"], $upload_path))
     {
      $user_avatar = $upload_path;
     }
    }
    else
    {
     $message .= '<div class="alert alert-danger">Only .jpg, .jpeg and .png Image allowed to upload</div>';
    }
   }
   else
   {
    $user_avatar = $_POST["hidden_user_avatar"];
   }
  }
  else
  {
   $user_avatar = $_POST["hidden_user_avatar"];
  }

  if($message == '')
  {
   $data = array(
    ':user_name'    => $_POST["user_name"],
    ':user_avatar'   => $user_avatar,
    ':user_birthdate'  => $_POST["user_birthdate"],
    ':user_gender'   => $_POST["user_gender"],
    ':user_address'   => $_POST["user_address"],
    ':user_city'    => $_POST["user_city"],
    ':user_zipcode'   => $_POST["user_zipcode"],
    ':user_state'    => $_POST["user_state"],
    ':user_country'   => $_POST["user_country"],
    ':register_user_id' => $_POST["register_user_id"]
   );

   $query = "
   UPDATE register_user 
   SET user_name = :user_name, 
   user_avatar = :user_avatar, 
   user_birthdate = :user_birthdate, 
   user_gender = :user_gender, 
   user_address = :user_address, 
   user_city = :user_city, 
   user_zipcode = :user_zipcode, 
   user_state = :user_state, 
   user_country = :user_country 
   WHERE register_user_id = :register_user_id
   ";

   $statement = $connect->prepare($query);

   $statement->execute($data);

   header("location:profile.php?action=view&success=1");
  }
 }
}

?>

<div class="row">
 <div class="col-md-9">
 <?php
 if(isset($_GET["action"]))
 {
  if($_GET["action"] == "view")
  {
   if(isset($_GET["success"]))
   {
    echo '
    <div class="alert alert-success">Profile Edited Successfully</div>
    ';
   }
 ?>
  <div class="panel panel-default">
   <div class="panel-heading">
    <div class="row">
     <div class="col-md-9">
      <h3 class="panel-title">Profile Details</h3>
     </div>
     <div class="col-md-3" align="right">
      <a href="profile.php?action=edit" class="btn btn-success btn-xs">Edit</a>
     </div>
    </div>
   </div>
   <div class="panel-body">
    <?php
    echo Get_user_profile_data_html($_SESSION["user_id"], $connect);
    ?>
   </div>
  </div>
 <?php
  }

  if($_GET["action"] == 'edit')
  {
   $result = Get_user_profile_data($_SESSION["user_id"], $connect);

   foreach($result as $row)
   {
 ?>
  <script>
  $(document).ready(function(){

   $('#user_gender').val("<?php echo $row["user_gender"]; ?>");

   $('#user_country').val("<?php echo $row["user_country"]; ?>");

   $('#user_birthdate').datepicker({
    assumeNearbyYear: true,
    format:'yyyy-mm-dd'
   });
  });
  </script>
  <div class="panel panel-default">
   <div class="panel-heading">
    <div class="row">
     <div class="col-md-9">
      <h3 class="panel-title">Edit Profile</h3>
     </div>
     <div class="col-md-3" align="right">
      <a href="profile.php?action=view" class="btn btn-primary btn-xs">View</a>
     </div>
    </div>
   </div>
   <div class="panel-body">
    <?php
    echo $message;
    ?>
    <form method="post" enctype="multipart/form-data">
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">Name</label>
       <div class="col-md-8">
        <input type="text" name="user_name" id="user_name" class="form-control" value="<?php echo $row["user_name"];  ?>" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">Date of Birth</label>
       <div class="col-md-8">
        <input type="text" name="user_birthdate" id="user_birthdate"  class="form-control" readonly value="<?php echo $row["user_birthdate"]; ?>" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">Gender</label>
       <div class="col-md-8">
        <select name="user_gender" id="user_gender" class="form-control">
         <option value="Male">Male</option>
         <option value="Female">Female</option>
        </select>
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">Address</label>
       <div class="col-md-8">
        <input type="text" name="user_address" id="user_address" class="form-control" value="<?php echo $row["user_address"]; ?>" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">City</label>
       <div class="col-md-8">
        <input type="text" name="user_city" id="user_city" class="form-control" value="<?php echo $row["user_city"];  ?>" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">Zipcode</label>
       <div class="col-md-8">
        <input type="text" name="user_zipcode" id="user_zipcode" class="form-control" value="<?php echo $row["user_zipcode"]; ?>" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">State</label>
       <div class="col-md-8">
        <input type="text" name="user_state" id="user_state" class="form-control" value="<?php echo $row["user_state"]; ?>" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">Country</label>
       <div class="col-md-8">
        <select name="user_country" id="user_country" class="form-control">
         <option value="">Select Country</option>
         <?php 

         echo load_country_list();

         ?>
        </select>
       </div>
      </div>
     </div>
     <div class="form-group">
      <div class="row">
       <label class="col-md-4" align="right">Profile</label>
       <div class="col-md-8">
        <input type="file" name="user_avatar" />
        <br />
        <?php
        Get_user_avatar($row["register_user_id"], $connect);
        ?>
        <br />
        <input type="hidden" name="hidden_user_avatar" value="<?php echo $row["user_avatar"]; ?>" />
        <br />
       </div>
      </div>
     </div>
     <div class="form-group" align="center">
      <input type="hidden" name="register_user_id" value="<?php echo $row["register_user_id"]; ?>" />
      <input type="submit" name="edit" class="btn btn-primary" value="Edit" />
     </div>
    </form>
   </div>
  </div>
 <?php
   }
  }
 }
 ?>

 </div>
 <div class="col-md-3">

 </div>
</div>

<?php

include('footer.php');

?>


footer.php



		</div>
		<br />
		<br />
	</body>
</html>

<style>



</style>

<script>

$(document).ready(function(){

	/*$('.dropdown-menu').click(function(e) {
        e.stopPropagation();
    });*/

	$('#searchbar').keyup(function(){

		var query = $(this).val();
		if(query != '')
		{
			$.ajax({
				url:"search_action.php",
				method:"POST",
				data:{query:query},
				success:function(data)
				{
					$('.countryList').html(data);
				}
			});
		}
		else
		{
			$('.countryList').html('');
		}

	});

	$(document).on('click', '.list-group-item', function(){
		$('#searchbar').val($.trim($(this).text()));
		//$('#countryList').fadeOut();
		$('.countryList').html('');

	});

	
	var is_open = 'no';

	$('#friend_request_area').click(function(){
		if(is_open == 'no')
        {
    	   load_friends_request_list_data();
           is_open = 'yes';
        }
	});

	function count_un_seen_friend_request()
	{
		var action = 'count_un_seen_friend_request';

		$.ajax({
			url:"friend_action.php",
			method:"POST",
			data:{action:action},
			success:function(data)
			{
				if(data > 0)
				{
					$('#unseen_friend_request_area').html('<span class="label label-danger">'+data+'</span>');
					is_open = 'no';
				}
			}
		})
	}	

	setInterval(function(){
		count_un_seen_friend_request();
	}, 5000);

	function load_friends_request_list_data()
	{
		var action = 'load_friend_request_list';
		$.ajax({
			url:"friend_action.php",
			method:"POST",
			data:{action:action},
			beforeSend:function()
			{
				$('#friend_request_list').html('<li align="center"><i class="fa fa-circle-o-notch fa-spin"></i></li>');
			},
			success:function(data)
			{
				$('#friend_request_list').html(data);
				remove_friend_request_number();
			}
		})
	}	

    function remove_friend_request_number()
    {
    	$.ajax({
    		url:"friend_action.php",
    		method:"POST",
    		data:{action:'remove_friend_request_number'},
    		success:function(data)
    		{
    			$('#unseen_friend_request_area').html('');
    		}
    	})
    }

    $('.dropdown-menu').click(function(event){

    	event.preventDefault();

    	var request_id = event.target.getAttribute('data-request_id');

    	if(request_id > 0)
    	{
    		$.ajax({
    			url:"friend_action.php",
    			method:"POST",
    			data:{request_id:request_id, action:'accept_friend_request'},
    			beforeSend:function()
    			{
    				$('#accept_friend_request_button_'+request_id).attr('disabled', 'disabled');
    				$('#accept_friend_request_button_'+request_id).html('<i class="fa fa-circle-o-notch fa-spin"></i> wait...');
    			},
    			success:function()
    			{
    				load_friends_request_list_data();
    			}
    		})
    	}

    	return false;

    });

    $('#friends_list').html('<div align="center" style="line-height:200px;"><i class="fa fa-circle-o-notch fa-spin"></i></div>');

    setTimeout(function(){
    	load_friends();
    }, 5000);

    function load_friends(query = '')
    {
    	$.ajax({
    		url:"friend_action.php",
    		method:"POST",
    		data:{action:'load_friends', query:query},
    		success:function(data)
    		{
    			$('#friends_list').html(data);
    		}
    	});
    }

    $(document).on('keyup', '#search_friend', function(){
    	var search_value = $('#search_friend').val();
    	if(search_value != '')
    	{
    		load_friends(search_value);
    	}
    	else
    	{
    		load_friends();
    	}
    });

    $('#share_button').click(function(){
    	var content = $('#content_area').html();

        var action = $('#share_button').data('action');

        var post_id = $('#share_button').data('post_id');

    	$.ajax({
    		url:"post_action.php",
    		method:"POST",
    		data:{content:content, action:action, post_id:post_id},
    		dataType:"JSON",
    		beforeSend:function()
    		{
    			$('#share_button').attr('disabled', 'disabled');
    			$('#share_button').html('<i class="fa fa-circle-o-notch fa-spin"></i> Post');
    		},
    		success:function(data)
    		{
    			$('#share_button').attr('disabled', false);
    			$('#share_button').html('Post');
    			$('#content_area').html('');
                $('#temp_url_content').remove();
    			$('#timeline_area').append('<div id="last_post_details"><div align="center" style="font-size:36px; color:#ccc"><i class="fa fa-circle-o-notch fa-spin"></i></div></div>');

                if(action == 'update')
                {
                    setTimeout(function(){
                        $('#last_post_details').html(make_post(data.content, data.user_image, data.user_name));

                        $('#'+data.temp_id).imagesGrid({
                            images:data.media_array
                        });

                    }, 5000);
                }
                else
                {
        			setTimeout(function(){
        				$('#last_post_details').html(make_post(data.content, data.user_image, data.user_name));
        			}, 5000);
                }
    		}
    	})
    });

    function make_post(content, user_image, user_name)
    {
    	html = `
    	<div class="panel panel-default">
            <div class="panel-heading">
                <div class="row">
                    <div class="col-md-9">
                        `+user_image+`&nbsp;<a href="#"><b>`+user_name+`</b></a> <span class="text-muted">has share post</span>
                    </div>
                </div>
            </div>
            <div class="panel-body" style="font-size:20px;">
                `+content+`
            </div>
        </div>
    	`;

    	return html;
    }

    $('#content_area').keyup(function(){
        var content = $('#content_area').html();

        var regex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

        var url = content.match(regex);

        if(url != null)
        {
            if(url.length > 0)
            {
                $.ajax({
                    url:"post_action.php",
                    method:"POST",
                    data:{action:'load_url_content', url:url},
                    dataType:"json",
                    beforeSend:function()
                    {
                        $('#content_area').append('<div id="temp_url_content"></div>');
                    },
                    success:function(data)
                    {
                        var html = `
                        <a href="`+data.link+`" target="_blank">
                            <div style="background-color:#f9f9f9">
                                `+data.media+`
                                <h3 style="color:#888">`+data.title+`</h3>
                                <p class="text-muted">`+data.description+`</p>
                            </div>
                        </a>
                        `;
                        $('#temp_url_content').html(html);
                    }
                })
            }
        }
        return false;
    });

    $('#multiple_files').on('change', function(){

        var form_data = new FormData();

        var file_input = $('#multiple_files');

        var total_files = file_input[0].files.length;

        for(var count = 0; count < total_files; count++)
        {
            var file_name = file_input[0].files[count].name;

            var extension = file_name.split('.').pop().toLowerCase();

            if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
            {
                alert('Invalid Image File');

                $('#multiple_files').val('');

                return false;
            }

            var file_size = file_input[0].files[count].size;

            if(file_size > 1000000)
            {
                alert('Image size Very Big');

                $('#multiple_files').val('');

                return false;
            }

            form_data.append('files[]', file_input[0].files[count]);
        }

        $.ajax({
            url:"upload.php",
            type:"POST",
            data:form_data,
            dataType:"json",
            contentType:false,
            processData:false,
            beforeSend:function(){
                $('#share_button').attr('disabled', 'disabled');

                $('#content_area').after('<div id="temp_url_content"><div align="center" style="font-size:36px; color:#ccc"><i class="fa fa-circle-o-notch fa-spin"></i></div></div>');
            },
            success:function(data)
            {
                $('#share_button').attr('disabled', false);
                $('#share_button').attr('data-post_id', data.post_id);
                $('#share_button').attr('data-action', 'update');
                $('#temp_url_content').html(data.html_data);
            }
        })
    });

    $(document).on('click', '.close', function(){

        var media_id = $(this).data('media_id');

        var path = $(this).data('path');

        $.ajax({
            url:"upload.php",
            method:"POST",
            data:{media_id:media_id, path:path, action:'remove_media'},
            success:function()
            {
                $('#media-'+media_id).fadeOut('slow');
            }
        });
    });

});

</script>


search_action.php



<?php

//search_action.php

include('database_connection.php');

include('function.php');

session_start();

if(isset($_POST["query"]))
{
	$search_query = preg_replace('#[^a-z 0-9?!]#i', '', $_POST["query"]);

	$search_array = explode(" ", $search_query);

	$replace_array = array_map('wrap_tag', $search_array);

	$condition = '';

	foreach($search_array as $search)
	{
		if(trim($search) != '')
		{
			$condition .= "user_name LIKE '%".$search."%' OR ";
		}
	}
	$condition = substr($condition, 0, -4);

	$query = "
	SELECT * FROM register_user 
    WHERE ".$condition." 
    AND register_user_id != '".$_SESSION["user_id"]."' 
    AND user_email_status = 'verified' 
    LIMIT 10
	";

	$statement = $connect->prepare($query);

	$statement->execute();

	$output = '<div class="list-group">';

	if($statement->rowCount() > 0)
	{
		foreach($statement->fetchAll() as $row)
		{
			$temp_text = $row["user_name"];
			$temp_text = str_ireplace($search_array, $replace_array, $temp_text);
			$output .= '
			<a href="#" class="list-group-item">
				' . $temp_text . '
                <div class="pull-left">
                    '.Get_user_avatar($row["register_user_id"], $connect).' &nbsp;
                </div> 
			</a>
			';
		}
	}
	else
	{
		$output .= '<a href="#" class="list-group-item">No Result Found</a>';
	}
	$output .= '</div>';

	echo $output;
}

if(isset($_POST["query_result"]))
{
	$output = '';
    //$query_string = str_replace(" ", ", ", $_POST["query_result"]);

    $search_array = explode(" ", $_POST["query_result"]);

    $condition = '';
    foreach ($search_array as $search)
    {
        if(trim($search) != '')
        {
            $condition .= "user_name LIKE '%".$search."%' OR ";
        }
    }

    $condition = substr($condition, 0, -4);

    $limit = 5;

    $page = 1;

    if($_POST['page'] > 1)
    {
        $start = (($_POST['page'] - 1) * $limit);
        $page = $_POST['page'];
    }
    else
    {
        $start = 0;
    }

    $query = "
    SELECT * FROM register_user 
    WHERE ".$condition." 
    AND register_user_id != '".$_SESSION["user_id"]."' 
    AND user_email_status = 'verified' 
    ";

    $filter_query = $query . 'LIMIT '.$start.', '.$limit.'';

    $statement = $connect->prepare($query);

    $statement->execute();

    $total_data = $statement->rowCount();

    $statement = $connect->prepare($filter_query);

    $statement->execute();

    $result = $statement->fetchAll();

    if($total_data > 0)
    {
        foreach($result as $row)
        {
            $button = '';

            $status = Get_request_status($connect, $_SESSION['user_id'], $row['register_user_id']);

            if($status == 'Pending')
            {
                $button = '
                <button type="button" name="request_button" class="btn btn-primary" disabled><i class="fa fa-clock-o" aria-hidden="true"></i> Pending</button>
                ';
            }
            else if($status == 'Reject')
            {
                $button = '
                <button type="button" name="request_button" class="btn btn-warning" disabled><i class="fa fa-ban" aria-hidden="true"></i> Reject</button>
                ';
            }
            else
            {
                $button = '
                <button type="button" name="request_button" class="btn btn-primary request_button" id="request_button_'.$row["register_user_id"].'" data-userid="'.$row["register_user_id"].'"><i class="fa fa-user-plus"></i> Add Friend</button>
                ';
            }

            $output .= '
            <div class="wrapper-box">
                <div class="row">
                    <div class="col-md-1 col-sm-3 col-xs-3">
                        '. Get_user_avatar_big($row["register_user_id"], $connect) .'
                    </div>
                    <div class="col-md-8 col-sm-6 col-xs-5">
                        <div class="wrapper-box-title">'.$row["user_name"].'</div>
                        <div class="wrapper-box-description"><i>From '.$row["user_country"].'</i></div>
                    </div>
                    <div class="col-md-3 col-sm-3 col-xs-4" align="right">
                        '.$button.'
                    </div>
                </div>
            </div>
        ';
        }
    }
    else
    {
        $output .= '
        <div class="wrapper-box">
            <h4 align="center">No Data Found</h4>
        </div>
        ';
    }

    $output .= '
    <br />
    <div align="center">
        <ul class="pagination">
    ';

    $total_links = ceil($total_data/$limit);

    $previous_link = '';

    $next_link = '';

    $page_link = '';

    if($total_links > 5)
    {
        if($page < 5)
        {
            for($count = 1; $count <= 5; $count++)
            {
                $page_array[] = $count;
            }
            $page_array[] = '...';
            $page_array[] = $total_links;
        }
        else
        {
            $end_limit = $total_links - 5;

            if($page > $end_limit)
            {
                $page_array[] = 1;
                $page_array[] = '...';

                for($count = $end_limit; $count <= $total_links; $count++)
                {
                    $page_array[] = $count;
                }
            }
            else
            {
                $page_array[] = 1;
                $page_array[] = '...';
                for($count = $page - 1; $count <= $page + 1; $count++)
                {
                    $page_array[] = $count;
                }
                $page_array[] = '...';
                $page_array[] = $total_links;
            }
        }
    }
    else
    {
        for($count = 1; $count <= $total_links; $count++)
        {
            $page_array[] = $count;
        }
    }

    for($count = 0; $count < count($page_array); $count++)
    {
        if($page == $page_array[$count])
        {
            $page_link .= '
            <li class="page-item active">
                <a class="page-link" href="#">'.$page_array[$count].' <span class="sr-only">(current)</span></a>
            </li>
            ';  

            $previous_id = $page_array[$count] - 1;

            if($previous_id > 0)
            {
                $previous_link = '<li class="page-item"><a class="page-link" href="javascript:void(0)" data-page_number="'.$previous_id.'">Previous</a></li>';
            }
            else
            {
                $previous_link = '
                <li class="page-item disabled">
                    <a class="page-link" href="#">Previous</a>
                 </li>
                ';
            }

            $next_id = $page_array[$count] + 1;

            if($next_id > $total_links)
            {
                $next_link = '
                <li class="page-item disabled">
                    <a class="page-link" href="#">Next</a>
                </li>
                ';
            }
            else
            {
                $next_link = '
                <li class="page-item"><a class="page-link" href="javascript:void(0)" data-page_number="'.$next_id.'">Next</a></li>
                ';
            }

        }
        else
        {
            if($page_array[$count] == '...')
            {
                $page_link .= '
                <li class="page-item disabled">
                    <a class="page-link" href="#">...</a>
                 </li>
                ';
            }
            else
            {
                $page_link .= '
                <li class="page-item"><a class="page-link" href="javascript:void(0)" data-page_number="'.$page_array[$count].'">'.$page_array[$count].'</a></li>
                ';
            }
        }
    }

    $output .= $previous_link . $page_link . $next_link;

    echo $output;
}

?>


search.php



<?php

//search.php

if(isset($_GET["query"]))
{
	$query = urldecode($_GET["query"]);

	$query = preg_replace("#[^a-z 0-9?!]#i", "", $query);
}

if(!isset($query))
{
	header('location:home.php');
}
else
{
	include('header.php');

?>
	
		<div class="row">
			<div class="col-md-9">
				<h3>Search Result for <b><?php echo $query; ?></b></h3>
				<div id="search_result_area">
					<div class="wrapper-preview">
						<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
					</div>
				</div>
			</div>
		</div>


		<script>
		$(document).ready(function(){
			var query_result = "<?php echo $query; ?>";

			$('#searchbar').val(query_result);

			load_data(query_result, 1);

			function load_data(query_result, page)
			{
				$.ajax({
					url:"search_action.php",
					method:"POST",
					data:{query_result:query_result, page:page},
					success:function(data)
					{
						$('#search_result_area').html(data);
					}
				})
			}

			$(document).on('click', '.page-link', function(){
				var page = $(this).data('page_number');

				if(page > 0)
				{
					load_data(query_result, page);
				}
			});

			$(document).on('click', '.request_button', function(){
				var to_id = $(this).data('userid');

				var action = 'send_request';

				if(to_id > 0)
				{	
					$.ajax({
						url:"friend_action.php",
						method:"POST",
						data:{to_id:to_id, action:action},
						beforeSend:function()
						{
							$('#request_button_'+to_id).attr('disabled', 'disabled');
							$('#request_button_'+to_id).html('<i class="fa fa-circle-o-notch fa-spin"></i> Sending...');
						},
						success:function(data)
						{
							$('#request_button_'+to_id).html('<i class="fa fa-clock-o" aria-hidden="true"></i> Request Send');
						}
					});
				}

			});

		});
		</script>
<?php

	include('footer.php');
}

?>


friend_action.php



<?php

//friend_action.php

include('database_connection.php');

include('function.php');

session_start();

if(isset($_POST["action"]))
{
	if($_POST["action"] == 'send_request')
	{
		sleep(5);
		$data = array(
			':request_from_id'				=>	$_SESSION['user_id'],
			':request_to_id'				=>	$_POST['to_id'],
			':request_status'				=>	'Pending',
			':request_notification_status'	=>	'No'
		);

		$query = "
		INSERT INTO friend_request 
		(request_from_id, request_to_id, request_status, request_notification_status) 
		VALUES (:request_from_id, :request_to_id, :request_status, :request_notification_status)
		";

		$statement = $connect->prepare($query);

		$statement->execute($data);
	}

	if($_POST["action"] == "count_un_seen_friend_request")
	{
		$query = "
		SELECT COUNT(request_id) as Total 
	    FROM friend_request 
	    WHERE request_to_id = '".$_SESSION["user_id"]."' 
	    AND request_status = 'Pending' 
	    AND request_notification_status = 'No'
		";

		$result = $connect->query($query);

		foreach($result as $row)
		{
			echo $row['Total'];
		}
	}

	if($_POST["action"] == "load_friend_request_list")
	{
		sleep(5);
		$query = "
		SELECT * FROM friend_request 
		WHERE request_to_id = '".$_SESSION["user_id"]."' 
	    AND request_status = 'Pending' 
	    ORDER BY request_id DESC
		";

		$result = $connect->query($query);

		$output = '';

		foreach($result as $row)
		{
			$user_data = Get_user_profile_data($row["request_from_id"], $connect);

			$user_name = '';

			foreach($user_data as $user_row)
			{
				$user_name = $user_row["user_name"];
			}

			$output .= '
			<li>
				'.Get_user_avatar($row["request_from_id"], $connect).'&nbsp;<b class="text-primary">'.$user_name . '</b>
				<button type="button" name="accept_friend_request_button" class="btn btn-primary btn-xs pull-right accept_friend_request_button" data-request_id="'.$row["request_id"].'" id="accept_friend_request_button_'.$row["request_id"].'"><i class="fa fa-plus" aria-hidden="true"></i> Accept</button>
			</li>
			';
		}
		echo $output;
	}

	if($_POST["action"] == 'remove_friend_request_number')
	{
		$query = "
		UPDATE friend_request 
		SET request_notification_status = 'Yes' 
		WHERE request_to_id = '".$_SESSION["user_id"]."' 
		AND request_notification_status = 'No'
		";
		$connect->query($query);
	}

	if($_POST["action"] == 'accept_friend_request')
	{
		sleep(5);
		$query = "
		UPDATE friend_request 
		SET request_status = 'Confirm' 
		WHERE request_id = '".$_POST["request_id"]."'
		";
		$connect->query($query);
	}

	if($_POST["action"] == 'load_friends')
	{
		$condition = '';

		if(!empty($_POST["query"]))
		{
			$search_query = preg_replace('#[^a-z 0-9?!]#i', '', $_POST["query"]);

			$search_array = explode(" ", $search_query);

			$condition = ' AND (';

			foreach($search_array as $search)
			{
				if(trim($search) != '')
				{
					$condition .= "register_user.user_name LIKE '%".$search."%' OR ";
				}
			}

			$condition = substr($condition, 0, -4) . ") ";
		}

		$query = "
		SELECT register_user.user_name, friend_request.request_from_id, friend_request.request_to_id FROM register_user 
		INNER JOIN friend_request 
		ON friend_request.request_from_id = register_user.register_user_id 
		OR friend_request.request_to_id = register_user.register_user_id 
		WHERE (friend_request.request_from_id = '".$_SESSION["user_id"]."' OR friend_request.request_to_id = '".$_SESSION["user_id"]."') 
		AND register_user.register_user_id != '".$_SESSION["user_id"]."'
		AND friend_request.request_status = 'Confirm' 
		".$condition."
		GROUP BY register_user.user_name 
		ORDER BY friend_request.request_id DESC
		";	

		$statement = $connect->prepare($query);

		$statement->execute();

		$html = '';

		if($statement->rowCount() > 0)
		{
			
			$count = 0;

			foreach($statement->fetchAll() as $row)
			{
				$temp_user_id = 0;

				if($row["request_from_id"] == $_SESSION["user_id"])
				{
					$temp_user_id = $row["request_to_id"];
				}
				else
				{
					$temp_user_id = $row["request_from_id"];
				}

				$count++;

				if($count == 1)
				{
					$html .= '<div class="row">';
				}

				$html .= '
				<div class="col-md-4" style="margin-bottom:12px;">
					'.Get_user_avatar_big($temp_user_id, $connect).'
					<div align="center"><b><a href="#" style="font-size:12px;">'.Get_user_name($connect, $temp_user_id).'</a></b></div>
				</div>
				';

				if($count == 3)
				{
					$html .= '</div>';
					$count = 0;
				}
			}
		}
		else
		{
			$html = '<h4 align="center">No Friends Found</h4>';
		}
		echo $html;
	}
}

?>


post_action.php



<?php

//post_action.php

include('database_connection.php');

include('function.php');

session_start();

if(isset($_POST["action"]))
{
	if($_POST['action'] == 'create')
	{
		sleep(5);
		$data = array(
			':user_id'		=>	$_SESSION["user_id"],
			':post_content'	=>	clean_text($_POST["content"]),
			':post_code'	=>	md5(uniqid()),
			':post_datetime'=>	get_date()
		);

		$query = "
		INSERT INTO posts_table 
		(user_id, post_content, post_code, post_datetime) 
		VALUES (:user_id, :post_content, :post_code, :post_datetime)
		";

		$statement = $connect->prepare($query);

		$statement->execute($data);

		$output = array(
			'content'	=>	html_entity_decode(clean_text($_POST["content"])),
			'user_image'=>	Get_user_avatar($_SESSION["user_id"], $connect),
			'user_name'	=>	$_SESSION["user_name"]
		);

		echo json_encode($output);
	}

	if($_POST["action"] == 'load_url_content')
	{
		$html = file_get_contents_curl($_POST["url"][0]);

		$doc = new DOMDocument();

		@$doc->loadHTML($html);

		$nodes = $doc->getElementsByTagName('title');

		$title = $nodes->item(0)->nodeValue;

		$description = '';

		$media = '';

		$link = $_POST['url'][0];

		$metas = $doc->getElementsByTagName('meta');

		for($i = 0; $i < $metas->length; $i++)
		{
			$meta_tag = $metas->item($i);

			if($meta_tag->getAttribute('name') == 'description')
			{
				$description = $meta_tag->getAttribute('content');
			}

			if($meta_tag->getAttribute('property') == 'og:description')
			{
				$description = $meta_tag->getAttribute('content');
			}

			if($meta_tag->getAttribute('name') == 'twitter:description')
			{
				$description = $meta_tag->getAttribute('content');
			}

			if($meta_tag->getAttribute('property') == 'og:video:url')
			{
				$media = '
				<div class="embed-responsive embed-responsive-16by9">
					  	<iframe class="embed-responsive-item" src="'.$meta_tag->getAttribute('content').'"></iframe>
					</div>
				';
			}

			if($media == '')
			{
				if($meta_tag->getAttribute('property') == 'og:image')
				{
					$media = '
					<div align="center"><img src="'.$meta_tag->getAttribute('content').'" class="img-responsive" /></div>
					';
				}
			}
		}

		if($media == '')
		{
			$media = '
			<div align="center"><img src="avatar/not-found.png" class="img-responsive" /></div>
			';
		}

		$output = array(
			'title'		=>	$title,
			'description'	=>	$description,
			'media'		=>	$media,
			'link'		=>	$link
		);

		echo json_encode($output);
	}

	if($_POST['action'] == 'update')
	{
		$data = array(
			':post_content'		=>	clean_text($_POST["content"]),
			':post_id'			=>	$_POST["post_id"]
		);

		$query = "
		UPDATE posts_table 
		SET post_content = :post_content 
		WHERE posts_id = :post_id
		";

		$statement = $connect->prepare($query);

		$statement->execute($data);

		$fetch_media = "
		SELECT * FROM media_table 
		WHERE post_id = '".$_POST['post_id']."'
		";

		$result = $connect->query($fetch_media);

		$media_array = array();

		foreach($result as $row)
		{
			$media_array[] = $row["media_path"];
		}

		$temp_id = rand();

		$output = array(
			'content'		=>	html_entity_decode(clean_text($_POST["content"])) . '<br /><br /><div id="'.$temp_id.'"></div>',
			'user_image'	=>	Get_user_avatar($_SESSION["user_id"], $connect),
			'user_name'		=>	$_SESSION["user_name"],
			'media_array'	=>	$media_array,
			'temp_id'		=>	$temp_id
		);

		echo json_encode($output);
	}
}

?>


upload.php



<?php

//upload.php

include('database_connection.php');

include('function.php');

session_start();

if(isset($_FILES['files']))
{
	$post_data = array(
		':user_id'		=>	$_SESSION["user_id"],
		':post_content'	=>	'',
		':post_code'	=>	md5(uniqid()),
		':post_datetime'=>	get_date(),
		':post_status'	=>	'Draft',
		':post_type'	=>	'Media'
	);

	$insert_query = "
	INSERT INTO posts_table 
	(user_id, post_content, post_code, post_datetime, post_status, post_type) 
	VALUES (:user_id, :post_content, :post_code, :post_datetime, :post_status, :post_type)
	";

	$statement = $connect->prepare($insert_query);

	$statement->execute($post_data);

	$post_id = $connect->lastInsertId();

	$html_data = '';

	for($count = 0; $count < count($_FILES['files']["name"]); $count++)
	{
		$name_array = explode(".", $_FILES['files']["name"][$count]);

		$extension = end($name_array);

		$new_file_name = rand(100000000,999999999) . '.' . $extension;

		$location = 'upload/' . $new_file_name;

		$tmp_name = $_FILES['files']["tmp_name"][$count];

		move_uploaded_file($tmp_name, $location);

		$media_data = array(
			':post_id'		=>	$post_id,
			':media_path'	=>	$location
		);

		$media_insert_query = "
		INSERT INTO media_table 
		(post_id, media_path) 
		VALUES (:post_id, :media_path)
		";

		$statement = $connect->prepare($media_insert_query);

		$statement->execute($media_data);

		$media_id = $connect->lastInsertId();

		$html_data .= '
		<div class="col-lg-2 col-md-3 col-4" style="margin-bottom:8px;" id="media-'.$media_id.'">
			<img src="'.$location.'" class="img-responsive" />
			<button type="button" class="close" data-media_id="'.$media_id.'" data-path="'.$location.'" aria-label="Close" style="position: absolute;top: 0;right: 18px;">
			  	<span aria-hidden="true">&times;</span>
			</button>
		</div>
		';
	}

	$output = array(
		'html_data'		=>	$html_data,
		'post_id'		=>	$post_id
	);

	echo json_encode($output);

}

if(isset($_POST["action"]))
{
	if($_POST["action"] == 'remove_media')
	{
		unlink($_POST["path"]);

		$query = "
		DELETE FROM media_table 
		WHERE media_id = '".$_POST["media_id"]."'
		";

		$connect->query($query);
	}
}

?>


function.php



<?php

//function.php

function make_avatar($character)
{
    $path = "avatar/". time() . ".png";
	$image = imagecreate(200, 200);
	$red = rand(0, 255);
	$green = rand(0, 255);
	$blue = rand(0, 255);
    imagecolorallocate($image, $red, $green, $blue);  
    $textcolor = imagecolorallocate($image, 255,255,255);  

    imagettftext($image, 100, 0, 55, 150, $textcolor, 'font/arial.ttf', $character);  
    //header("Content-type: image/png");  
    imagepng($image, $path);
    imagedestroy($image);
    return $path;
}

function Get_user_avatar($user_id, $connect)
{
	$query = "
	SELECT user_avatar FROM register_user 
    WHERE register_user_id = '".$user_id."'
	";

	$statement = $connect->prepare($query);

	$statement->execute();

	$result = $statement->fetchAll();

	foreach($result as $row)
	{
		return '<img src="'.$row['user_avatar'].'" width="25" class="img-circle" />';
	}
}

function load_country_list()
{
    $output = '';
    $countries = array("Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe");
    foreach($countries as $country)
    {
        $output .= '<option value="'.$country.'">'.$country.'</option>';
    }
    return $output;
}

function Get_user_profile_data($user_id, $connect)
{
    $query = "
    SELECT * FROM register_user 
    WHERE register_user_id = '".$user_id."'
    ";
    return $connect->query($query);
}

function Get_user_profile_data_html($user_id, $connect)
{
    $result = Get_user_profile_data($user_id, $connect);

    $output = '
    <div class="table-responsive">
        <table class="table">
    ';

    foreach($result as $row)
    {
        if($row['user_avatar'] != '')
        {
            $output .= '
            <tr>
                <td colspan="2" align="center" style="padding:16px 0">
                    <img src="'.$row["user_avatar"].'" width="175" class="img-thumbnail img-circle" />
                </td>
            </tr>
            ';
        }

        $output .= '
        <tr>
            <th>Name</th>
            <td>'.$row["user_name"].'</td>
        </tr>
        <tr>
            <th>Email</th>
            <td>'.$row["user_email"].'</td>
        </tr>
        <tr>
            <th>Birth Date</th>
            <td>'.$row["user_birthdate"].'</td>
        </tr>
        <tr>
            <th>Gender</th>
            <td>'.$row["user_gender"].'</td>
        </tr>
        <tr>
            <th>Address</th>
            <td>'.$row["user_address"].'</td>
        </tr>
        <tr>
            <th>City</th>
            <td>'.$row["user_city"].'</td>
        </tr>
        <tr>
            <th>Zip</th>
            <td>'.$row["user_zipcode"].'</td>
        </tr>
        <tr>
            <th>State</th>
            <td>'.$row["user_state"].'</td>
        </tr>
        <tr>
            <th>Country</th>
            <td>'.$row["user_country"].'</td>
        </tr>
        ';
    }
    $output .= '
        </table>
    </div>
    ';

    return $output;
}

function wrap_tag($argument)
{
    return '<b>' . $argument . '</b>';
}

function Get_user_avatar_big($user_id, $connect)
{
    $query = "
    SELECT user_avatar FROM register_user 
    WHERE register_user_id = '".$user_id."'
    ";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        return '<img src="'.$row['user_avatar'].'" class="img-responsive img-circle" />';
    }
}

function Get_request_status($connect, $from_user_id, $to_user_id)
{
    $output = '';

    $query = "
    SELECT request_status 
    FROM friend_request 
    WHERE (request_from_id = '".$from_user_id."' AND request_to_id = '".$to_user_id."') 
    OR (request_from_id = '".$to_user_id."' AND request_to_id = '".$from_user_id."') 
    AND request_status != 'Confirm'
    ";

    $result = $connect->query($query);

    foreach($result as $row)
    {
        $output = $row["request_status"];
    }

    return $output;
}

function Get_user_name($connect, $user_id)
{
    $query = "
    SELECT user_name 
    FROM register_user 
    WHERE register_user_id = '".$user_id."' 
    ";
    $result = $connect->query($query);
    foreach($result as $row)
    {
        return $row['user_name'];
    }
}

function clean_text($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function get_date()
{
    return date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')));
}

function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

?>








PHP Social Networking Websites tutorial source code will be available very soon.