PHP & Web Development Blogs

Search Results For: application
Showing 1 to 5 of 30 blog articles.
17711 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.
4740 views · 3 years ago
Why I joined Nomad PHP
I've been using PHP since 1996. I've been paid to use PHP for the last 12 years.

I am a big fan of the language and it's amazing to see just how much it's changed in the last 24 years.

I finally joined NomadPHP because in the current climate, I feel like I need to give back to the community, and share some of the things that I've learned over the years.


In my current role, I’m working with a large pool of developers from many different backgrounds and skill levels to maintain a large pool of php based tools for a web hosting company.

These tools range from in house tools for support and sales, to customer facing tools for automation and quality of life applications.

I’m a big fan of frameworks, specifically Laravel. I discovered Laravel 4.0, decided to give it a try and immediately realized how valuable it could be as a way to prototype quickly. It has since grown to a tool in my toolbox I use regularly for medium and small applications simply as a time saver.

Please feel free to reach out to me if you have any questions, or what to pick my brain. I can’t promise I know it all, but over the years I’ve learned how to solve problems and find answers.

Thank you, and I look forward to what may come.

Chris.
8976 views · 4 years ago
When PHP Frameworks Suck

INTRO

If you are working as a PHP software developer, there is an extremely high chance that all of your application, you’re currently working on, using frameworks of any kind.
PHP community developers of all levels worship frameworks since there are big historical and practical reasons for that.

Historical reasons

Since early PHP versions, developers were disreputable because not everybody considered PHP as a programming language, similar to JavaScript a couple of years ago. While strong type language existed decades ago, PHP continues to be soft type since now, only in version 7 basic types were introduced. There is also a matter of the fact that you can script in PHP without using a single object.

But that opened a space for frameworks to step in and introduce themselves as a tool or standard which will shape projects, give them right and order, introduce structure and rules.
And finally, they did. Frameworks are good examples of nice structures, using all available new features PHP offers with every version, enforcing some good practice, etc.

Practical reasons

The framework offers a lot of common problems already solved. They offer a nice ecosystem for other developers to contribute and plug their components. There is a lot of online resources for learning and stay updated about any particular framework. Also, what every framework community tries very hard, is to make setup and usage easy.

WHEN PHP FRAMEWORKS SUCKS

I recently had the opportunity to give a talk on a conference and one meetup about why PHP framework sometimes sucks. Sometimes things we see in framework tutorials does not seem to be very much aligned with some object-oriented standards we are striving to enforce, and with basic clean code guidelines. On the other hand, there is nothing wrong with using a framework, if you use it right.

This article is the first "pilot" article in this series. In every new blog in this series, we will go more in-depth about every specific topic I covered during my presentation.
I'm very excited to share this knowledge, as I saw many developers suffer from bonded-to-framework disease.

https://twitter.com/damnjan/status/1058306144458956800

I won’t spend much time here on any particular framework discussion. This series will be just a guide on how to unbind yourself from frameworks and use them as a tool, instead of being independent.

**Here is the link to the presentation slides.**
36853 views · 4 years ago
Securing PHP RESTful APIs using Firebase JWT Library

Hello Guys,

In our Last Blog Post, we have created restful apis,But not worked on its security and authentication. Login api can be public but after login apis should be authenticate using any secure token. one of them is JWT, So i am providing the Steps for Create and use JWT Token in our already created API.


Now its time To Implement JWT Authentication IN our Api, So these are the steps to implement it in our already created Apis


Step 1:Install and include Firebase JWT(JSON WEB TOKEN) in our project with following composer command        


 composer require firebase/php-jwt 


include the composer installed packages
require_once('vendor/autoload.php');


use namespace using following:
 use \Firebase\JWT\JWT; 



Step 2: Create a JWT server side using Firebase Jwt Library's encode method in Login action , and return it to Client



Define a private variable named Secret_Key in Class like following:

 private {
$payload = array(
'iss' => $_SERVER['HOST_NAME'],
'exp' => time()+600, 'uId' => $UiD
);
try{
$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); $res=array("status"=>true,"Token"=>$jwt);
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;
}


In our login action , if the user has been logged in successfully then with the status,_data_ and message just replace the login success code with following code:

$return['status']=1;
$return['_data_']=$UserData[0];
$return['message']='User Logged in Successfully.';

$jwt=$obj->generateToken($UserData[0]['id']);
if($jwt['status']==true)
{
$return['JWT']=$jwt['Token'];
}
else{
unset($return['_data_']);
$return['status']=0;
$return['message']='Error:'.$jwt['Error'];
}





Step 3: Now with every request after login should have the JWT token in its Post(even we can receive it in get or authentication header also but here we are receiving it in post)



