PHP & Web Development Blogs

Search Results For: session
Showing 1 to 5 of 11 blog articles.
8 views · 1 months ago


For any development project to be successful, it’s important to choose the right technology and programming language. Most of the time, developers get confused about which programming language to choose.

Nowadays, PHP and Python have gained popularity among the programming languages for web development projects. However, choosing one between PHP vs Python is a difficult task. Recently, this has become a good topic for discussion.

Here, in this blog, we will compare the two popular programming languages: PHP vs Python. Let’s see which one turns out to be the best choice for web development.


What is Python?

Python is an open-source programming language developed in the year 1991 by Guido Van Rossum. It is one of the most commonly used languages due to its high level and easy-to-understand syntax.

According to the survey by Stack Overflow, Python is one of the most preferred programming languages. These Python app examples highlight its robustness and suitability for building scalable and innovative solutions across different platforms. Most of the companies and developers around the world are using Python web development.

What is PHP?

PHP or Hypertext Pre-processor, is an open-source server scripting language that is used for creating interactive and engaging web pages. This programming language comes with many features, libraries, plugins, and add-ons that increase community support and functionalities.

PHP language was developed by Rasmus Lerdorf in the year 1995. Earlier, PHP was named as Personal Home Page, which was later changed to Hypertext Pre-processor. An advantage of using PHP language is it supports all web browsers.

PHP is a practical, flexible, and fast programming language that can handle dynamic content on HTML sites, session tracking, and databases.

Features: PHP vs Python

PHP

* Open-source language, anyone can download and use it for free.
* PHP is easy to use and code than other programming languages.
* It is more efficient than other scripting languages like ASP and JSP.
* Offers access to log in by creating a summary of the recent user accesses.
* Provides database integration and supports distinct databases such as MySQL and Oracle.
* It has predefined error-reporting constants that generate warning or error messages.

Python

* Python is an easy-to-learn programming language.
* Provides an ideal structure and support for large applications.
* It can operate on different hardware platforms utilizing the same user interface.
* Python can be integrated with C, C++, and Java programming code.
* It’s easy to incorporate low-level modules in Python interpreter.
* Python offers high-level dynamic types of data and support for dynamic type checking.
* Its features support automatic garbage collection.
* It supports an interactive mode of testing and debugging.


Pros and Cons: PHP vs Python

Here, we will compare the pros and cons of PHP vs python for web development.

Pros of PHP

* Has a large ecosystem.
* Flexible and platform-independent.
* Several open-source PHP frameworks are available to use for free.
* Offers many pluggable frameworks, Open-source and object-oriented.
* Supports different database interfaces such as No SQL, PostgreSQL, and so on.
* It is supported by many operating systems and works cross-platform.
* Encourages top-notch debugging.
* Provides in-built SQL support.
* Offers support for database collection modules.
* It supports all operating systems like Windows, Linux, and UNIX.

Cons of PHP

* Delayed and wired performance.
* Not apt for content-based applications.
* Utilizes weak typing that can lead to false knowledge and data to users.
* Its core behavior can’t be changed.
* There’s no IOT alliance.
* Fewer security protocols and features.

Pros of Python

* Easy to learn and maintain.
* An open-source and uniformly unfolding language.
* Enables cross-platform code reusability.
* Object-oriented and versatile language to deploy.
* Offers WORA functionality.
* Helps in developing GUI apps.
* Has automatic garbage collection.
* It can be integrated easily with other languages, such as Java or C++.
* Provides libraries like Tenseorflow for math-intensive tasks.

Cons of Python

* Creates delays in web app testing.
* It utilizes an enormous amount of memory to help developers in easy development.
* Operates slower than other web development languages.
* Not of much use in mobile computing browsers and mobile app development.
* It has dynamic typing, which makes error detection more difficult.
* It’s too large for a simple and small app or website.
* Run time errors occurs due to duck typing.

When Should You Select PHP?

PHP is a commonly used server-side scripting language among developers. The best use cases in which you should select PHP:
* For developing blogs, websites, and web applications.
* Work effectively on the server side.
* Less investment.

When Should You Select Python?

