PHP & Web Development Blogs

Search Results For: memory
Showing 1 to 5 of 9 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
8 views · 3 months ago


Today’s digital transformation has significantly empowered every company to produce accurate information at all touch points. Whether it’s a large-scale enterprise or a small private venture, every organization irrespective of all sizes needs proper web app development services to build a sophisticated database for storing and managing its data. Examples of web applications include customer relationship management (CRM) systems, project management tools, and e-commerce platforms. These custom software developers play a crucial role in tailoring web applications to meet specific business needs, ensuring seamless integration and optimal functionality.

A database is a set of a vast range of structured & unstructured data stored in a system and adequately managed through DBMS or Database Management System. The data stored in the database is highly sensitive, hence companies need to be careful while accessing any data or information.

When considering the development of web applications, partnering with a reputable web development firm is essential to ensure the seamless integration and efficient management of databases. A skilled web development firm possesses the expertise to optimize database systems, enhancing data organization, security, and retrieval processes for an enhanced user experience. In this article, we will delve into the top database solutions for web applications in 2024 and explore the advantages they bring to the forefront of modern software development.

Types of Databases For Web Applications

Depending on your business model, industry domain, and other factors, your business application system will have certain requirements. Different databases types are used for different enterprise requirements. However, the database is technically divided into two types: SQL & NoSQL.

SQL or Structured Query Language is a relational database that comes with a relational structure. This is used for managing structured data only. On the other hand, the NoSQL database doesn’t have any relational structure & they are used to store unstructured data types. For your convenience, we have shared a complete comparison of both databases below.

SQL Databases
NoSQL Databases
Mix of proprietary & open-source
Open source database
Comes with rational structure
No rational structure
Ideal for managing structured data
Best for storing unstructured & semi-structured data
Vertically scalable
Horizontally scalable
Examples: MySQL, PostgreSQL, Oracle, etc
Examples: MongoDB, Cassandra, Firebase, etc

Enterprises have deeply relied on SQL to manage all their databases in web apps, but as cloud, microservices & distributed applications become popular, there are NoSQL options also available. Before you choose the right database, you must consider a number of factors such as size, structure & scalability requirements. Apart from that, you need to consider some of the following questions also:
* What type of data structure do you need?
* What is the amount of data you want to store?
* What is your total budget?
* Does it allow for support contracts & software licenses?
* What is the requirement for your data security?
* What third-party tools do you want to add to your database?

Best Databases For Web Applications In 2024

Finding out the right database option for a web app development may impact the scalability and success of any project. With too many options available, it’s quite challenging to select which one is the best for you. 2024’s widely-popular databases include:

1. MySQL:

MySQL is one of the best open-source relational databases developed by Oracle Corporation in 1995. According to the Stack Overflow developer survey, this database was used by 46.8% as of 2022. The robustness, maturity, and stability of this database make it perfect for web applications. Moreover, MySQL database uses a structured language & written in C & C++.
Latest version: MySQL 8.0.33

Key features of MySQL database include:
* Easy to deploy & manage
* It supports Consistency, Atomicity, Isolation & Durability
* It’s an RDBMS or Relational Database Management System
* Provides fast-loading utilities with several memory caches to maintain servers
* Offers top-notch results without compromising any functionality
* Contains solid Data Security layers to offer complete security solutions

2. PostgreSQL:

Launched in 1996, PostgreSQL is also a very popular database used as a data warehouse or primary data store for web, analytics, geospatial and mobile applications. This is also an open-source SQL-based RDBMS (relational database management system) that supports C, C++, C#, Ruby, Java, Python, and other programming languages. This agile database is compatible with different OSs such as Windows, Linux, Unix, MacOSX, etc.
Latest version: PostgreSQL 15.3

Key features of the PostgreSQL database include
* Houses different constraints such as primary keys, foreign keys, exclusion constraints, explicit locks, advisory locks, etc
* Supports different SQL features like SQL Sub-selects, Multi-Version Concurrency Control,
* Streaming Replication, complex queries, etc.
* Compatible with different data types like Structured, Customizations, Primitives, Geometry & Documents.
* Supports MVCC or multi-version concurrency control

