PHP & Web Development Blogs

Search Results For: your
Showing 1 to 5 of 42 blog articles.
1591 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.
5442 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!
6676 views · 2 years ago
10 SEO Best Practices for Web Developers

You've built an amazing website, but how do you make sure people can find your site via search engines? In this article we cover 10 best practices to make sure your article not only stands out, but ranks well with search engines.

1. Take time to research keywords


To determine the best keywords for your site, you'll need to do some keyword research. This usually consists of combing through your competitors' sites for the keywords that are driving them the most traffic. There are several ways you can get started with keyword research. One recommended way is to create a spreadsheet with your competitors' sites listed and add keywords that you can copy and paste your competitors' keywords into Google's Keyword Tool and Google Webmaster Tools Keyword Analyzer tool. Analyze your competition's site's website titles to find out what keywords they are using tools such as Ahrefs, Moz, SpyFu, or SEMrush to find out what keywords others are using on your competitor's site.

2. Focus on your Title tag


This is the headline for every article. It needs to be bold and attention grabbing so it can catch the eye of potential users. Pick it somewhere around 60-90 characters to make sure it is displayed properly in search engines as well as readable in the browser tab. As you write your title, focus on the unique keywords your readers are likely to search for. Also make sure that the keywords you select are relevant to your page. Another good practice is to make the title tag and your header (h1) the same.

3. Carefully craft your H1, H2, H3 tags


Careful usage of header tags helps search engines identify keywords within your page. To get the best results from your header tags, use H1, H2, and H3 in order with keywords in your H2 and H3 headers that support your H1 tag. Remember, your H1 tag should mimic your title tag, whereas the H2 and H3 can expand and add additional context. You can also utilize multiple H2 and H3 tags, however be sure that these headers are supporting the H1 tag and relevant to the content on your page. Using irrelevant header keywords can actually work to your disadvantage.

4. Avoid loading content with JavaScript


Despite it's popularity, JavaScript is not yet well supported by search engines and can mask important content. Progressive Web Apps in particular can suffer as key content is loaded after the page is spidered, or in the case of many search engines that do not yet index JavaScript not loaded at all. This is also the case for many social media sites, meaning that content loaded dynamically is not evaluated or pulled in, resulting in the default skeleton of your site being what shows up in search engines and in link previews.

5. Carefully name images


In the past search engines would evaluate your images based on their alt tag, however as more and more developers loaded irrelevant keywords into this hidden image text search engines instead added more emphasis to the actual name of the image itself. This means using generic image names such as 1.jpg can actually hurt your site ranking as search engines might be looking for seokeywords.jpg. Now, just because you're carefully naming your images with relevant keywords describing the image doesn't mean you should ignore the alt tag. Be sure to continue to include alt tags for older search engines, in the case the image doesn't load, and for accessibility (ie screen readers).

6. Work to improve your page load time


It’s not a secret that faster sites rank higher in search engines. Most search engines use the PageSpeed Index from Google to determine the speed of websites. One thing Google looks at is how fast images are loading. For this reason, we recommend taking a look at how long it takes for the first image to load on your site or even take advantage of lazy loading for non-critical images. You want images to be loading within 30 seconds at the absolute latest, before the user can actually click on the page. You also need to make sure that if you're using multiple images that they load as one group. Next, take a look at how long it takes to load a webpage. Are pages taking longer than three seconds to load on your site? You want to have pages that load fast for users, but your code and templates can easily be causing this to happen.

7. Optimize text throughout your page


Beyond your title tag, headers, and images it's important to work keywords into your standard content, while also working to avoid overloading keywords. To help prevent overloading and increase search engine rankings across multiple keywords you can use alternative phrases. In the case of "PHP training" an alternative phrase might be "PHP tutorials" or "PHP course." This both helps support the primary keyword, while also allowing the page to rank for these keywords as well. Remember to use the tools referenced above to find the keywords that are right for your site, and then work them in to natural sentences without forcing keywords or becoming overly repetitive. Also keep in mind, just as important as the content and keywords on the page are to search engines, how users engage with that content is also critical. If your page experience's high bounce rates or low engagement with the content, it is likely to be deprioritized by search engines, meaning a page highly optimized for search engines but not humans may enjoy a higher ranking, but only for a short time before it is heavily penalized.

8. Build your Domain and Page Authority


Domain and Page Authority are determined not just by the number of back-links (or sites linking to your domain or page), but also the quality of the sites and pages linking to you. One practice that has made obtaining a better DA or PA harder has been purchasing or acquiring bulk back-links. Note this practice is actually against Google's TOS and may result in your entire site being banned from their search results! Because of this practice, it's important to focus on high quality sites and work to get back-links naturally either through partnerships or syndicated content (such as blog posts). You can also check your DA here or using one of the many tools referenced above.

9. Take advantage of social media