* Python programming language has gained popularity in recent times. Below we have given some of the best cases in which you should choose Python.
* For operating in the areas of robotics and data science.
* When you want accurate and extensive data analytics.
* Developing websites using the Django framework.

Why opt for PHP?

Here, we will give you some reasons why you should opt for the PHP programming language.
* Open-source language, easy to download and use.
* Easy to learn and operates effectively on the server side.
* This scripting language can run on distinct platforms such as Windows, Mac OS X, Linux, and UNIX.
* It’s compatible with every server, like IIS, Apaches, and so on.
* Supports a broad range of databases.

Why opt for Python?

As you know, there are many advantages and disadvantages of using Python. Here, we will tell you why you should choose Python for web development.
* Python language is easy to use and maintain.
* Python syntax is quick to understand and debug as well. Therefore, its source code is easier to maintain.
* It has a garbage collection feature and memory addresses accordingly.
* It comes with many pre-built libraries.
* Python supports GUI apps such as Django, Tkinter, WXPython, etc.
* It’s a versatile and portable language. You can run Python on different types of operating systems or platforms.
* Python comes with a database-friendly interface that can store a colossal amount of data for commercial DBMS systems.
* It has an interactive shell that helps in unit testing before deploying a product.

Comparison: PHP vs Python

Above, we have given the features and pros & cons of PHP vs Python. In this section, we will give you a comparison between PHP vs Python in accordance with different parameters.

Parameters
Python
PHP
Release
    .
    .
Learning curve
Easier
Steep
Language type
Specialized for web development
General purpose programming language
Syntax
Clear & concise
Complex
Security
High
Medium
Readability
High
Low
Database connectivity
Faster
Slower
Debugging
Fast
Slower
Performance
Lesser support
Faster
Supported Frameworks
Flask, Django, Web2Py
Laravel, Zend, Codelgniter
GitHub Stars
    . 9k
    . 5k
TIOBE Rating
    . st position
    . th position
Forks
    . 5 k
    . 9k
Major Users
Instagram, YouTube, Quora, Reddit
Facebook, Yahoo, Flickr, Tumblr


This comprehensive comparison between PHP vs Python can help you to choose the right language for web development. Now, we will compare some other elements that would give you a clear picture of both PHP vs Python.

1. Ease of Learning

Python is an easier language to learn compared to PHP. If you are a beginner, then Python is a good choice as you can learn it quickly. Python programs are shorter as well as easy to write in comparison to other languages.

PHP programming language is made for creating sophisticated web apps. It’s not a general-purpose language, and it takes time to learn it.

2. Ease of Use

Python is an open-source programming language that is versatile and portable. Python’s syntax is simple, and coding is easy to learn compared to PHP. But PHP is not just an ordinary programming language it’s used for creating dynamic web pages with HTML. This makes PHP more difficult to use than Python.

3. Community Support

Both PHP and Python provide good community support. PHP has been in the market for a long time and has a large community of developers. Therefore, you can immediately get support if you opt for PHP.

However, there are even many Python developers who constantly develop python apps. So, the community support in Python is also good. Consequently, we can’t say whether PHP or Python is better at providing community support.

4. Flexibility

Nowadays, web apps backed by Machine Learning are in high demand. Also, ML is a significant part of Python. Python provides many machine-learning libraries, such as Tensorflow, Theano, Pandas, and Scikit-learn. Additionally, these libraries are rapid, unique, & robust and work effectively with a web framework.

Nonetheless, Python programming language can be used in many other fields apart from web development. But when it comes to PHP, it’s best for web development. Therefore, we can say Python is a better choice here.

Our skilled developers delivers the most promising web development firms to make dynamic websites for your business.

5. Speed to Market

Python provides a comprehensive set of modules and third-party libraries to help developers finish the project faster. One of the popular web frameworks written in Python is Django. It utilizes the MVC pattern to allow developers to create apps fast using a significant division of concerns and reusability.

PHP also has a vast set of tools, frameworks, and libraries. Laravel is a popular PHP framework that allows the MVC pattern. Additionally, it comes with many helpful functionalities for web development, like routing, templating, authentication, and so on.

6. Web Frameworks