No afetr successfully login you will get the JWt Token in your response,Just add that Token with every post request of after login api calls. So we will do it using postman, Find the screenshot 1 for checking the JWT Token is coming in login api response

JWT DEMO LOGIN API RESPONSE


Step 4:After reciving the JWt in every after login api call, we need to check whether the token is fine using JWT decode method in After login Apis like
UserBlogs
is a After login Api, So for verify that we are creating Authencate method in class like following:


 public function Authenticate($JWT,$Curret_User_id)
{
try {
$decoded = JWT::decode($JWT,$this->Secret_Key, array('HS256'));
$payload = json_decode(json_encode($decoded),true);

if($payload['uId'] == $Curret_User_id) {
$res=array("status"=>true);
}else{
$res=array("status"=>false,"Error"=>"Invalid Token or Token Exipred, So Please login Again!");
}
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;

}


Step 5: Cross check the response returned by Authenticate method in
UserBlogs
Action of api , replace the
UserBlogs
Action inner content with following code:


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

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);
if($resp['status']==false)
{
$return['status']=0;
$return['message']='Error:'.$resp['Error'];
}
else{
$blogs=$obj->get_all_blogs($_POST['Uid']);
if(count($blogs)>0)
{
$return['status']=1;
$return['_data_']=$blogs;
$return['message']='Success.';
}
else
{
$return['status']=0;
$return['message']='Error:Invalid UserId!';
}
}
}
else
{
$return['status']=0;
$return['message']='Error:User Id not provided!';
}


Ah great its time to check out the UserBlogs Api, please find the screenshoot for that, Remember we need to put the JWt Token in POST Parameter as we have already recived that Value in Login Api call.

JWT DEMO Authentication in userBlogs API Call

Now if you want to verify that token is expiring in given time(10 minutes after generation time/login time), i am just clicking the same api with same token after 10 minutes and you can see there will not return any data and it is returning status false with following message :


JWT DEMO Authentication in userBlogs API Call


Also if you want to eloborate it more then i suggest you to try with modify Uid value with same token , you will another authentication issue and also if you modify the JWT token also then also you will not get the desired result and get authentication Issue

Thanks for reading out if you want the complete code of this file then please find following:
<?php 
header("Content-Type: application/json; charset=UTF-8");
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;

class DBClass {

private $host = "localhost";
private $username = "root";
private $password = ""; private $database = "news";

public $connection;

private $Secret_Key="*$%43MVKJTKMN$#";
public function connect(){

$this->connection = null;

try{
$this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);
$this->connection->exec("set names utf8");
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}

return $this->connection;
}

public function login($email,$password){

if($this->connection==null)
{
$this->connect();
}

$query = "SELECT id,name,email,createdAt,updatedAt from users where email= ? and password= ?";
$stmt = $this->connection->prepare($query);
$stmt->execute(array($email,md5($password)));
$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);
return $ret;
}

public function get_all_blogs($Uid){

if($this->connection==null)
{
$this->connect();
}

$query = "SELECT b.*,u.id as Uid,u.email as Uemail,u.name as Uname from blogs b join users u on u.id=b.user_id where b.user_id= ?";
$stmt = $this->connection->prepare($query);
$stmt->execute(array($Uid));
$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);
return $ret;
}

public function response($array)
{
echo json_encode($array);
exit;
}

public function generateToken($UiD)
{
$payload = array(
'iss' => $_SERVER['HOST_NAME'],
'exp' => time()+600, 'uId' => $UiD
);
try{
$jwt = JWT::encode($payload, $this->Secret_Key,'HS256'); $res=array("status"=>true,"Token"=>$jwt);
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;
}

public function Authenticate($JWT,$Current_User_id)
{
try {
$decoded = JWT::decode($JWT,$this->Secret_Key, array('HS256'));
$payload = json_decode(json_encode($decoded),true);

if($payload['uId'] == $Current_User_id) {
$res=array("status"=>true);
}else{
$res=array("status"=>false,"Error"=>"Invalid Token or Token Exipred, So Please login Again!");
}
}catch (UnexpectedValueException $e) {
$res=array("status"=>false,"Error"=>$e->getMessage());
}
return $res;

}
}