3. Microsoft SQL Server:

Launched in 1989, Microsoft SQL Server is a powerful RDBMS used for transaction processing, analytics applications, and business intelligence in IT environments. It comes with built-in intelligence & enables businesses to boost their performance, security, and availability seamlessly. MS SQL Server comes in different editions with authentication & security features.
Latest version: Microsoft SQL Server 2022

Key features of the Microsoft SQL Server database include:
* Available on both Linux & Windows platforms
* Supports semi-structured, structured, and spatial data
* It has a custom-built graphical integration
* Helps users build different designs and tables without syntax
* Comes with several features for protection, monitoring, and data classification
* Gives alerts on security gaps, misconfigurations & suspicious activities

4. MongoDB:

MongoDB is a document-oriented open-source NoSQL database used for high-volume data storage. Written in JavaScript, C++, and Python, this is a very flexible and scalable database platform that removes relational DB approaches. MongoDB offers a high level of flexibility through load balancing and horizontal scaling capacities. This is a perfect option for web apps that need high performance.
Latest version: MongoDB 6.0.5

Key features of the MongoDB database include:
* Effectively supports ad hoc queries
* Highly scalable & flexible database
* Offers schema-less database
* Appropriate indexing for query executions
* Replication for data availability & stability

5. Oracle:

Oracle is a very popular RDBMS that is known for its high-performance and cost-optimization solutions. This is a commercial relational database written in C, C++ & Java. Oracle comes with a relational database architecture that offers an easy, scalable, performant solution for accessing, defining, and managing data.
Latest version: Oracle 21c

Key features of the Oracle database include:
* Executes fast backup & recovery
* Provides multiple database support
* Offers superior scalability
* Offers better user controls and identity management
* Utilizes a single database for every data type

6. Redis:

Redis stands for Remote Dictionary Server and is a widely-used open-source database used for web applications and cache management. Redis can also be used with different streaming solutions like Amazon Kinesis & Apache Kafka to analyze & process real-time data.

This database also supports different data structures like lists, streams, bitmaps, strings, maps, and so on. Because of its high performance, Redis is vastly used in many sectors such as IoT, Gaming, Financial Services, etc.
Latest version: Redis 7.0.11