You get robust and well-designed web development frameworks both in PHP and Python. Most of the big businesses utilize web frameworks that PHP provides. For example, Laravel and Symfony are mature web frameworks, and a huge community supports them. So, we can say PHP makes web development easy.

Python also has many exceptional frameworks that are highly scalable, easy to use, fast and secure. It’s two most popular web frameworks are Flask and Django. If you want a shorter development period, then you can choose Django over PHP-based frameworks.

7. Library Management

Python uses Pip to handle and deal with packages. Pip ensures that Python app development is easy, rapid, and meets development needs. Python has powerful library management compared to PHP. It has a wide range of packages and tools that assist and make web app development easier. So, in terms of library management, Python clearly wins it.

8. Security

When it comes to security, most businesses prefer using Python. For instance, Django offers many pre-built security features that aid in safeguarding the apps from distinct security breaches & threats.

Apart from that, many government organizations rely on Python as their secret hacking tool. Most of the security problems are addressed by its large community support. However, PHP is less strong than Python in aspects of security.

9. Environment Management

In terms of handling environments, Python is the best programming language. It has a Virtualenv system that aids in installing different versions of the language and switching between them immediately.
PHP has no comparison with Python when it comes to handling environments. There’s an analog of PHP, VirtPHP, but it’s archived and not maintained. Therefore, most of the developers opt for Python.

10. Debugging

Python has an in-built debugger called Python Debugger or PDB. It utilizes many debugging strategies. PDB enables dynamic typing and lets developers work effortlessly without stating things at the start of a program.
PHP also comes with an XDebug package for handling bugs and error-checking the codes. But PHP development is quite slow in identifying and removing bugs. Therefore, it often experiences security issues.


The Bottom Line PHP vs Python: Which One You Choose for Web Development?


From the blog, you must have inferred that both PHP and Python are good for web development. However, there are many aspects in which Python wins over PHP. But this doesn’t mean that you only have to opt for Python. The selection of programming language majorly depends on the complexity and needs of the project.

Sphinx Solutions is a leading and trusted web app development company. Our team of web developers can help you create the best web apps for your business based on your specifications. Schedule a call with our experts to get an estimation for your web app development project, or email us at [email protected].

PHP vs Python: FAQs

1. Why choose Python over PHP?
Python is chosen over PHP for web app development due to many reasons, such as ease to use, simple syntax, flexibility, security, high performance, etc.
2. Which programming language is secure: PHP vs Python?
Python is a preferred programming language when it comes to security as it has many security features compared to PHP.
3. Why is Python used mostly?
Python is a general-purpose programming language and is utilized in web development, mobile app development, AI, ML, game development, big data, and so on.
Browse More Related Article
    . React and Nodejs: The Best Combination for Web Application Development
    . A Timeless Guide on How to Expand Your Native App to a Web App
8280 views · 3 years ago


Recently I was faced with a task to post data from a .csv file to an external REST API. I’m just going to log in to this article about what I did to get the job done.

Let’s start by creating a template for uploading the file. For this article’s sake, lets make the changes in the dashboard.blade.php file.


<form method="post" enctype="multipart/form-data"> @csrf <div class="custom-file"> <input type="file" accept=".csv" name="excel" class="custom-file-input" id="customFile" /> <label class="custom-file-label" for="customFile">Choose file</label > </div> <div> <button type="submit" class="btn btn-primary btn-sm" style="margin-top: 10px" >Submit> </div>

</form>

Note : Don’t forget to add enctype=”multipart/form-data”!



Once the user has submitted the file, we need a new router to process the file and send its content to the REST API. Let’s start by creating a Controller.


php artisan make:controller UploadController


Now in the web.php file,


Route::post('/upload', [UploadController::class, 'upload'])->name('upload')->middleware('auth');


In the UploadController.php , create a function named upload. We will be writing all the code inside this function. Also, we need an action for the form.


<form method="post" action="{{route('upload')}}" enctype="multipart/form-data">


Now inside the upload function, we need to get the submitted file and parse its contents.

Get the submitted file,


$file = $request->file('excel');


Parse the submitted file,


if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { ..... }

}


We will be using a dummy REST API to create users — https://reqres.in/api/users. This is the request body required to create a user.


{ "name": "test", "job": "test"

}