$return=array();
$obj = new DBClass();
if(isset($_GET['action']) && $_GET['action']!='')
{
if($_GET['action']=="login")
{
if(isset($_POST['email']) && isset($_POST['password']))
{
$UserData=$obj->login($_POST['email'],$_POST['password']);
if(count($UserData)>0)
{
$return['status']=1;
$return['_data_']=$UserData[0];
$return['message']='User Logged in Successfully.';

$jwt=$obj->generateToken($UserData[0]['id']);
if($jwt['status']==true)
{
$return['JWT']=$jwt['Token'];
}
else{
unset($return['_data_']);
$return['status']=0;
$return['message']='Error:'.$jwt['Error'];
}

}
else
{
$return['status']=0;
$return['message']='Error:Invalid Email or Password!';
}
}
else
{
$return['status']=0;
$return['message']='Error:Email or Password not provided!';
}
}
elseif($_GET['action']=="UserBlogs")
{
if(isset($_POST['Uid']))
{

$resp=$obj->Authenticate($_POST['JWT'],$_POST['Uid']);
if($resp['status']==false)
{
$return['status']=0;
$return['message']='Error:'.$resp['Error'];
}
else{
$blogs=$obj->get_all_blogs($_POST['Uid']);
if(count($blogs)>0)
{
$return['status']=1;
$return['_data_']=$blogs;
$return['message']='Success.';
}
else
{
$return['status']=0;
$return['message']='Error:Invalid UserId!';
}
}
}
else
{
$return['status']=0;
$return['message']='Error:User Id not provided!';
}
}
}
else
{
$return['status']=0;
$return['message']='Error:Action not provided!';
}
$obj->response($return);
$obj->connection=null;
?>

1592 views · 8 months ago


Introduction


MongoDB, a popular NoSQL database, provides flexibility and scalability for modern web applications. In this guide, we will explore how to use MongoDB with PHP, a widely used scripting language. We'll cover the necessary steps to establish a connection, perform CRUD operations, and leverage the power of MongoDB in your PHP projects.

Prerequisites


Before diving into MongoDB integration, ensure you have the following:
   
. MongoDB installed and running on your machine.
   
. PHP installed on your machine, preferably version 7 or above.
   
. Composer, a dependency management tool for PHP.

Step 1: Installing the MongoDB PHP Driver


The first step is to install the MongoDB PHP driver, which enables PHP to communicate with MongoDB. We can use Composer to handle the installation process efficiently. Open your terminal or command prompt and navigate to your project directory. Then run the following command:


composer require mongodb/mongodb


This command installs the MongoDB PHP driver along with its dependencies. Composer will create a vendor directory containing the required files.

Step 2: Establishing a Connection


To connect to MongoDB from PHP, we need to create a new instance of the MongoDB client class. Open your code editor and create a new PHP file, for example, connect.php. Add the following code:


<?php

require 'vendor/autoload.php';

use MongoDB\Client;

$client = new Client("mongodb://localhost:27017");

?>


In this code, we require the Composer-generated autoloader and import the Client class. We then create a new instance of the Client class, specifying the MongoDB server's connection URL. Adjust the URL if your MongoDB server is running on a different host or port.

Step 3: Performing CRUD Operations


Now that we have established a connection, let's explore how to perform basic CRUD operations using MongoDB with PHP.

Creating Documents


To insert a new document into a MongoDB collection, use the insertOne() method. Here's an example:

<?php
$collection = $client->test->users;

$newUser = [
'name' => 'John',
'email' => '[email protected]',
'age' => 25
];

$insertResult = $collection->insertOne($newUser);
echo "Inserted document ID: " . $insertResult->getInsertedId();
?>


In this code, we select the users collection within the test database. We create a new document as an associative array and then use the insertOne() method to insert it into the collection. Finally, we retrieve and display the ID of the inserted document using the getInsertedId() method.

Reading Documents


To retrieve documents from a MongoDB collection, use the find() method. Here's an example:

<?php
$collection = $client->test->users;

$documents = $collection->find();

foreach ($documents as $document) {
echo $document['name'] . ': ' . $document['email'] . "\n";
}
?>


In this code, we retrieve all the documents from the users collection. We iterate over the result using a foreach loop and access specific fields, such as the name and email, to display their values.

Updating Documents


To update documents in a MongoDB collection, use the updateOne() method. Here's an example:

<?php
$collection = $client->test->users;

$updateResult = $collection->updateOne(
['name' => 'John'],
['$set' => ['age' => 30]]
);

echo "Modified " . $updateResult->getModifiedCount() . " document(s).";
?>


In this code, we update the age field of the document with the name 'John' using the $set operator. The updateOne() method updates the first matching document. We then retrieve the number of modified documents using the getModifiedCount() method.

Deleting Documents


To remove documents from a MongoDB collection, use the deleteOne() method. Here's an example:

<?php
$collection = $client->test->users;

$deleteResult = $collection->deleteOne(['name' => 'John']);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s).";
?>


In this code, we delete the document with the name 'John'. The deleteOne() method removes the first matching document, and we retrieve the number of deleted documents using the getDeletedCount() method.

Conclusion


Congratulations! You have learned the basics of using MongoDB with PHP. By establishing a connection, performing CRUD operations, and leveraging the power of MongoDB, you can build powerful and scalable web applications. Remember to refer to the MongoDB PHP documentation for additional features and advanced usage.

SPONSORS