What are we doing here?

This blog includes a series of videos and references to help new users or enthusiasts better understand how to use open source and free technology tools. The quick links includes more information for accessing many of the tools covered along with other references to learn more for taking advantage of these tools.

Click HERE to see the full list of topics covered!
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

PHP with S3

 


This blog and video runs through getting started with PHP and S3. The subsequent code is all open source in the GitHub page located at the below link.

https://github.com/JoeMrCoffee/yourS3objects

Previously we looked at MinIO using it's console and UI, as well as quick set up in docker. This is a slightly more advanced look at interacting with object storage from a programmatic standpoint. 

PHP has an open SDK to tie in with S3 object storage that is provided by AWS. The video, as well as the source code in GitHub installs the SDK as part of the Docker bring up and build. This is done in the Dockerfile, and is very similar to installing the MongoDB packs required to make a PHP connection to a MongoDB database. 

From the code all the connection information to the S3 object store is in the 'header.php' file. If one wanted to use this site, or just its source code, they could also adjust the endpoint to the appropriate values. The 'header.php' file gets included in all the subsequent pages using the PHP include command, so everything else will follow the values in the header.php file.

The video talks a bit about the usefulness of the site. I developed it mostly as a reference for how the SDK could be used, but the actual site might be useful as a quick way for teams to just store and manage files in a particular bucket that only the admin or host could adjust.

Some more useful reference is below:

Adding Comments to Posts - MongoDB and PHP

This article explores adding a comments section to blog or forum posts. 

Using my previous project 'OutNoteOrganizer' - which still needs a better name, but all the good ones I could think of were taken - I thought about the design and felt it needed to have a comment section. 

Similar to say for example Reddit, though not public, teams or groups of people could want to leave comments on the initial post. The other thing I didn't like about the initial design was that anyone in the associate group could edit and change the content without a good way from the UI to track what was changed. 

Now the current version only allows the original post author to edit the post, and other group members with access to the post can leave comments.

How I got here?

In terms of how I visualized the code structure, previously I was hung up thinking that comments should be fields in the post itself. For example comment 1, comment 2, etc. However, while it might be possible to do that, it's complex if you want to have an unlimited number of comments to a post. Adjust the concept a bit and you can think of comments that link to the post but are stored in a different table (in MongoDB a different collection) called 'comments'.


Again with MongoDB, there is no need to 'prime' or 'setup' the table. Just from the code tell the DB what fields you want and it will accept the values as a BSON object. 

Once you have an HTML form filled in you really only need this code to create a new collection called 'comments'. 

$col = $db -> comments; //Point the query at the new collection comments (this will create the collection)

//Collect data from an HTML form

$username = $_POST['author'];

$comment = $_POST['commentcontent'];

$postname = $_POST['postname'];

//Create a PHP array to insert into MongoDB

$insertcomment = ['author' => $username, 'comment' => $comment, 'postname' => $postname];

//Make the insert query / connection - the if / else just catches an error

if ($postcomment = $col->insertOne($insertcomment)){

        echo "<h3>Comment added to $postname. </h3>";

}

else { echo "<h3>Error occured while adding that comment. Please contact your IT administrator.</h3>"; }

I also wanted to create a hidden form so that it only appears when a user clicks 'ADD COMMENT'. Initially I was thinking using Javascript and passing an innerHTML call would work. It does for the action, but because the comments need to collect some hidden data (i.e. the post title, the logged in user, etc) in PHP variables, the hidden variables need to exist in the PHP code before the Javascript action takes place. 

Explanation: PHP is a server side language meaning all the actions are requests to the server on page load. If the page loaded, but the PHP variables are not present during page load, the script won't know about them. Javascript is a run-time in the web browser itself. This makes it good for these on page actions - like <onclick='dothisfunction()'>. However, passing additional HTML after the page loaded will omit the variables we need.

It turns out that Javascript has styling properties as well. What they do is allow for CSS changes to be applied to specific elements identified by the 'id' tag.  What we can do is rather than pass new HTML code to the page - which causes issues with the PHP variables needed - we can more simply change the fields from 'hidden' to 'visible'. This way the PHP variables are known to the script, but the same visual result of handling a pop up can be achieved. 

In code - HTML with PHP variables - called using echo in PHP

<button onclick='addcomment()'>ADD COMMENT</button><br><br>

<div id='AddComment' style='visibility: hidden;'>

<form method='post' action='submitcomment.php' id='insertComment'>

<textarea class='giantinput' name='commentcontent' placeholder='Add a comment'></textarea>

<input type='hidden' name='author' value='$loginuser'>

<input type='hidden' name='postname' value='$postname'>

<br><br><input type='submit' form='insertComment' value='Submit'></form>

</div>

In code - JS

function addcomment() {
    var commentform = document.getElementById('AddComment');
    
     if (commentform.style.visibility === 'hidden') {
        commentform.style.visibility = 'visible';
     }
    
     else { commentform.style.visibility = 'hidden'; }
 }

The above is fairly basic as an example implementation. For better accuracy, it may be the case that the HTML form for the comments needs to collect more than just the post title or name, but also say the post author, the date, or better the object ID to ensure if there are say multiple posts with the same name all the comments do not get pulled into each post. 

Just wanted to share a bit of code and discovery using PHP and Javascript hand-in-hand to create a useful layout. Hope it helps. 