Keeping this in mind, we will create a sample .csv template to be submitted. The fields need to be two, namely Name and Job.



We need to send the values from this file as the request body to the API. So let’s add the code to loop through the content of this file.


if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { Http::post('https://reqres.in/api/users', [ 'name' => $data[0], 'job' => $data[1], ]); }

}


This will create each student for each row of the file. But we don’t need to send the data of the first row of the file.

Full code:


public function upload(Request $request){ $file = $request->file('excel'); if($file){ $row = 1; $array = []; if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { if($row > 1){ Http::post('https://reqres.in/api/users', [ 'name' => $data[0], 'job' => $data[1], ]); array_push($array,$data[0]); } $request->session()->flash('status', 'Users '.implode($array,", ").' created successfully!'); $row++; } } }else{ $request->session()->flash('error', 'Please choose a file to submit.'); } return view('dashboard');

}


This will post the data starting from the second row of the file, display a success message once the users are created, and an error message if the submit button is clicked without choosing a file.

Full template:


<div class="container max-w-7xl mx-auto sm:px-6 lg:px-8" style="width: 50%"> @if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif @if (session('error')) <div class="alert alert-error"> {{ session('error') }} </div> @endif <form action="{{route('upload')}}" method="post" enctype="multipart/form-data"> @csrf <div class="custom-file"> <input type="file" accept=".csv" name="excel" class="custom-file-input" id="customFile" /> <label class="custom-file-label" for="customFile">Choose file</label> </div> <div> <button type="submit" class="btn btn-primary btn-sm" style="margin-top: 10px">Submit</button> </div> </form>

</div>




That’s it, thanks for reading :)
7594 views · 4 years ago
Midwest PHP and Nomad PHP Join Forces!


Interested in sponsoring? Check out the prospectus



A little history

Several years ago I had the distinct privilege of founding Midwest PHP with Jonathan Sundquist. The goal was simple, to bring an affordable PHP conference to Minnesota and the midwest region.

Midwest PHP was created for one simple reason - there weren't a lot of alternatives, especially affordable ones. At the time, your choices were ZendCon in Silicon Valley, php[tek] in Chicago, or Northeast PHP in Boston. While Northeast PHP formed the blueprint of a community conference - it still required a flight and a costly hotel in Boston. I wanted something where local attendees, college students, and those just beginning in their PHP careers could go to learn, network, and become part of the PHP community.

Shortly after Midwest PHP was formed (originally we were using the name PHPFreeze - until Sundquist told me what a horrible idea it was), Adam Culp launched Sunshine PHP which has become one of the top community focused PHP conferences (but still requires that flight and hotel in Miami). Sundquist and I knew that any reasonable developer would still prefer to attend a conference in a blizzard than enjoy the beautiful Floridian weather (ok, that might not be it, but we still understood the need that existed).

After moving to California for my new job, Jonathan Sundquist continued to run Midwest PHP as more community conferences appeared. With his efforts, and the torch being passed to Mike Willbanks, Midwest PHP celebrated it's seventh consecutive year, becoming the longest continuously running PHP conference (if you go by formed date, if you go by actual conference date Sunshine PHP beats us out by a month).


A renewed focus


Developers at Midwest PHP

Because of the incredible work Jonathan and Mike have done, Midwest PHP has stood the test of time - and the peaks and valleys that come with any conference. With the shifts in the PHP community and the sad loss of several community conferences - we realized the need for Midwest PHP is more now than ever, and to meet that need we needed to reimagine the way the conference operated.

We also realized that the best way to make Midwest PHP accessible was to combine forces, creating a seamless partnership between Nomad PHP and Midwest PHP. Through this partnership we're not only able to stream the event to make it more accessible ($19.95/mo), but also expand the conference.

This year, taking place onApril 2-4, 2020 - Midwest PHP will bring together over 800 developers both in-person and virtually! Making this year truly unique, however, and staying with our purpose of helping new developers be part of the PHP community is abrand new, FREE, beginner track. I'm excited to say we will be giving away 200 tickets to those wishing to attend our Beginner or Learn PHP track!!!