Speaking of back-links, social media can be a powerful tool for increasing page visibility while also improving your search engine rankings! Remember, most social sites do not support or read JavaScript, so ensure your content is available on the page. If you do have a progressive web app with JavaScript loading your content, look into using Headless Chrome to render a JavaScript free version of your site for specific bots (note - the content MUST be the same content a user would see or your site may be blocked). There are also numerous tools to allow you to build the content via JavaScript on the server backend before passing it to your readers. To help get even more exposure, consider adding social share links or tools like AddThis.

10. Good SEO takes time


The truth is that there really aren't any special secrets or ingredients to ranking well in search engines (well not that Google has publicly shared). Instead it's about properly formatting your page, making sure it's readable to search engines, and providing content that your readers will engage with. As you provide more valuable content, and more people like and link to your content - your site's Domain Authority will gradually increase, giving your site and pages more powerful - resulting in a higher ranking.
5718 views · 2 years ago
A Beginners Guide To Artificial Intelligence For Web Developers

Artificial Intelligence has significantly transformed the way we work and interpret information. With technologies such as OCR, machine learning, deep learning, natural language processing, and computer vision; machines are now able to provide greater insights and perform tasks that typically required hours and hours of work from humans.

What is artificial intelligence?


A.I. or artificial intelligence is the technology that enables machines to perform tasks that usually require human intelligence. But instead of using human brains, A.I. uses different technologies such as computers, or even software algorithms, to perform tasks. Some of the most common A.I. technologies include speech recognition, voice recognition, machine translation, natural language processing, computer vision, and predictive analytics. The term artificial intelligence comes from the combination of artificial and intelligence. While artificial intelligence is a property of the physical world, intelligence is the property of the mind. How does it make sense in Web Development? As mentioned earlier, A.I. has significantly transformed the way we work and interpret information.

How is AI applied to web development?


In the majority of cases, AI is used to assist a developer in a number of functions: Automatically format existing content, analyze images for semantic meaning Break down complex tasks into smaller pieces Example applications of AI in web development Example image compression algorithms. Tools such as image recognition and machine learning have been key factors in the development of new image processing algorithms. Traditionally, manually processing an image was a lengthy and tedious process, but when computer vision was introduced into the process it drastically decreased the amount of time required to complete this task. Now, programs such as image recognition can identify objects in images and classify them based on both visual and metadata attributes.

Machine learning


When data is fed into a machine learning algorithm, the machine learns to understand it. For instance, if you provide a machine learning algorithm examples of dogs verses blueberries, the machine will learn to identify what a picture of a blueberry looks like, verses a picture of a dog. Natural Language Processing Natural language processing is a sub-field of machine learning. You can apply natural language processing for reading emails, chatting, or writing blog posts (such as this one!). A good example of natural language processing in action can be found in Microsoft's Cortana. Deep learning This is the most popular type of artificial intelligence today.

Deep learning


Deep learning algorithms are very similar to how the human brain works, with its built in mechanisms to learn and memorise a vast amount of information. It's these connections that enable machines to be able to recognise patterns and learn from them. An example of this is Google Translate, which recognises more than a 1,000 languages. This isn't an example of AI but it shows how useful these programs can be. Deep learning is one of the hottest technologies in the field of machine learning and this explains why almost all of the major technology companies are pushing these advances forward.

Natural language processing


For example, your phone can understand you better when you speak to it. If you say “Hey, Siri,” your phone will listen to you and respond to your questions. In general, it means that the system has been trained and is able to better understand the context of what you’re trying to communicate. This type of Natural Language Processing is used in the majority of companies today, including the likes of Google and Apple, to improve the user experience, provide better customer service, and to aid in the effective execution of processes. Machine learning Machine Learning is an extremely powerful technique used to further improve the knowledge of artificial intelligence, as well as to make machines smarter by discovering patterns and generalities in vast amounts of data.

Computer vision


Computer vision is a technology that has been able to recognize objects in images and video for eons. A popular example is Apple's Siri, which was one of the first software to use computer vision to provide contextual awareness. AI is built on this technology, providing the capability to recognize various images and videos. The industry is still in its infancy, but what we have seen so far has been incredibly incredible. What's amazing is that just a few years ago we thought that vision was completely under our control, but now, it has evolved to understand the nuances of objects.

Conclusion

“In the year 2050, the Amazon book you ordered for your Kindle will be delivered by a drone.”

This futuristic statement by Amazon CEO Jeff Bezos did leave you pondering. But it is one thing to dream about the future and another thing to think about the innovations taking place in the present and how you can exploit them to drive better business results. To make the most of the technologies coming to our everyday lives, we must acquire a knowledge of the AI technology, its features, and its application. Succeeding in today’s competitive and challenging business world, requires a broad set of skills such as coding, business analysis, computer programming, and ecommerce marketing.

Learn more about AI with our video library
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

SPONSORS