Full source code and Docker Compose to install is located on GitHub.

 

Getting started with PHP and MongoDB

 

This post and video delve into the world of schemaless, NoSQL databases. NoSQL databases are powerful and interesting ways of storing data at scale. Because they do not have a traditional table that dictates what kind of data needs to be written, NoSQL databases, like MongoDB, can accept data much more easily. There is also the benefit that, at scale, a cluster of multiple nodes can be hosting a common database and collection where as a traditional database cannot scale-out horizontally. 

In cloud computing, NoSQL databases are what drive the likes of Amazon, Google, Facebook and more. 

In order to learn more about them I wanted to try and replicate what I know on PHP and MySQL (a schema or relational database), and apply it to PHP with MongoDB. I did struggle a bit because of the way I was building the container and my lack of familiarity with the way Composer works. As such I thought I'd share my progress and provide the docker-compose file along with a run through of how to get it setup and running. 

The Dockerfile and Docker Compose script are located on my GitHub with no license and anyone can feel free to use the repository to quickly bring up and test a LAMP stack using MongoDB instead of MySQL or MariaDB. Just git clone, and run docker-compose up from the directory and it should build everything. 

Also included in the repo is a very simple HTML form that will write a Name and Age to the MongoDB instance. These two web pages are essentially just offered as a reference for how to connect and get started. 

Docker Compose source: https://github.com/JoeMrCoffee/MongoLAMP

Additional references that I found helpful:

Official documentation on using PHP with MongoDB:
https://docs.mongodb.com/drivers/php/

Official Docker image for MongoDB and Mongo-Express:
https://hub.docker.com/_/mongo
(This was the base for the docker compose minus the Apache PHP image)

Another great tutorial which is worth a look as well.
https://www.javatpoint.com/php-mongodb

User login and logout using PHP - Part 3 of 3 (still maybe 4)

 

This post and video runs through how to create some logic for searching through a user table in a database, validating the given login credentials, and displaying different results based on the outcome. 

Key concepts covered are the session_start() function of PHP, essentially allowing for the webpage to store data (cookies) about a user, using a counter to help check the login, and then session_destroy() function to logout. 

This bit of code was actually something I thought up, but previous references helped walk me through it. JoyofPHP by Alan Forbes again briefly talks about how, conceptually, to handle some of this, and there are slews of examples on sites like StackOverflow, and W3schools for dealing with sessions and variables.

The bit of javascript code to automatically refresh the page on first load I found from this StackOverflow post. The site is a wealth of knowledge with contributors from all over the world helping to solve each others coding roadblocks. Something anyone who even wants to just start to learn will find useful, and Google results often reference it.

Note: Mentioned in the first post, this tutorial doesn't include a security portion, but should one be considering a live website including SSL/TLS will be critical before doing anything like a user login with sensitive information. At the very least purchase a valid certificate, create your own if its an internal site/system, or run Let's Encrypt on the site.

I hope all of this will be helpful, and provide a good starting place for future development and learning.

PHP + CSS + HTML overview - Post 2 of 3 (maybe 4)



This post goes over how to take the functions of the 'mysqli' function we covered in the previous PizzaOrder site, and create a more usable flow in a nicer format. The new site adds an order confirmation page and website management pages for internal users to add products and review new orders.

User login and control is coming in a separate video.

While this particular code is largely my own, I also wanted to link back again to the JoyofPHP, and also help signal out W3schools website which has a ton of info on managing and creating feature websites. Their site is linked on the right-hand side column in the blog as well, but it is a great source of know-how for getting started with website creation/optimization.

One other note to add is the W3schools' explanations of the enctype for uploading a file to PHP - Note https://www.w3schools.com/tags/att_form_enctype.asp

I hope this is helpful, thanks again.

Intro to Web design using HTML, CSS and PHP - 1 of 3



This tutorial covers the basics of using HTML and PHP to interact with a user, collect data into an HTML form, capture the data, then submit to an existing database. 

Primarily we cover HTML <form></form>, PHP mysqli, PHP echo, and the basic formatting of an HTML table. 

I designed this to be very simple on purpose to act as a base. In the next two or three videos I hope to explore more about formatting and creating a more useful flow of user data and a shopping cart to open orders. In many ways these fields are just building on what is already shown in this video, but help to demonstrate how powerful the mysqli integration is with HTML, CSS, and PHP for create dynamic websites. 

Of course there are a multitude of other features and optimizations that can be done and included. I hope this can be a good foundation for new users or those interested to take the first steps - like I am - into web and software design.

I also wanted to reference The Joy of PHP by Alan Forbes again as his book taught me what little I know of PHP. The examples I'm showing are just pieces of code and know-how that his more in-depth book details, and I found it really helpful and easy to apply.

Finally, I can't emphasize enough, the current site is NOT secure. We built our LAMP stacks without an SSL (Secure Sockets Layer) certificate so that would need to be added to the Apache server/service on a server facing the internet. More information can be found on various sites, and currently one of the best open SSL implantation is Let's Encrypt. It does require some access to the Apache server to setup, but automates the SSL certificate re-registration/authentication so is quite nice for most sites. As an admin it will be up to your team to pick the best solution, but I wanted to ensure that while previous LAMP stacks are both viable test environments, a production environment (hosting a site on the Internet) shoudl have both SSL certicates and strong Firewall protection.