We will also work to keep prices as low as possible as we offer our standard PHP tracks (Everyday PHP and PHP Performance & Security) starting at $250/ person, anda brand new enterprise track geared at developers facing challenges at unprecedented scale starting at $450/ person.

Last but not least, it is our goal with the help of our sponsors to include the workshop day as part of your ticket price - allowing you to get one day of in-depth training, and two more full days of sessions. On top of this, we're also excited to make the Nomad PHP and Nomad JS video libraries available for Standard and Enterprise attendees, providing over 220 additional virtual sessions on demand!


For sponsors

Sponsoring a conference is hard. We understand the challenge of gauging ROI, planning travel, and coordinating outreach. With the combined forces of Midwest PHP and Nomad PHP, we're able to offer sponsors unique plans that maximize their investment - while ensuring the funds go back into the event to create an amazing experience for our attendees.

Beyond Midwest PHP's goal to be the largest PHP conference this year - the included Nomad PHP advertising will help you reach a much larger and broader audience, allowing for follow up advertisements and consistent engagement with the PHP community.


Interested in sponsoring? Check out the prospectus



Next steps

For more information, please visit the Midwest PHP website. The venue, call for papers, and additional information will all be posted there soon.
15394 views · 5 years ago
Implement Web Push Notification in PHP using W3C provided Notification API

Hi Guys,
I am sharing you the simple steps by which you can broadcast the web push notifications to your subscriber. In this tutorial we are making a subscriber form and saving information using Ajax and PHP and then through a server side code returning response to current logged in user and showing notification to that user.
Following are the steps to build this system


1. Create a database, I am creating db with name 'web_notifications'


Creating subscribers and notifications tables using following sql statements


CREATE TABLE IF NOT EXISTS <code>subscribers</code> (
<code>id</code> int(11) NOT NULL,
<code>name</code> varchar(255) NOT NULL,
<code>email</code> varchar(255) NOT NULL,
<code>createdAt</code> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE <code>subscribers</code> ADD PRIMARY KEY (<code>id</code>);

ALTER TABLE <code>subscribers</code> MODIFY <code>id</code> int(11) NOT NULL AUTO_INCREMENT;



CREATE TABLE IF NOT EXISTS <code>notifications</code> (
<code>id</code> int(11) NOT NULL,
<code>to_user</code> int(11) NOT NULL,
<code>title</code> varchar(255) NOT NULL,
<code>body</code> varchar(255) NOT NULL,
<code>url</code> varchar(255) NOT NULL,
<code>is_sent</code> int(11) NOT NULL DEFAULT '0',
<code>createdAt</code> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE <code>notifications</code> ADD PRIMARY KEY (<code>id</code>);

ALTER TABLE <code>notifications</code> MODIFY <code>id</code> int(11) NOT NULL AUTO_INCREMENT;





2. Now create a db_connect.php file with following code


<?php 
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "web_notifications";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>



3. Create a cookies.js file to read and write browser cookies


function WriteCookie(key,content) {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
document.cookie = key+"=" + escape(content) + ";";
document.cookie = "expires=" + now.toUTCString() + ";"
}

function ReadCookie(key) {
var allcookies = document.cookie;
cookiearray = allcookies.split(';');
var CookieData=Array();
for(var i=0; i<cookiearray.length; i++) {
k = cookiearray[i].split('=')[0];
v = cookiearray[i].split('=')[1];
CookieData[k]=v;
}
return CookieData[key];
}



4. Create a ajax file to read and mark is_sent if any notification foun to be sent in database for that user. create file with name 'fetch_notifications.php' with following content


<?php require 'db_connect.php';

$sql = "SELECT id,title,body,url FROM notifications where to_user='".@$_GET['user_id']."' and is_sent='0' ";
$result = $conn->query($sql);

$data=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[]=$row;

$upd = "update notifications set is_sent='1' where id='".$row['id']."' ";
$conn->query($upd);

}
}

if(count($data)>0)
{
$response=array("status"=>1,"notification"=>$data);
}
else
{
$response=array("status"=>0,"error"=>"No new notification!");
}

echo json_encode($response);

$conn->close();
?>



5. Now code index.php to show subscriber form and on submit insert record into the subscriber table