Key features of the Redis database include:
* Provides premium speed with improved caching & in-memory capabilities.
* Supports a variety of data structures (strings, hashes, lists, bitmaps, HyperLogLogs, etc)
* Compatible with different languages (Java, PHP, Python, C, C#, C++, etc)
* Offers quick access to data for training, deploying, and developing applications

7. Cassandra:

Released in 2008, Cassandra is a distributed open-source NoSQL database that effectively manages vast amounts of data. It provides excellent scalability that supports multi-datacenter replication and automatic data replication. Cassandra database is ideal for applications that need prompt data access with high performance.
Latest version: Cassandra 4.1.0

Key features of the Cassandra database include:
* Easy to scale
* Highly scalable & comes with strong architecture
* Offers flexibility for data distribution
* Faster linear-scale performance
* Very flexible data storage
* Supports properties like Consistency, Atomicity, Isolation, and Durability

How Much Does The Web Application Database Cost?

In general, the average web app development cost ranges from $5,000 to $100,000. However, this cost depends on too many parameters like web app database complexity, features & functionalities, backend infrastructure, etc.

If you want to get a proper estimation of your web database application cost, you can take advantage of a web app cost calculator. For your convenience, we have listed the average web application development costs based on their categories.
Factors
Basic Web Apps
Medium Apps
Complex Apps
Highly Complex Apps
Estimated cost
$3,000 to $15,000
$15,000 to $60,000
$60,000 to $2,50,000
More than $250,000
Timeline
    . to 5 weeks
    . to 20 weeks
    . to 25 weeks
More than 9 months
Features
Simple landing page
Static content
Landing page
Database integration
Admin panel
User accounts
Online payment options
Third-party integrations
Landing page
Huge database integration
Admin panel
Multipleuser accounts
Online Payment options
Third-party integrations
Personalized features
Landing page
Top-notch database integration
Admin panel
Customized features
Examples
Online brochures
Portfolio
websites
MVP
Web portals
E-commerce websites
Online gaming sites with animation
Web applications for businesses
Automated billing systems
Human resources management system (HRMS)
Complex ecommerce websites
Custom web apps
On-demand web apps
App for complex businesses
High-end features with AI/ML integration
Custom web apps

Final Words

In the past, the process of selecting a database web application was straightforward. However, in this modern era of software development, this process has become very intrinsic as too many options are available today and the business requirements have also transformed.

For a business that works with small apps, NoSQL databases like MongoDB can be the best choice & for managing large & complex applications, databases like MySQL, MS SQL Server, and PostgreSQL can be the right choice. Would you like to know more about web applications with databases? Talk to our experts today.
6064 views · 3 years ago
Web Sockets in PHP

In his talk Websockets in PHP, John Fransler walks us through the use of WebSockets in PHP.

While discussing bi-directional real-time application development, John notes that PHP is often not invited to the table due to its lack of native support. Of all the possible attempts to bring in PHP on this stage of real-time development, Ratchet, a PHP WebSocket library, comes closest. "Ratchet is a loosely coupled PHP library providing developers with tools to create real-time, bi-directional applications between clients and servers over WebSockets."* Ahem!

Today's dynamic world


In today's dynamic content world of the internet, it is required to serve real-time bi-directional messages between clients and servers. WebSockets are simple, full-duplex, and persistent. They work over Http and are a standard today.

WebSockets have compatibility with 96.5% of clients globally

There's a very high chance your client has the necessary plumbing to access your content via WebSockets. WebSockets gives the ability to have real-time data on to your clients without the need for polling.

To understand WebSockets, John takes an example of a Javascript client and Ratchet Server. Javascript has everything built in to allow access to a socket. For example, you can use the send method on a WebSocket variable to send a message to the server, or if you want to respond to a message from the server, you use the OnConnection method.

While on the Server, John uses Ratchet, which is built on React PHP. A server script is then configured and set up to run and listen on a port for incoming HTTP requests. For messages, JSON is used, and to find public methods, a router is set up. He then goes on to instantiate the server-side script in Ratchet.

There are four functions of a Ratchets message component interface that are used in this example:

OnOpen gets called when a new connection is made.

OnClose gets called when a client quits. It's essential to keep an eye on memory management, and essential to keep tidying up as you move through the code.

OnError gets called when there is an exception faced by the user.

OnMessage gives the text of the JSON message, which is being exchanged with the client.

For Initialization, Jason continues to walk through the example. He shows how one can loop through the clients, both inside the server and outside the server. Outside the server, it’s a feature of React PHP. On database access, and with traditional standard synchronous MySQL in PHP, what usually happens is that it forces the code to wait for the query to return a result and do nothing — Fortunately, with Asynchronous MySQLi, that is not the case.

John gets into the details explaining Variables, References & Pointers. He also gives a demo where a central site has updated information on the Bitcoin and ether prices. A client terminal reflects the last values. Now the client doesn't have to poll the server for new values. When there is a change in the Bitcoin or ether values, the server pushes down the client's update. No polling helps with a lot of overheads and gets closer to real-time.

Using Supervisord


For Long-running applications - Jason recommends running a supervisord, use proxy to expose the port, and add a site certificate. Supervisord keeps an eye out for the server running the service; it can be used to restart the service and log any service issues. Recommended proxies are AWS load balancer, Nginx, and HA Proxy. For scalability, use multiple smaller WebSocket servers and a smaller number of clients per server used and load balancing. If one has to support a chat feature to allow clients to talk to each other in near real-time, it is recommended to use Redis. The Redis server proxies the messages between the server nodes.

The talk concludes with John summarizing best practices on error handling and takes QnA on various aspects of WebSockets such as handling load balancers and asynchronous calls to MSQLi.

The presentation for this video, along with the code, is hosted at John Curt's GitHub. More info about John's current areas of interest can be found on John's Blog.

Watch the video now


Related videos
11056 views · 3 years ago


It took me quite some time to settle on my first blog post in this series and I found myself thinking about the most requested functionality in my career – The good ‘ol Custom CMS – typically geared towards clients that want a straight forward, secure solution that can be expanded upon in a modular format and that’s their IP.

This will be our starting point. A blank slate to build something epic with clean code and even cleaner design. And in the spirit of building from scratch, I will refrain from using classes or a framework. The main reasoning behind this is to truly get everyone acquainted with and excited about PHP development.

Join me as I transform rudimentary code into something extraordinary that can be morphed into just about any Content, PHP, and MySQL driven project. So without further ado, let’s jump into it!

The bare necessities


If you’re just getting started with development, there’s a nifty bite sized server called UniformServer that will be your best friend throughout your coding career. PHPMyAdmin (an awesome visual db management tool) comes built in so if you’re looking for a work right out of the box solution, this is it.

Alternatively, you can opt for XAMPP or use an alternative server of your choice.

Now here’s where the exciting stuff begins, mapping things out.


I don’t see this done/encouraged often enough. Feel free to grab a piece of paper to logically map out your steps or produce a rough draft of where you’d like this project to go.

In this tutorial, I would like to achieve the following:



DB, DB, Set up your DB.


This requires a bit of planning but let’s start of with the basic structure we need to see this through.

We are going to need a user table and a content table and are a few ways to tackle this.

If you’re using the PHPMyAdmin tool you can create your database, add user permissions (Click on Permissions after creating your database), and create a table with ease.



If you’re like me and prefer to look at good ‘ol SQL then writing an SQL statement is the preferred approach.


CREATE TABLE <code>mydbname</code>.<code>content</code> ( <code>ID</code> INT(11) NOT NULL AUTO_INCREMENT , <code>title</code> VARCHAR(100) NOT NULL , <code>content</code> LONGTEXT NOT NULL , <code>author</code> VARCHAR(50) NOT NULL , PRIMARY KEY (<code>ID</code>)) ENGINE = MyISAM COMMENT = 'content table';


Understanding the SQL statement

In a nutshell we are creating a table with important fields. Namely:

####

ID | Title | Content | Author

#######

The ID field is our unique identifier.Now we can move on to the file structure.

Everything has a place in the file structure game


You can use a structure that speaks to your coding style / memory.

I tend to use the following:



Choose a name for your CMS, which should be placed at the webroot of your localhost/server.

Replicate the folder structure as per the above example.

Next, we’re going to create a basic connection file.


You can create a conn.php file in your root/includes folder.

The connection file will provide crucial information to connect to the database.

Type the following into your conn.php file, remember to include your own database credentials.


<?php

$letsconnect = new mysqli("localhost","dbuser","dbpass","dbname");

?>


Let’s go to the homepage (index.php)


Create a file called index.php at the root of your CMS folder.

I will be adding comments in my code to help you understand what each line does.

Comments are a useful tool for developers to add important notes private to their code.

We need to pull information from the database so it’s imperative that we include our connection file.


<?php

include('includes/conn.php');

if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;

}else{

$getmydata=$letsconnect -> query("SELECT * FROM content");

foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";

}

}

