PHP & Web Development Blogs

Search Results For: creating
Showing 1 to 5 of 24 blog articles.
17863 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.
1651 views · 9 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.
4618 views · 5 years ago
PHP Basics

It's 2018, and you're a top-notch modern web developer, with a load of knowledge and tools right there at your disposal: Google and StackOverflow, debugger with a GUI, IDE with autocomplete, you name it. Occasionally, though, you still find yourself in a plain old text console on a remote server, or you have to do something without IDE, or there is no network connection... In such cases it might be helpful to feel comfortable in a simple terminal. In this post I'm going to list some switches for the PHP command that you can use to get information and some utilities.

Getting basic information about PHP


$ php -i
phpinfo()
PHP Version => 7.2.10-0ubuntu1

System => Linux awesome 4.18.0-10-generic #11-Ubuntu SMP Thu Oct 11 15:13:55 UTC 2018 x86_64
Build Date => Sep 13 2018 13:38:55
Server API => Command Line Interface
Virtual Directory Support => disabled
...


Full information about your PHP interpreter. Pipe the output to the Unix less command in order to get pagination and search: php -i | less. Type Q to exit the less shell. Some distros might lack less, in that case you may try php -i | more, which doesn't give you search but still has pagination.

Want a short summary of which PHP extensions you have? Just ask:

$ php -m
[PHP Modules]
calendar
Core
ctype
date
dom
ds
exif
...


More specific info about core and extensions' functions and classes


Full information about functions and classes provided by an extension:

$ php --re ds
Extension [ <persistent> extension #46 ds version 1.2.6 ] {

- Dependencies {
Dependency [ json (Required) ]
Dependency [ spl (Required) ]
}

- Classes [11] {
Interface [ <internal:ds> interface Ds\Hashable ] {

- Constants [0] {
}

- Static properties [0] {
}
...


Information on a specific class:

$ php --rc Ds\Vector
Class [ <internal:ds> <iterateable> final class Ds\Vector implements Ds\Sequence, Traversable, Countable, JsonSerializable, Ds\Collection ] {

- Constants [1] {
Constant [ public integer MIN_CAPACITY ] { 8 }
}

- Static properties [0] {
}
...


Same for a function:

$ php --rf fopen
Function [ <internal:standard> function fopen ] {

- Parameters [4] {
Parameter #0 [ <required> $filename ]
Parameter #1 [ <required> $mode ]
Parameter #2 [ <optional> $use_include_path ]
Parameter #3 [ <optional> $context ]
}
}


Utilities


Ever found yourself creating a dummy PHP file of just a few lines - only to be run once and then deleted? The -a switch might be what you're looking for:

$ php -a
Interactive mode enabled

php > var_dump(join(", ", [1, 2, 3]));
php shell code:1:
string(7) "1, 2, 3"
php >


It starts an interactive shell so you can type any PHP code and execute it straight away. Requires PHP to be compiled with readline support (most distros have that anyway).

Want a quick check for any parse/syntax errors in a PHP file? Use linter:

$ php -l test.php 
PHP Parse error: syntax error, unexpected 'array_shift' (T_STRING) in test.php on line 4
Errors parsing test.php


It has a web-server!


Yes! Just in case you missed it, as of PHP 5.4.0, the CLI SAPI provides a built-in web server. Want a quick look at a web page generated by an app? Here you go:

$ cd /my_application/document_root
$ php -S localhost:8000


Then open http://localhost:8000/ in your browser of choice and enjoy!

Hope you also have enjoyed this reading. Your feedback and questions are always appreciated!
5503 views · 2 years ago
Create your first PHP app

PHP is an incredibly powerful programming languaage, one that powers roughly 80% of the web! But it's also one of the easier languages to learn as you can see your changes in real time, without having to compile or wait for the code to repackage your app or website.

Defining a PHP script


To get started, create a file called "myfirstpage.php." You can actually call it anything you'd like, but the important part here is the extension: .php. This tells the server to treat this page as a PHP script.

Now let's go ahead and create a basic HTML page:


<html>

<head>

<title>Hello</title>

</head>

<body>

Hello

</body>

</html>


Go ahead and save your page and upload it to any host that supports PHP. Now visit your page and you should see a page that outputs "Hello."

Echo content


Now let's add some PHP code to our script. To signal the server to render PHP code we first open with the <?php tag, then we write our PHP code, and finally close it with the ?> tag. This is important as if we were creating an XML file and forgot to escape the opening XML tag which also has a question mark, we would run into a fatal error.

Now let's write some PHP code that tells the server to echo specific output. To echo or print the content on the page we can use the echo statement in our PHP code by placing the text we want to echo in single quotes and then end the command with a semi colon. Let's echo out "there!":


<html>

<head>

<title>Hello</title>

</head>

<body>

Hello <?php echo 'there!'; ?>

</body>

</html>


Now upload your script and test it on your webhost. You should now see "Hello there!" on your screen. Now this isn't as exciting since we could do the same thing in HTML without PHP, so let's create dynamic content based on the URL string.

Using $_GET

PHP allows you to interact with your visitors and handle incoming data. This means that you can use either the URL (querystring) or forms to retrieve user input. There are additional ways to access data as well, but we will not be covering those in this introduction.

In your browser, add the following to the end of your url: ?name=yourname


The full URL should now look like myfirstpage.php?name=yourname

You'll notice when you visit this page nothing happens - so let's change that! To access the value of name in the querystring, we can use $_GET['name'] like so:


<html>

<head>

<title>Hello</title>

</head>

<body>

Hello <?php echo $_GET['name']; ?>

</body>

</html>


You'll notice that unlike the text "there!" that the GET is not in quotes - this is because this is a variable and by not placing it in quotes we're telling PHP to render this as a variable and not as text. If we leave the single quotes, instead of saying "Hello yourname" it would say "Hello $_GET['name']."

Using logic and defining variables


Along with getting user input, you can also create conditions to determine what content should be output. For example, we can determine whether or not to say "Good morning" or "Good evening" depending on the time, along with your name using the querystring.

To do this, we'll be using if, elseif, and else along with the PHP date() function. You can learn more about how to use different date formats to output the date here, but we'll be using the date() function to get back the hour of the day (based on the server's time) between 0 (midnight) and 23 (11pm). We'll then use greater than (>) to determine what to assign to our $time variable which we'll output with the user's name.


<html>

<head>

<title>Hello</title>

</head>

<body>

<?php

if(date("G") > 18) {

$time = 'evening';

} elseif (date("G") > 12) {

$time = 'afternoon';

} else {

$time = 'morning';

}

echo 'Good '.$time.' '.$_GET['name'];

?>

</body>

</html>


Now upload your script again to the web server and refresh the page. Depending on the time of the server you should see either Good morning, Good afternoon, or Good evening followed by your name.

If you get an error, or the page is blank, make sure you have closed all of your quotes and have a semicolon after your statements/ commands. Missing a quote or semicolon is one of the most common causes of PHP errors.

You may also receive an error if the timezone has not been set on your server. To resolve this (or change the timezone/ output of the script) try adding this line as the first line following the opening PHP bracket (<?php):


date_default_timezone_set('America/Los_Angeles');


With that you have created your first PHP script and have already taken advantage of many of the fundamentals used in every PHP program. While there is more to learn you are well on your way, and have a great start on defining variables, using user input, and taking advantage of PHP's built in functions.


Want more? Go even further with our Beginning PHP video training course!
8275 views · 3 years ago


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

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


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

</form>

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



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


php artisan make:controller UploadController


Now in the web.php file,


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


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


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


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

Get the submitted file,


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


Parse the submitted file,


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

}


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


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

}


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



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


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

}


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

Full code:


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

}


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

Full template:


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

</div>




That’s it, thanks for reading :)

SPONSORS

PHP Tutorials and Videos