<?php require 'db_connect.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Web Push Notification Demo</title>
<script src="./cookies.js" type="text/javascript"></script>
<link href=" <script src=" <script src=" <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
<?php
if(isset($_POST['subscribe_form']))
{
$_SESSION['is_login']=0;
$username=$conn->real_escape_string($_POST['username']);
$useremail=$conn->real_escape_string($_POST['useremail']);


$sql = "INSERT INTO subscribers set name='".$username."',email='".$useremail."' ";
if ($conn->query($sql) === TRUE) {
$_SESSION['is_login']=1;
$_SESSION['Uid']= $conn->insert_id;
$_SESSION['Uname']= $username;
?>
<script type="text/javascript">
WriteCookie("Uid","<?php echo $_SESSION['Uid']; ?>");
</script>
<?php
$msg="<p style='color:green'>You have subscribe for push notification succesfully :)</p>";
} else {
$msg="<p style='color:red'>Error in subscribing for notifications</p>";
}


}

?>
<div class="container">
<?php
if(isset($msg) && $msg!='')
{
?>
<br>
<div class="alert alert-info">
<?php echo $msg; ?>
</div>
<?php
}

if(isset($_SESSION['is_login']) && $_SESSION['is_login']==1)
{
?>
<h2>Welcome <?php echo $_SESSION['Uname']; ?></h2>
<script type="text/javascript">

setInterval(function(){
check_notification();
}, 10000);

function check_notification()
{
var Uid=ReadCookie("Uid");
if(Uid!==undefined)
{
$.ajax({url: "fetch_notifications.php?user_id="+Uid, success: function(result){
var response=JSON.parse(result);
if(response.status==1)
{

response=response.notifications;
for (var i = response.length - 1; i >= 0; i--) {
var url = response[i]['url'];
var noti = new Notification(response[i]['title'], {
icon: 'logo.png', body: response[i]['body'],
});
noti.onclick = function () {
window.open(url);
noti.close();
};

};

}
else{
console.log(response.error);

}

}

});
}
}


</script>
<?php
}
else
{
?>
<h2 class="text-center">Subscribe for Notifications</h2>
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-6 pb-5">

<div class="card border-primary rounded-0">
<div class="card-header p-0">
<div class="bg-info text-white text-center py-2">
<h3><i class="fa fa-envelope"></i> Information</h3>
<p class="m-0">provide your information</p>
</div>
</div>
<div class="card-body p-3">
<form method="post">
<!--Body-->
<div class="form-group">
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-user text-info"></i></div>
</div>
<input type="text" class="form-control" id="username" name="username" placeholder="Input Your Name Here" required>
</div>
</div>
<div class="form-group">
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-envelope text-info"></i></div>
</div>
<input type="text" class="form-control" id="useremail" name="useremail" pattern="[^@\s]+@[^@\s]+\.[^@\s]+" title="Invalid email address" placeholder="[email protected]" required>
</div>
</div>

<div class="text-center">
<input type="submit" value="Subscribe" name="subscribe_form" class="btn btn-info btn-block rounded-0 py-2">
</div>
</form>
</div>

</div>



</div>
</div>
<?php }?>
</div>



</head>
<body>

</body>
</html>
<?php
$conn->close();
?>


The frontend of your subscription page (index.php) should look like this:


Subscribing Form to User

Now we are ready to receive notification in frontend, but we still need to create an admin page from where we can send notification to subscriber(s).


6. Create a table for admin user