$letsconnect -> close();

?>


Let’s get a (very) basic backend up and running


Create a file called index.php in your backend folder.

We need to create a basic form to capture our data.

Let’s code some HTML!


<html>

<head><title>Backend - Capture Content</title></head>

<body>

<form action="<?php $_SERVER[‘PHP_SELF’];?>" method="post">

<input type="text" name="title" placeholder="Content Title here" required/>

<textarea name="content">Content Here</textarea>

<input type="text" name="author" placeholder="Author" required/>

<input type="submit" value="Save My Data" name="savedata"/>

</form>

</body>

</html>


Next, we need to process the form data.


Type the following just above the
<form> 
tag.


<?php

if(isset($_POST['savedata'])){

include('../includes/conn.php');

if ($letsconnect->connect_error) {

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

}else{

$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";

if (mysqli_query($letsconnect, $sql)) {

echo "Your data was saved successfully!";

} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);

} $letsconnect->close();

}

}

?>


Note, this is a basic MySQL query to insert data. However, before using this in production it's important to add proper escaping and security to prevent SQL injections. This will be covered in the next article.


Congrats you made it to the end of tutorial 1!


Test out your creation, modify your content, and play around.

Go to your sitename/index.php to see your frontend after capturing data via sitename/backend/index.php

Next Up:


codewithme Now With Security, Functionality, and Aesthetics in mind.


Conclusion


Coding doesn’t have to be daunting and it’s my aim to divide a complex system into bitesized tutorials so you can truly use the knowledge you’ve acquired in your own projects.
26258 views · 4 years ago
Introduction to Gitlab CI for PHP developers
As a developer, you've probably at least heard something about CI - Continuous integration. And if you haven't - you better fix it ASAP, because that's something awesome to have on your skill list and can get extremely helpful in your everyday work. This post will focus on CI for PHP devs, and specifically, on CI implementation from Gitlab. I will suppose you know the basics of Git, PHP, PHPUnit, Docker and unix shell. Intended audience - intermediate PHP devs.
Adding something to your workflow must serve a purpose. In this case the goal is to automate routine tasks and achieve better quality control. Even a basic PHP project IMO needs the following:
* linter) checks (cannot merge changes that are invalid on the syntax level)
* Code style checks
* Unit and integration tests
All of those can be just run eventually, of course. But I prefer an automated CI approach even in my personal projects because it leads to a higher level of discipline, you simply can't avoid following a set of rules that you've developed. Also, it reduces a risk of releasing a bug or regression, thus improving quality.
Gitlab is as generous as giving you their CI for free, even for your private repos. At this point it is starting to look as advertising, therefore a quick comparison table for Gitlab, Github, Bitbucket. AFAIK, Github does not have a built-in solution, instead it is easily integrated with third parties, of which Travis CI seems to be the most popular - I will therefore mention Travis here.

Public repositories (OSS projects). All 3 providers have a free offer for the open-source community!


| Provider | Limits |
|---|---|
| Gitlab | 2,000 CI pipeline minutes per group per month, shared runners |
| Travis | Apparently unlimited |
| Bitbucket| 50 min/month, max 5 users, File storage <= 1Gb/month |

Private repositories


| Provider | Price | Limits |
|---|---|---|
| Gitlab | Free | 2,000 CI pipeline minutes per group per month, shared runners |
| Travis | $69/month | Unlimited builds, 1 job at a time |
| Bitbucket| Free | 50 min/month, max 5 users, File storage <= 1Gb/month |

Getting started

I made a small project based on Laravel framework and called it "ci-showcase". I work in Linux environment, and the commands I use in the examples, are for linux shell. They should be pretty much the same on Mac and nearly the same on Windows though.
composer create-project laravel/laravel ci-showcase

Next, I went to gitlab website and created a new public project: https://gitlab.com/crocodile2u/ci-showcase. Cloned the repo and copied all files and folders from the newly created project - the the new git repo. In the root folder, I placed a .gitignore file:
.idea
vendor
.env

Then the .env file:
APP_ENV=development

Then I generated the application encryption key: php artisan key:generate, and then I wanted to verify that the primary setup works as expected: ./vendor/bin/phpunit, which produced the output OK (2 tests, 2 assertions). Nice, time to commit this: git commit &amp;&amp; git push

At this point, we don't yet have any CI, let's do something about it!

Adding .gitlab-ci.yml

