PHP & Web Development Blogs

Search Results For: simple
Showing 1 to 5 of 23 blog articles.
17710 views · 5 years ago
Creating a Virus with PHP

In his talk, “Writing Viruses for Fun, Not Profit,”Ben Dechrai (after making the viewer take a pledge to only use this knowledge for good and not evil) walks through how many viruses operate, and just how easy it is to build your own self-replicating virus in PHP.

The danger of many of these viruses according to Ben is that the most dangerous viruses often escape detection by not looking like a virus. Instead they encrypt their code to hide their true intent, while also constantly adapting and evolving.

Perhaps even more dangerously, they act like they’re benign and don’t actually do anything - often times laying dormant until called upon by the malicious actor.

Creating the Virus

What’s scary is just how simple it was for Ben to create such a virus, one that mutated ever so slightly as it infected every other file on the server. Opening up unlimited possibilities from scraping customer data, to DDOS attacks, to simply hijacking your domain.



But those attacks are just the start as Ben demonstrated how easy it is to write new files, delete files, eval() and execute foreign code - which could even be extended to accessing the underlying server itself if shell_exec() is enabled.

To add to the problem, Ben shares how challenging it can be to identify malicious code on your server as many of these attacks are far more sophisticated than the the virus he created in a matter of minutes - hiding themselves and often appearing as if they are part of the original source code.

Deploying the Virus

To drive his point home, Ben demonstrates how even seemingly secure systems can be vulnerable - as all it takes is one tiny misstep within your application.

He highlights this by building what should be a secure photo gallery - one that checks the extension and mime-type of the image - and even stores it outside of the public directory. He goes even farther by adding additional sanity checks with a PHP script that then renders the image.

After walking through the code and it’s security features, he then downloads a simple image from the internet. Opening his editor he quickly injects the virus (written in PHP) into the image and uploads it, passing all of the server checks.

Surely, since it passed these checks the system is secure, right? Ben loads the gallery to proudly show off the image - which is just that… an image, with nothing special or out of the ordinary.
Except that when he opens the image gallery files, each has been infected with the malicious code.

The culprit that allowed for Ben to hijack an entire system and execute foreign code, create new files, and even hijack the entire site? When displaying the image the file was included using PHP’s include() function, instead of pulling in the data using file_get_contents() and echoing it out.

Such a simple mistake provided Ben, if he was a malicious hacker, complete access to all of the files on the system.

Protecting Yourself

Security always exists in layers - and this could have been prevented by including a few more layers, such as using an open source library to rewrite the image, reviewing the image source before pulling it in, or again not giving it executable access by using the PHP include() function.

But what’s terrifying is how simple it is to hijack a site, how easy it is to get access to your system and private data, and how easy it is to overlook security vulnerabilities - especially with open source tooling and those that take plugins.

As Ben explains, sometimes the core code itself is really secure, but then you get two different plugins that when used together accidentally create a security vulnerability. That by itself is one of the most challenging as you can audit each plugin individually, and still not know you’re opening up your system to malicious actors.

This is why it's not just important to stay up to date on the latest security measures and best practices, but to be constantly thinking like a hacker and testing your code for vulnerabilities.

Learn More

You can watch thefull video to learn more how viruses operate, how to quickly build your own PHP virus (but you must promise to use it for good), and what to watch for in order to protect yourself, your customers, and your architecture.
13914 views · 5 years ago
Laravel Eloquent Relationship Part 1

Laravel introduces eloquent relationships from laravel 5.0 onwards. We all know, while we creating an application we all have foreign keys. Each table will be connected to some other. Eloquent make easy to connect each tables easily. Here we will One to one, one to many and many to many relationships. Here we will see three types of relationships,
   
. One to one relationships
    . One to many relationships
    . Many to many relationships

Why Eloquent Relationships

Here we have 2 tables, students and marks, so for join each table,

$student = student::join(‘marks’,’marks.student_id,’=’,students.id’)->where(‘students.id’,’1’)->get();