CREATE TABLE IF NOT EXISTS <code>admin</code> (
<code>id</code> int(11) NOT NULL,
<code>username</code> varchar(255) NOT NULL,
<code>password</code> varchar(255) NOT NULL,
<code>createdAt</code> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE <code>admin</code> ADD PRIMARY KEY (<code>id</code>);

ALTER TABLE <code>admin</code> MODIFY <code>id</code> int(11) NOT NULL AUTO_INCREMENT;

INSERT INTO <code>web_notifications</code>.<code>admin</code> (<code>id</code>, <code>username</code>, <code>password</code>, <code>createdAt</code>) VALUES (NULL, 'admin', MD5('123456'), CURRENT_TIMESTAMP);




Following is the code for admin.php to add the notifications to subscriber(s) account also i have inserted following login credentials for admin in admin table:
username:admin
password:123456


7. Now put following code in admin.php


<?php require 'db_connect.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>ADMIN PAGE</title>
<link href=" <script src=" <script src="
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
<?php
if(isset($_POST['login']))
{
$_SESSION['admin_login']=0;
$username=$conn->real_escape_string($_POST['username']);
$password=$conn->real_escape_string($_POST['password']);
$sql = "SELECT * FROM admin where username='".$username."' and password='".md5($password)."' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$_SESSION['admin_login']=1;
$msg="<p style='color:green'>Admin Logged-in Successfully :)</p>";
}
else {
$msg="<p style='color:red'>INVALID CREDENTIALS FOR ADMIN</p>";
}


}
if(isset($_POST['add_notification']))
{
$title=$conn->real_escape_string($_POST['title']);
$body=$conn->real_escape_string($_POST['body']);
$url=$conn->real_escape_string($_POST['url']);
$users=$_POST['users'];

foreach ($users as $user_id) {
$ins = "insert into notifications set to_user='".$user_id."' , title='".$title."', url='".$url."', body='".$body."' ";
$conn->query($ins);
}
$msg="<p style='color:green'>Notification(s) added to subscribers account.</p>";

}

?>
<div class="container">
<?php
if(isset($msg) && $msg!='')
{
?>
<br>
<div class="alert alert-info">
<?php echo $msg; ?>
</div>
<?php
}

if(isset($_SESSION['admin_login']) && $_SESSION['admin_login']==1)
{
?>
<h2>Welcome Admin, Send notification to Subscriber(s)</h2>

<form method="post">



<div class="form-group">
<label for="sel1">Select Subscriber(s):</label>
<select multiple="multiple" required="required" class="form-control" id="users" name="users[]">
<?php
$sql = "SELECT id,name FROM subscribers";
$result = $conn->query($sql);

$data=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['name']."</option>";
}
}
?>
</select>
</div>

<div class="form-group">
<label for="email">Title</label>
<input type="text" required class="form-control" placeholder="notification title here" name="title" id="title">
</div>

<div class="form-group">
<label for="email">Message</label>
<textarea required class="form-control" placeholder="notification message here" name="body" id="body"></textarea>
</div>

<div class="form-group">
<label for="email">Url</label>
<input type="url" required class="form-control" placeholder="notification landing/click url here" name="url" id="url">
</div>

<input type="submit" class="btn btn-primary btn-block" name="add_notification" value="Submit" />

</form>


<?php
}
else
{
?>
<h2 class="text-center">ADMINISTRATOR</h2>
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-6 pb-5">

<div class="card border-primary rounded-0">
<div class="card-header p-0">
<div class="bg-info text-white text-center py-2">
<h3><i class="fa fa-envelope"></i> LOGIN</h3>
<p class="m-0">provide admin login credentials</p>
</div>
</div>
<div class="card-body p-3">
<form method="post">
<!--Body-->
<div class="form-group">
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-user text-info"></i></div>
</div>
<input type="text" class="form-control" id="username" name="username" placeholder="Input username here" required>
</div>
</div>
<div class="form-group">
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fa fa-key text-info"></i></div>
</div>
<input type="password" class="form-control" id="password" name="password" placeholder="your password here" required>
</div>
</div>

<div class="text-center">
<input type="submit" value="Login" name="login" class="btn btn-info btn-block rounded-0 py-2">
</div>
</form>
</div>

</div>



</div>
</div>
<?php }?>
</div>



</head>
<body>

</body>
</html>
<?php
$conn->close();
?>


The admin page will ask login credentials first then it will look like following screenshot:

Admin Send Notifiv=cation to subscribers

Now in your project if you open index.php you have a frontend where user will register themselves to receive notifications, and admin.php is your backend where you can send notifications to users or subscribers


If you face any problem in setup this small project please just let me know in the comments below, or by messaging me.
7746 views · 5 years ago
Standalone PHP Class for Managing Session Based Multiple Cart

Hi Guys,

I am sharing you a standalone class for managing a session based cart system. In this class I have provided multiple methods for adding, updating and deleting the products. and By using this class you may manage multiple cart objects with different data only you need to pass a different key in constructor of that class.