Everyone going to implement CI with Gitlab, is strongly encouraged to bookmark this page: https://docs.gitlab.com/ee/ci/README.html. I will simply provide a short introduction course here plus a bit of boilerplate code to get you started easier.
First QA check that we're going to add is PHP syntax check. PHP has a built-in linter, which you can invoke like this: php -l my-file.php. This is what we're going to use. Because the php -l command doesn't support multiple files as arguments, I've written a small wrapper shell script and saved it to ci/linter.sh:
#!/bin/sh
files=<code>sh ci/get-changed-php-files.sh | xargs</code>last_status=0
status=0
# Loop through changed PHP files and run php -l on each
for f in "$files" ; do message=<code>php -l $f</code> last_status="$?" if [ "$last_status" -ne "0" ]; then # Anything fails -> the whole thing fails echo "PHP Linter is not happy about $f: $message" status="$last_status" fi
done
if [ "$status" -ne "0" ]; then echo "PHP syntax validation failed!"
fi
exit $status

Most of the time, you don't actually want to check each and every PHP file that you have. Instead, it's better to check only those files that have been changed. The Gitlab pipeline runs on every push to the repository, and there is a way to know which PHP files have been changed. Here's a simple script, meet ci/get-changed-php-files.sh:
#!/bin/sh
# What's happening here?
#
# 1. We get names and statuses of files that differ in current branch from their state in origin/master.
# These come in form (multiline)
# 2. The output from git diff is filtered by unix grep utility, we only need files with names ending in .php
# 3. One more filter: filter *out* (grep -v) all lines starting with R or D.
# D means "deleted", R means "renamed"
# 4. The filtered status-name list is passed on to awk command, which is instructed to take only the 2nd part
# of every line, thus just the filename
git diff --name-status origin/master | grep '\.php$' | grep -v "^[RD]" | awk '{ print }'

These scripts can easily be tested in your local environment ( at least if you have a Linux machine, that is ;-) ).
Now, as we have our first check, we'll finally create our .gitlab-ci.yml. This is where your pipeline is declared using YAML notation:
# we're using this beautiful tool for our pipeline: https://github.com/jakzal/phpqa
image: jakzal/phpqa:alpine
# For this sample pipeline, we'll only have 1 stage, in real-world you would like to also add at least "deploy"
stages: - QA
linter:
stage: QA
# this is the main part: what is actually executed
script: - sh ci/get-changed-php-files.sh | xargs sh ci/linter.sh

The first line is image: jakzal/phpqa:alpine and it's telling Gitlab that we want to run our pipeline using a PHP-QA utility by jakzal. It is a docker image containing PHP and a huge variety of QA-tools. We declare one stage - QA, and this stage by now has just a single job named linter. Every job can have it's own docker image, but we don't need that for the purpose of this tutorial. Our project reaches Step 2. Once I had pushed these changes, I immediately went to the project's CI/CD page. Aaaand.... the pipeline was already running! I clicked on the linter job and saw the following happy green output:
Running with gitlab-runner 11.9.0-rc2 (227934c0) on docker-auto-scale ed2dce3a
Using Docker executor with image jakzal/phpqa:alpine ...
Pulling docker image jakzal/phpqa:alpine ...
Using docker image sha256:12bab06185e59387a4bf9f6054e0de9e0d5394ef6400718332c272be8956218f for jakzal/phpqa:alpine ...
Running on runner-ed2dce3a-project-11318734-concurrent-0 via runner-ed2dce3a-srm-1552606379-07370f92...
Initialized empty Git repository in /builds/crocodile2u/ci-showcase/.git/
Fetching changes...
Created fresh repository.
From https://gitlab.com/crocodile2u/ci-showcase * [new branch] master -> origin/master * [new branch] step-1 -> origin/step-1 * [new branch] step-2 -> origin/step-2
Checking out 1651a4e3 as step-2...
Skipping Git submodules setup
$ sh ci/get-changed-php-files.sh | xargs sh ci/linter.sh
Job succeeded

It means that our pipeline was successfully created and run!

PHP Code Sniffer.