dd($student);



the above query is to long, so when we connect more tables its too tough we will be having a big query and complicated.



Model Query using Relationships


$student_marks = student::find(1);

dd($student_marks->mark1);



The above example is a simple example of eloquent relationships. We can reduce the first query into a simple one.





ONE TO ONE RELATIOSHIPS

Here we are creating 2 tables:
* Users
* Phones

Now we can see one to one relationships using hasone() and belongsto().

We need to create table using migrations



Create migrations


users table will be created by using


Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});


Phones table will be created by


Schema::create('phones', function (Blueprint $table) {

$table->increments('id');

$table->integer('user_id')->unsigned();

$table->string('phone');

$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

});



After that we need to create model for each tables, as we all know if the table name is laravel table name will be ending with ‘s’ and model name will be without ‘s’ of the same table name.



User model



<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;



class User extends Authenticatable

{

use Notifiable;





protected $fillable = [

'name', 'email', 'password',

];





protected $hidden = [

'password', 'remember_token',

];





public function phone()

{

return $this->hasOne('App\Phone');

}

}



Phone Model



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Phone extends Model

{



public function user()

{

return $this->belongsTo('App\User');

}

}



For Creating records



$user = User::find(1);

$phone = new Phone;

$phone->phone = '9080054945';

$user->phone()->save($phone);



$phone = Phone::find(1);

$user = User::find(10);

$phone->user()->associate($user)->save();



Now we can get our records by


$phone = User::find(1)->phone;

dd($phone);



$user = Phone::find(1)->user;

dd($user);





ONE TO MANY RELATIONSHIPS

Here we will use hasMany() and belongsTo() for relationships

Now we are creating two tables, posts and comments, we will be having a foreign key towards posts table.


Migrations for posts and comments table


Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});



Schema::create('comments', function (Blueprint $table) {

$table->increments('id');

$table->integer('post_id')->unsigned();

$table->string("comment");

$table->timestamps();

$table->foreign('post_id')->references('id')->on('posts')

->onDelete('cascade');

});



Now we will create Post Model and Comment Model



Post Model



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Post extends Model

{



public function comments()

{

return $this->hasMany(Comment::class);

}

}



Comment Model



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Comment extends Model

{



public function post()

{

return $this->belongsTo(Post::class);

}

}



Now we can create records


$post = Post::find(1);

$comment = new Comment;

$comment->comment = "Hi Harikrishnan";

$post = $post->comments()->save($comment);

$post = Post::find(1);



$comment1 = new Comment;

$comment1->comment = "How are You?";

$comment2 = new Comment;

$comment2->comment = "Where are you?";

$post = $post->comments()->saveMany([$comment1, $comment2]);



$comment = Comment::find(1);

$post = Post::find(2);

$comment->post()->associate($post)->save();



Now we can get records


$post = Post::find(1);

$comments = $post->comments;

dd($comments);



$comment = Comment::find(1);

$post = $comment->post;

dd($post);



MANY TO MANY RELATIONSHIPS

Many to many is little bit different and complicated than the above two.



In this example, I will create users, roles, and role, users_tables, here each table will be connected each other using the foreign keys.



Using belongsToMany() we will use see a demo of Many to many relationship



Create Migrations



Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});



Schema::create('roles', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->timestamps();

});