Let me share you the How can we use that Class:


Include The cart class


require 'PhpKart.class.php';



Create a Cart Object initializing the Cart base key name, by using different keys we can manage multiple cart data in a same project , like main cart or wishlist


$obj1 = new PhpKart("MainCart");


Here Maincart is the keyname in which $obj1 insert/modify/delete the data


Adding any product inside cart


$obj1->add_to_cart($product_id=123,$quantity=2,$product_information=array("product_name"=>"Tomato","Price"=>20));


Where parameter1 is product, id,parameter 2 is quantity, and Parameter 3 is product information Array


Now If we want to update the quantity in product_id=123 with quantity 5 then use following:


$obj1->add_to_cart($product_id=123,$quantity=5);


Here we did not pass the information array again because no matter you pass or not if the product information is already added in the cart then if won't be affected So no ned to pass this, only pass product id and its Quantity


If we want to add another product:


$obj1->add_to_cart($product_id=145,$quantity=3,$product_information=array("product_name"=>"Potato","Price"=>30));



Now we have a case what if our product is already having some quantity and we want to increase into it or decrease into it, Then to retrieve the already added product information, using AlreadyExists method by passing product id,it will return array if it exists and it will return boolean false if not exists:


$already_exists=$obj1->AlreadyExists($product_id=145); 
if($already_exists !== false )
{
print_r($already_exists);
}



If we want to remove any product from cart:


$obj1->remove_from_cart($product_id=145);



If we want to get all products from the current cart


print_r( $obj1->getAllItems() );


It will return you an array with all the items exist in the current cart



Getting all item's count inside the current cart


echo $obj1->getTotalItems(); 



If we want to get calculate total amount in the current cart


echo $obj1->getCartTotalAmount($priceKeyName='Price')


Note: In the above snippet we need to provide teh same key name which we have used for product price in project information array at the time of adding items in cart array, and need to take the same key name in all the products inserting in Same Cart



If we want to clear/reset the current cart then use following:


$obj1->clear_cart(); 


Now if we want to save some other user interested items separately which use likes but don't want to buy now so that items can be Add into wishlist So we need to create new object with different cart ket name and that list will be manage separately using it's object. Like Following:



Create new Object by passing different Key

$obj2=new PhpKart("MyWishlist"); 



Add a new item to $obj2 object containing the items user want to add in his/her wishlist


$obj2->add_to_cart($product_id=159,$quantity=8,$product_information=array("product_name"=>"Baby Toy","Price"=>100));



Show the total cart Amount


echo $obj2->getCartTotalAmount("Price"); 



Full Source Code


Following is the full code for that cart managing Class . Just create a file named PhpKart.class.php and add following code in it:

<?php 
if(!session_id()){
@session_start();
}


class PhpKart{

private $cart_key;

public function __construct($CartkeyName)
{
$this->cart_key=$CartkeyName;
}
public function add_to_cart($product_id,$quantity='1',$product_information=array())
{
$_SESSION[$this->cart_key][$product_id]['product_id']=$product_id;
$_SESSION[$this->cart_key][$product_id]['quantity']=$quantity;
if(!isset($_SESSION[$this->cart_key][$product_id]['product_information']) && !empty($product_information)){
$_SESSION[$this->cart_key][$product_id]['product_information']=$product_information;
}
}
public function remove_from_cart($product_id)
{
unset($_SESSION[$this->cart_key][$product_id]);
}
public function clear_cart()
{
unset($_SESSION[$this->cart_key]);
}
public function getTotalItems()
{
return count($_SESSION[$this->cart_key]);
}
public function getCartTotalAmount($price_key_name)
{
$total=0;
foreach($_SESSION[$this->cart_key] as $row)
{
$total += ($row['product_information'][$price_key_name]*$row['quantity']);
}

return $total;
}
public function AlreadyExists($product_id)
{
if (isset($_SESSION[$this->cart_key][$product_id]))
{
return $_SESSION[$this->cart_key][$product_id];
}
else
{
return false;
}
}
public function getAllItems()
{
return $_SESSION[$this->cart_key];
}


}

?>

SPONSORS

PHP Tutorials and Videos