PHP Code Sniffer is a tool for keeping app of your PHP files in one uniform code style. It has a hell of customizations and settings, but here we will only perform simple check for compatibilty with PSR-2 standard. A good practice is to create a configuration XML file in your project. I will put it in the root folder. Code sniffer can use a few file names, of which I prefer phpcs.xml:
<?xml version="1.0"?>
/resources

I also will append another section to .gitlab-ci.yml:
code-style:	stage: QA	script:	# Variable $files will contain the list of PHP files that have changes	- files=<code>sh ci/get-changed-php-files.sh</code> # If this list is not empty, we execute the phpcs command on all of them - if [ ! -z "$files" ]; then echo $files | xargs phpcs; fi

Again, we check only those PHP files that differ from master branch, and pass their names to phpcs utility. That's it, Step 3 is finished! If you go to see the pipeline now, you will notice that linter and code-style jobs run in parallel.

Adding PHPUnit

Unit and integration tests are essential for a successful and maintaiable modern software project. In PHP world, PHPUnit is de facto standard for these purposes. The PHPQA docker image already has PHPUnit, but that's not enough. Our project is based on Laravel, which means it depends on a bunch of third-party libraries, Laravel itself being one of them. Those are installed into vendor folder with composer. You might have noticed that our .gitignore file has vendor folder as one of it entries, which means that it is not managed by the Version Control System. Some prefer their dependencies to be part of their Git repository, I prefer to have only the composer.json declarations in Git. Makes the repo much much smaller than the other way round, also makes it easy to avoid bloating your production builds with libraries only needed for development.
Composer is also included into PHPQA docker image, and we can enrich our .gitlab-ci.yml:
test:	stage: QA	cache:	key: dependencies-including-dev	paths: - vendor/	script:	- composer install	- ./vendor/bin/phpunit

PHPUnit requires some configuration, but in the very beginning we used composer create-project to create our project boilerplate.laravel/laravel package has a lot of things included in it, and phpunit.xml is also one of them. All I had to do was to add another line to it:
xml

APP_KEY enironment variable is essential for Laravel to run, so I generated a key with php artisan key:generate.
git commit & git push, and we have all three jobs on theQA stage!

Checking that our checks work

In this branch I intentionally added changes that should fail all three job in our pipeline, take a look at git diff. And we have this out from the pipeline stages:Linter:
$ ci/linter.sh
PHP Linter is not happy about app/User.php:
Parse error: syntax error, unexpected 'syntax' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in app/User.php on line 11
Errors parsing app/User.php
PHP syntax validation failed!
ERROR: Job failed: exit code 255

**Code-style**:
$ if [ ! -z "$files" ]; then echo $files | xargs phpcs; fi
FILE: ...ilds/crocodile2u/ci-showcase/app/Http/Controllers/Controller.php
----------------------------------------------------------------------
FOUND 0 ERRORS AND 1 WARNING AFFECTING 1 LINE
---------------------------------------------------------------------- 13 | WARNING | Line exceeds 120 characters; contains 129 characters
----------------------------------------------------------------------
Time: 39ms; Memory: 6MB
ERROR: Job failed: exit code 123

**test**:
$ ./vendor/bin/phpunit
PHPUnit 7.5.6 by Sebastian Bergmann and contributors.
F. 2 / 2 (100%)
Time: 102 ms, Memory: 14.00 MB
There was 1 failure:
1) Tests\Unit\ExampleTest::testBasicTest
This test is now failing
Failed asserting that false is true.
/builds/crocodile2u/ci-showcase/tests/Unit/ExampleTest.php:17
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
ERROR: Job failed: exit code 1

Congratulations, our pipeline is running, and we now have much less chance of messing up the result of our work.

Conclusion

Now you know how to set up a basic QA pipeline for your PHP project. There's still a lot to learn. Pipeline is a powerful tool. For instance, it can make deployments to different environments for you. Or it can build docker images, store artifacts and more! Sounds cool? Then spend 5 minutes of your time and leave a comment, you can also tell me if there is a pipeline topic you would like to be covered in next posts.

SPONSORS

The Ultimate Managed Hosting Platform