Schema::create('role_user', function (Blueprint $table) {

$table->integer('user_id')->unsigned();

$table->integer('role_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

$table->foreign('role_id')->references('id')->on('roles')

->onDelete('cascade');

});



Create Models



User Model


<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;



class User extends Authenticatable

{

use Notifiable;





protected $fillable = [

'name', 'email', 'password',

];





protected $hidden = [

'password', 'remember_token',

];





public function roles()

{

return $this->belongsToMany(Role::class, 'role_user');

}

}


Role Model


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Role extends Model

{



public function users()

{

return $this->belongsToMany(User::class, 'role_user');

}

}


UserRole Model


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class UserRole extends Model

{

}



Now we can create records


$user = User::find(2); 

$roleIds = [1, 2];

$user->roles()->attach($roleIds);



$user = User::find(3);

$roleIds = [1, 2];

$user->roles()->sync($roleIds);



$role = Role::find(1);

$userIds = [10, 11];

$role->users()->attach($userIds);



$role = Role::find(2);

$userIds = [10, 11];

$role->users()->sync($userIds);



Now we can retrieve records


$user = User::find(1); 

dd($user->roles);



$role = Role::find(1);

dd($role->users);




Hence laravel Eloquent is more powerful and we do relationships easily compared to native query. We will be having three more relationships in laravel. Ie.., has many, one to many polymorphic and many to many polymorphic. With eloquent relationship we can easily connect the tables each other. One to one relationships we can connect two tables with their basic functionalities. In one to many we will connect with single table with multiple options. In Many to many we will be having more tables.
6002 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
5244 views · 3 years ago
Top 12 PHP Libraries to Leverage Your Web App Development



PHP, by all means, is an immensely powerful language!



We may fall short of words, but there won't come any end to its qualities. The endless functionalities and possibilities of this server-side scripting language have managed to get it a strong and supportive community of PHP programmers on a global level. At present, PHP powers more than half on websites and applications on the internet.


Do you know what makes PHP so praiseworthy?



It is the simplicity, easy programming structure, and developer-friendly web functionalities that are to be credited to turn PHP into one of the top programming languages. You can create highly interactive and dynamic websites and applications with desired results by making use of PHP.



However, coding often could be a tough and tedious task to accomplish. As a solution to this, you get built-in PHP libraries that optimize the process of coding for maximum productivity.



But what are these libraries?




That's exactly what you will find out as you move ahead in this article, a list of top 12 PHP libraries capable of leading the development process in an intended manner.



So, without waiting any further, let's move ahead to learn about PHP libraries in-depth.



PChart




PChart is a PHP library assisting with the generation of text data in the form of something more appealing to the eyes and known as visual charts.



You can use this library to represent data as bar charts, pie charts, and many more different formats. The PHP script here utilizes SQL queries to put data in the impressive charts or graphs form.



Mink




Another well-known in the list of PHP libraries is Mink. It allows you to keep an eye on if a proper interaction is happening between your web apps and the browser. Eliminating the API differences between the two types of browser emulators, Mink offers an authentic testing environment for you. It also supports PHPUnit, Behat, and Symfony2.



Monolog




Monolog is a PHP logging library that helps you with saving logs to the specified locations by sending them to set files, sockets, inboxes, databases, or other web services. The use of the PSR-3 interface permits to type-hint logs in counter to your libraries that maintain optimum interoperability.



Hoa




This modular, extensible, and structured set of PHP libraries we know as Hoa establishes a link between the research and the industry.



It recommends essential paradigms, mechanisms, and algorithms for building the reliability of a site. Many PHP developers in different parts of the world use Hoa for ideal PHP development.



Guzzle




Guzzle is an HTTP client library for PHP that enables you to send HTTP requests to combine with web services.



It offers a simple interface that makes the development of query strings, POST requests, HTTP cookies, and many other attributes possible. You can also use Guzzle to send synchronous and asynchronous requests from the similar interface.



Ratchet




If your need is to develop real-time, two-directional apps between clients and servers over WebSockets, Ratchet is the PHP library you need to do it effectively.



Creating event-driven apps with Ratchet is a rapid, simple, and easy job to do!



Geocoder




Geocoder is a library to create applications that are very well geo-aware.



With Geocoder, there is an abstraction layer that helps with geocoding manipulations.



It is further split into two parts, known as HttpAdapter and Provider.



ImageWorkshop




ImageWorkshop is an open-source PHP library letting you work over the manipulation of images with layers. You can crop, resize, add watermarks, create thumbnails, and so much more. You can also enhance the images on the sites.



PhpThumb




phpThumb is the library specialized at handling the work associated with creating thumbnails with minimal coding. Accepting every image source type and image formats, it makes you do a lot ranging from rotating or cropping to watermarking or defining the image quality.



Parody




This simple library we know as Parody is used to copy classes and objects. It also provides results for method calls, acquiring properties, instantiating objects, and more. Sequential method chaining is used by Parody to produce defining class structures.



Imagine




This object-oriented PHP library is meant for working with images along with manipulating them. The often adopted operations such as resizing, cropping, and applying filters happen instantly and relatively well with Imagine.



With Imagine, you get a color class that forms the RGB values of any given color. Draw shapes like arc, ellipse, line, etc. with the features available.



PhpFastCache




PhpFastCache is an open-source PHP library that makes caching feasible. Coming as a single-file, it can be integrated within a matter of minutes.



Caching methods supported by PhpFastCache involve apc, memcache, memcached, wincache, pdo, and mpdo.


The Bottom Line




It's not about what extra difference these libraries make; it's about what significant individual contributions these libraries make for a final desired PHP app or website.



A PHP programmer, too, agrees with these libraries' benefits.



It's your time now to try and believe!
4365 views · 3 years ago


People that visit your website face an invisible threat each time they log on. Small businesses are especially vulnerable to digital data breaches, and that can change the way your customers feel about you. But, although you cannot stop hackers from trying, there are things you can do as a business owner to make your website a safer experience for everyone. Keep reading for tips.

Mature digitally.


You may be ahead of the times when it comes to products and services, but, chances are, your website hasn't fully kept up. It's time to learn all you can about the internet and digital security. If you are already somewhat tech savvy, a PHP Security Course from Nomad PHP can help you better understand everything from cryptography to website error messages.

Adapting to today's digital environment means transforming your website to quickly and easily identify threats via machine learning and network monitoring. And, as Upwork explains, digital maturity not only keeps your website safe, but adopting this mindset can also increase your efficiency and accuracy by reducing human errors.

Understand the threats.


It is not enough to simply keep up with your website, you also have to understand the types of threats that are out there. You're likely familiar with ransomware and phishing, but, it's also a good idea to know how a website can get hacked. Your site's content management system and vulnerabilities within your operating system are all weak points that hackers can easily identify.

Insist on security measures.


When customers log into your website, they input their credentials. Each time they do so, you can best protect their information by keeping your systems up to date. You'll also want to ensure that your site is hosted on a secure service and that you have an SSL certificate installed.

If you are not already, have your IT department or managed IT services perform regular website security checks. PhoenixNAP, an IT services provider, notes that those websites working via WordPress should also be safely outfitted with the most recent security plug-ins.

Eliminate spam.


If your website allows for comments that are not manually approved, anyone on the internet can post. This leaves it open for hackers and other unscrupulous individuals to comment with spam and malicious links that your customers may inadvertently click on. While many of these simply exist as a way for the commenter to drive traffic to another website, others are designed to draw your readers' attention, gain their trust, and access their personal information.

Prioritize passwords.


Your customers' passwords are the keys by which they open the door to your website. Unfortunately, many people do not treat them with as much care as they do the keys they use in the non-digital world.

It's true, passwords can be a pain, but you are not doing yourself or your customers any favors by allowing simple one-word passcodes to access your site. Instead, design your site to require a strong password. How-To Geek asserts that this will have a minimum of 12 characters and include a combination of upper and lower case letters, symbols, and numbers.

While you will likely rely on your IT experts to secure your website, the truth is that it is ultimately up to you to ensure this is done. So even if you are not a digital mastermind, knowing all you can about web security can help you be a better business owner. Your customers will be safer, and a secure website is just one way to strengthen your business's online presence and keep up with today's -- and tomorrow's -- technology.

SPONSORS

PHP Tutorials and Videos