User Tools

Site Tools


blog:spring2016:cjann:journal

Web Application Development Journal

January 25th, 2016

The first two days of our adventure into PHP discovery was mostly preparation.

On our first day we were made hip to the syllabus and basic login procedures, using our myccc login names and passwords that were setup previously. Using the ssh lab 46 command to active the secure shell access to lab 46, which allows us to remotely access the lab remotely.

On the second day we jauntily explored basic Unix command line commands. The aforementioned ssh lab 46 command brings up the home prompt. The home prompt is frightening as it is different from the traditional windows based prompt, and is set to lab46:~$.

Basic working directory commands like ls (like dir in windows prompt), ls -l (like windows dir but more better), and pwd (which prints the working directory) were reconnoitered.

Mkdir *folder / file name* is the Unix form of making a new folder, further showcasing how Unix utilizes frightening brevity. Other basics such as changing file permissions (chmod ### filename), copying a file (cp. Filename), change file name (mv originalname newname), delete file (rm filename), and a manual for the ls command (man ls).

This afternoon (1/25) we added basic PHP to a basic HTML page. PHP syntax is very simple thus far, somewhat similar to java or javascript I have confronted in previous coursework. PHP embedded in an HTML document uses a non-closing tag similar to <img> or <br> tags in HTML. PHP content is started by a <?PHP and ended by a ?>, and any HTML content can be added in between closed instances of PHP code with no ill effects.

Easily enough, variables are handled somewhat similarly to Java / javascript in that they can be declared and initialized on the same line. Also, PHP functions are similar to Java / Javascript methods in that they typically have parenthesis following (we used rand(min number, max number), which is used for pseudo random number generation). PHP’s output (println in java) is echo “content”.

February 1st, 2016

In the second week of Server Side Programming I have encountered if / else statements, loops, and another topic to be named later, as I was absent from class today (2/1).

The if, and if else statements share similar syntax to other programming languages I have encountered (notably, java). The keyword if is followed by a condition inside of parenthesis, in our case it was a comparison operation of ($size < 133). $size is a variable in which we stored the value of a random number, using the method learned last week rand(1, 400). The interpreter checks the condition, and performs the code block following it if the condition is met. In our case the condition inside the brackets was to randomize the color of the text on the webpage if the value of $size is less than 133. To do this we created three variables with the values of rand(0, 255), and plugged those values into echoed html code setting the color of the text. Echo “<div style=\”color: rgb ($rval, $gval, $bval);\”>”;

Similar methods were used in an else if statement with the condition of ($size < 266). If the else if condition is met, the color AND size of the text is randomized. Color is randomized using previously outlined methods, and the size is randomized by including the style font-size: $size; added to the div.

Loop syntax in php is exactly the same as in java, and javascript if memory serves. We created a table using echoes and loops, starting the basic table structure using echo commands. We started by creating the variable $i, which was set equal to zero. The table tag, tr, and th tags were initialized with echo statements, with various style elements.

The for loop condition was ($i = 0; $i < 17; $i = $i + 1). This condition sets I equal to zero, ensures the value of I is less than 17, and will run the code block if I is indeed less than 17, and increments I by one, and performs the check all over again. The process will repeat until I is equal to 17.

Inside the code block we created three variables with random values ranging from 0 to 255, and used those in an echo statement to set the background color of the table rows. Effectively randomizing the background of each row. Also, inside the code block we included echo statements to create the structure of the table. Echo statements added for structure: <td>$i</td> <td> </td>” </tr>. Inside the rows we created a simple multiplication table. Inside the left cells of the table we put the value of I inside the cells ($i), and on the right hand cells we put the variable $square, which was set equal to $i * $i.

As a parting thought, it is possible in php to use a second set of quotes in php instead of escaping them. I’d prefer using this method, but I’m going to make an effort to get comfortable escaping them because I feel it could benefit me in the long run as my code becomes more complex.

I’ll continue this entry later, feeling pretty ill and concentrating is laborious.

February 8th, 2016

Starting to feel less ill, so hopefully this entry will be more interesting.

While loops are gloriously simplified from for loops, and were covered during my sick leave on 2/1. The syntax is $i=0; While ($i < number) { Code that does important code things $i++; }

The variable I is set to zero, and the code in the code block is run until the condition is no longer true. The incrementing operation occurs at the end of the code block.

In the class example we used the for loop to generate table structure for a simple multiplication table with random cell colors using rand, similar to our fantabulous for loop execution previously outlined in the last entry. This code is located in the file loopfun2.php for future reference.

Also during my regrettable absence on 2/1 we covered do while loops, which function similarly to other outlined loops but with different structure

$i=0; Do { Code to do wonderful things $i++; } While ($i < number);

In do while loops the code block is first. The incrementing operation is performed at the end of the code block, and the condition is after the code block. The code block is repeated until the condition is no longer true.

As noted in the file loopfun3.php, the do while loop is the only loop with a terminating semi-colon.

Foreach loops were also covered during my absence, and appear to be quite different than loops previously spoken of. The syntax as follows:

$array = array (array of things);

Foreach ($array as $i) { Code to do our bidding }

For each loops run the code block for every item in the array. For each loop example is located in the beautiful loopfun4.php

Arrays are pretty basic at this point in my humble experience, but they are worth covering, and there are things about them worth mentioning that may be different in php than in other languages I have been exposed to. Like the following key based array:

$arrayname = array( name = value (strings and numbers?), name = value, name = value, name = value, name = value, );

The items in the key value array can later be used in regular arrays, using only the key value to reference them. The newly created array can then be bent to our will, and used for any operation an array could be used for (as seen in arrayfun2.php).

To be covered in the next entry: functions, and whatever else we cover between now and next Monday. A concerted effort needs to be made to create entries 2 or three times a week, instead of everything at once.

February 15th, 2016

This entry of my opus will cover the fun we’ve been having with FUNctions.

Function definitions are similar to what I’ve previously seen in java. It begins with the keyword function, followed by the name of the function, followed by parenthesis with any parameters inside, and a code block to contain the function code. The awe inducing example used in class is as follows:

Function average($num1, $num2, $num3, $num4) {

$sum = $num1 + $num2 + $num3 + $num4;

Return $avg; }

Any object preceded by a dollar sign is a variable. The return keyword designates the value that is chucked out of the function.

When we call the function we add parameters between the parenthesis where the variables are. These are used inside the code to perform computation. The fabulous function call in class looked as such:

$val = average(89, 77, 92, 81);

The parameters are added together inside the code block, and the result is assigned to the variable $avg. This variable can now be used in any other needed operations we demand of our hard working code.

We’ve used stock php functions as well. We used imagecreatetruecolor, imagecolorallocate, and other functions to draw adorable shapes into a browser window. The code block looked like this:

$img = imagecreatetruecolor(200, 200); $fuschia = imagecolorallocate($img, 255, 0, 255); $green = imagecolorallocate($img, 0, 255, 0); $px = (imagesx($img) - 7.5 * strlen(“FOOF”)) / 2; imagestring($img, 3, $px, 9, “FOOF”, $fuschia); imagefilledrectangle($img, 10, 100, 190, 120, $fuschia); imagefilledrectangle($img, 90, 50, 110, 190, $green); imagepng($img, “thing.png”, 0, PNG_NO_FILTER); imagedestroy($img);

echo “<img src=\”thing.png\“>”;

On line one we use imagecreatetruecolor. This function takes two parameters, the height and width of the image area being drawn. The next line we use image color allocate which takes the name of the image area, and the three rgb values to create the color. The result of this function is stored in the variable $fuschia. The third line is nearly identical to the second, only is stored in the variable $green. I’ve forgotten what line four does. It looks like it possibly sets the location for the string being rendered on line five. From appearances, line 5 writes “FOOF” in the image area. It uses the function imagestring. Imagestring appears to take several arguments. It uses the name of the image area, a number, a variable, another number, a string, and a variable which is a color. Line six and seven use the imagefilledrectangle function. We are using it to draw shapes inside of our image area. It takes six parameters: the name of the image area, the four coordinates in pixels, and the color to be assigned to the rendered shape.

The next to last line uses the imgpng function. According to the php documentation, this function “outputs or saves a PNG image from the given image”. Therefore, I concur that this function actually renders the image. It takes four parameters: the variable the image information is stored in, a string for the filename, a number, and PNG_NO_FILTER. In the documentation the last parameter sets a bitmask which reduces the png file size. PNG_NO_FILTER disables such a filter.

The last line uses the function imagedestroy. According to the documentation, it frees up the memory allocated for the image. I’m assuming that after the code is interpreted and the image is outputted to the browser, this function clears that image from system memory.

Lastly, we use echo to output the image into an html tag using this line echo “<img src=\”thing.png\“>”;

Function work will be continued in my entry. I am burning with anticipation.

February 21st, 2016

In today and tomorrow’s entry I’ll be elegantly going over our graph code (found in graph.php), and another topic to be named later.

In the graph.php file we expand our understanding of functions using previously used functions, and some new, to create a graph-like image on a webpage.

The file starts with the function header(“Content-type: image/png”) (I’m unsure if I’ve covered this function before, but I’ll cover it again for posterity). According to documentation:

Header() is used to send a raw HTTP header. Header() must be called before any actual output is sent.

So this function needs to be at the beginning of the php code block, if my understanding is as wonderful as I’ve been led to believe. It takes a string as a parameter. In our case the code is

Header(“Content-type: image/png”);

So in our instance we’re telling the involved processes that the incoming data is an image of the png type.

In the next code block we see functions we’ve used before in our A1 flavored programming. Imagecreatetruecolor and imagecolorallocate. Following these, there are two calls to the imageline() function. In our case it looks like this:

Imageline($img, 0, 0, 0, 99, $white); Imageline($img, 0, 99, 799, 99, $white);

This function is similar to imagefilledrectangle. It takes a grouping of parameters: the name of the image area, four coordinates, and the color the object is drawn in. This function doesn’t draw a square, and appears to only draw a line. These two lines represent the x and y axes of our graph.

Following that line we have

$fh = fopen(“/home/wedge/public_html/php/data.txt”, “r”);

We’re storing the results of the fopen function to the variable fh. Fopen is used to locate a file and open it. The file we are accessing was a plain text file of numbers that will be used as data to draw our graph (I/O like in java?). The other parameter “r” sets the file to read only. Whatever that means. According to the documentation it’s the “mode parameter”, which specifies the type of access the input stream has.

To be continued tomorrow

February 22nd, 2016

Today's blog entry will address my ever expanding knowledge of functions, and finish up the write-up of graph.php. I also hope to start a project this week because my blog is seriously lacking in fanciful creativity.

After the fopen line we have two variable assignments $x and $y, which are set equal to numbers.

Following that, we have a for loop. I'm not entirely sure what the for loop does at this moment, but it should become clear after sleuthing. The code block is as follows:

fscanf($fh, “%d”, $pt); imageline($img, $x, $y, $x + 98, 100 - $pt, $blue); $x= $x + 98; $y = 100 - $pt;

After parsing the documentation fscanf is a file input function, possibly similar to those seen in java (filereader?). $fh is the file object we created earlier using our data file. The parameter “%d” appears to be a formatting parameter, and is set to treat the inputs as integers. Unsure as to what $pt is referring to on this line, but perhaps it will become clear.

The next line is using the imageline function to draw a line through php magic. It's using the image area, x, y, 98, 100, pt, and blue as parameters. It's using x, y, and values added to x as coordinates for the line. It's also using $pt in a calculation, but I still have no idea where $pt came from. At this point I have to assume it's a variable output from fscanf. After the imageline we have the $x and $y variables being assigned new values. Adding 98 to x, and subtracting $pt from 100 for y. These values are reset before each subsequent for loop.

A similar for loop is created for each line. Four lines in total.

UPDATE: Is $pt an array of values returned from reading the file?

February 29th, 2016

In this week's entry I'll be briefly outlining the ONE (read: need more) self created project I have created, along with our recent work with forms and get. Potential works to be covered: action.php (which interacts with form.html, and the classlist 1-3.php.

In this week's entry I'll be briefly outlining the ONE (read: need more) self created project I have created, along with our recent work with forms and get. Potential works to be covered: action.php (which interacts with form.html, and the classlist 1-3.php.

The one project I have created by myself for the class was some php that draws a star on a webpage, and is located in starand.php. There was originally supposed to be two working versions of the file: one with predetermined colors, and one with random colors. I borked the copying of the files, so now there is only one version (the one with randomized colors) until I un-bork my mistake.

It’s very similar to our other work. Using the basic stuff like the rand function, imagecolorallocate, imagline, imagepng, et al, I draw a star to the webpage. The star is currently unfilled. Moving forward, if I were to continue work with this project, I would fill the star. Currently, the randomized colors aren’t working how I would like. I had intended for each line of the star to be a random color, but as of now they are all the same randomized color. A secondary objective after filling the star would be to correctly randomize the colors the way I had intended them to be.

Regarding our recent work with forms and get, we have two files merged in an illustrious php union: action.php and form.html.

Form.html (unsurprisingly) is an html page with various form types on the page. The starting form tag has an attribute “action” and it’s value is “action.php”. This attribute assigns the file (or possibly program / application?) that will be sent and processes data we enter into the forms. There are three text entries, one select dropdown box, one radio button selection, and a submit button. Each text area has a name, which will be used by our php file. The dropdown selection and radio button have values associated with each option, which will also be used in our php file. Our submit button submits (shocking) data to the action.php file.

Our action.php file is elegant in its design, and how it processes our sent information. The value “$_POST[formname]” is used to call values that the user has entered into the form fields. In the first line we echo out a message to the user, along with the name that was entered into the name field from the html page. The same is being done with the email address field, and the secret magical number field. We also show that these values can be used in other operations, as there is an if / else statement regarding the entered number:

If ($_POST[‘number’] == 37)

Echo “ HOORAH<br />”;

Else

Echo “ WRONG<br />”;

As shown, we have a pretty fancy if statement there. We’re checking to see if the entered number is equal to 37, and displaying two different messages to the user depending on the results of that check.

Lastly, the user’s selection is returned to them using methods similar to how the text fields were returned. That’s it, for our magnificent awe-inspiring forms / action files.

In classlist.php we are importing information from an external file outside of lab46, and displaying specific information from that file on our webpage display. This operation is also assisted by the file “xml2array.php”. It’s a gigantic php helper file designed to help display our information correctly. Future goals include reviewing the file in greater detail, and possibly using it to create a future project.

The first line of php code in the “classlist.php” file is

Include(“xml2array.php”)

From reading the documentation website it appears that this function is similar to importing packages or classes in java (?). Any variables or functions used in the included file can also be used in our “classlist.php” file.

The next line we are storing a url (it’s CCC’s class list schedule) into the variable $url. The next line we are storing some information in a variable called $coursedata, using the function xml2array. Xml2array takes two parameters: $url, 1, and a string “tag”. After inspecting the xml2array.php file I’ve discovered where all of that has come from. Xml12array function comes from the “imported” file.

This entire imported file appears to be an xml parser. Inside it I see many references to xml and parsing. Given the structure of our classlist.php file, and my previous experience with coding, it seems that the parser is taking the parsed xml and storing it in an array for us to use.

In the fourth line we start using the parsed data. We are accessing $coursedata variable (the array of stored parsed xml) four times, and storing them in a variable. Each line is accessing a different piece of text using array syntax. The first line is extracting the CRN using the following line:

$crn = $coursedata[“XML”][“Section”][2600][“CRN”];

The code is accessing the 2600 section, and selecting the CRN of that class. Similar selections are being made on the next three lines. These variables are then used to print the course information to the screen using the echo function.

March 6th, 2016

New plan: to address the lack of self-work, and the ever growing size of the opus entries, it would behoove me to break them up into two parts: half will be breaking down important parts from the lecture for better understanding, the other half will be work of my own that I will be writing about.

One of our super interesting projects from the last week or so was the Drawerer application. Using php and html we have two files interacting: drawerer.html and draw.php. The drawerer.html file takes input from the user and outputs it to a window in the form of a drawn shape.

Drawerer.html is a simple html page with a few forms setup for input. Important parts to note are the “name” and “value” of the form fields. The php files interact with these values specifically.

Draw.php is the file that receives the data from the html file. The first line establishes the content-type for the header, and we’ve seen it before. The next four lines are taking the name of the field and storing them to variables to be used in code later, we’ve seen this before. On line 5 we encountered something less familiar, and I’ve not covered it before in my blog. The line is:

If (isset($_POST[“fill”])) $fill = $POST_(“fill”); Else $fill = “no”;

In our html page we have an option to fill the drawn shape, or leave it as just an outline. This form is a checkbox. The line above checks to see if it is selected. If it’s selected, the shape is filled. This line is required because the browser would throw an error later in our code if it were unchecked. There is a similar if statement following this one to check for whether or not the user has selected the outline option.

The following code block is nothing we haven’t seen before. First line is setting the image area to the height and width specified in the html file. The six lines after that are creating our colors and storing them in variables.

The next two code blocks are if statements detecting what color the user has chosen, and setting a variable “hue” equal to one of our defined colors.

Following that, there’s an if statement to draw the rectangle. The first if detects whether or not the rectangle should be filled, and if it should be filled it’s passed the color of the fill from the previous if statement. The else sets the rectangle to a non-filled rectangle. The last if detects whether or not the border option was checked. If yes, we draw an imagerectangle as a border for the first.

The next block of if statements is exactly the same as the previous, only they check whether or not the shape should be a circle. The only things of note are the values being passed to the circle drawing functions. The variables of height and width are divided by two for circle reasons, and the two integer values of 0 and 360. According to the php documentation, these values are the start and end point of the circle. Changing the value from 360 to 180 breaks the drawn image, I had initially thought that it would only draw half of a circle. If I remember this for class I can ask about it.

To be continued tomorrow.

March 7th, 2016

This part of the entry will be somewhat disjointed. I have not made too much progress in my proposed project, but I have made some. For the rest of this week’s entry I’ll recount what I have so far, what I plan to do, and some of the issues I had getting it working.

The concept for the project is pretty ambitious: I plan to create a html page and a php page that interact to “create” a website using user input. It’s a task of gargantuan proportions, and may never be finished. It’ll be using the basic forms we’ve already seen. Asking the user’s name, size of the banner, one two or three columns, possibly insert images, links, etc. Basically an exercise is GET / POST, and using echo to display things. I’d like to find a place to add some complex if statements and loops, but that’s much farther down the line after I get the framework down.

My muy fantastico project is coming along swimmingly, albeit slowly. The html file is a simple table with form structure inserted into the table. Note to self: create the table and forms with php! This could be a great opportunity to practice loops. It’s currently only text boxes. I’ll add the full gamut of form stuff to see what I can work in. (Forgot: the html file name

In the php file I have very little as well. Closing and ending php tags obviously. I have four variables in use: name , width, height, and banner color. All of these are taken from their respective form entries from the html page. This file will be mostly about bringing in the information from the html page and doing things with it.

Some trouble I had with this file, while not really php related, was remembering how div tags are styled. I’m using div tags to setup the banners and columns for the content area. I was trying to setup the width and height as separate attributes outside of the styling attributes, which is wrong. Width and height belong inside styles along with color, background-color, font-style, etc.

My if / else statement was initially broken and not functioning. I don’t remember specifically what the problem was, but for a time the file was only outputting the results of the second part of the if / else statement.

Stupidly enough, I did have a brief moment of brain-fartery in which I was treating the php tag similar to an html tag, which was causing delays.

Some more delays came from the naming of my variables. I kept switching / replacing “username” and “name”, which caused broken results for a bit. This is a good reminder to keep variables as simple as possible, and to match them with the html content as much as possible.

Somewhat related, I did manage to discover new shortcuts for nano completely by accident. I was fat-fingering other shortcuts when I discovered that alt+m turns on mouse support, and alt+g allows you to jump to a specified line number. Absolutely flabbergasted, and these discoveries greatly improve quality of life.

March 14th, 2016

This week’s entry will be mostly covering old (but nonetheless magnificent) classwork. I would love to expand on projects I have been working on at home, but alas my weekend proved eventful and I was unable to make very much progress. Initially I will cover what I was present for on Friday, then review what I missed during my (again) regretful absence on Wednesday.

The file is called magick.php, and there were two iterations of it. The first was designed to read an image, edit the image, and then output the edited image into our publichtml/php folder. It effectively put a border around the image, reflected the image, and saved it as a copy (I’ve forgotten the command line procedure for making the code run, I’ll need to ask for that in the future). The second iteration did the same as the first, but a function was added to create a “charcoal” effect on the image.

The file starts with this line:

$img = new Imagick(“mudkip.jpg”);

Nothing unusual, other than a call to a new function that is spanking new to us. The imagick( ) function is taking a string as a parameter (the name of the file to be edited). Imagick is a function from a native php extension that is used to create and modify images (as per the php documentation). It differs from the previously used draw commands in that it creates / edits much more complex images than the simple RGB drawings we’ve been heretofore creating. According to documentation imagick can be used to create or edit over hundreds of file types, including popular formats like GIF, JPEG, PNG, and PDF.

On the next line we have the following:

$img → thumbnailImage(320, null);

Through much trepidation, on this line we are exposed to several new things. Firstly, the symbol →. This works exactly the same way as Java’s dot notation. The line would look like this in java (hopefully):

Img.thumbnailimage(320, null);

So, effectively, it’s how we access class functionality in php (note: possibly ask for clarification sometime). We have an object of the $img class, and it’s being worked on by the thumbnailimage( ) function.

http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php

Thumbnailimage is used to change the size of the image. In this example the function is taking a number value and null. In the documentation it takes 3 parameters: an integer for rows, an integer for columns, and a Boolean value for a “best fit” option. If best fit is set to true, the image is scaled to always fit inside the given integer values for columns and rows.

The following line:

$img → borderImage(new ImagickPixel(“white”), 5, 5);

It appears that this line is setting a border to the image. There’s similar syntax as the line above it, so we are again accessing class functions. borderImage( ) is very simply described in the documentation as “surrounding the image with a border”. It takes three parameters: color (gmagickpixel object or string), width, and height. Gmagickpixel is a class within magickpixel, and here we’re using it to set the border color. The documentation page for this class / function is pretty cryptic and lacks an introductions. It may be another thing to bring up in class?

The next line is the function we added to “charcoal the image”, and proved exceedingly artistic:

$img → charcoalImage(100, 5);

Same syntax as the last few lines. This line is applying a charcoal sketch effect to the image, and belongs to the imagick extension / package, or whatever it is. It takes two parameters: an integer for the radius “of the Gaussian”, and an integer for the sigma (the standard deviation of the Gaussian).

These two parameters are explained pretty well in the comments in the documentation, so I’m going to do my best to paraphrase them succinctly:

http://php.net/manual/en/imagick.charcoalimage.php

The Gaussian is like the brush (photshop / gimp verbage), the radius is the radius of the brush, and the standard deviation is the level of variation of the individual brush prints. Radius, as recommended by the commenter, should be no higher than 10-30 pixels, depending on image size. Otherwise the effect is lost and distorted. The commenter also suggests that the deviation not be higher than the radius so as to give the charcoal effect. As he puts it “Think of it as ‘Charcoal Brushes of $radius pixels size, with each brush being as much as $sigma Pixels bigger or smaller than that’.”

Next two lines are some brand new stuff as well:

$reflection = $img → clone(); $reflection → flipImage();

So, again we see the class notation stuff. We’re using the clone() function. There is an object cloning page in the documentation, and you essentially make another exact copy of an object (and in this instance we are storing it in a variable). According to the documentation, the properties of the object are also copied and any properties referenced from other variables remain as references. (not sure what this means, need to ask).

The second line is using the cloned image and reflecting it using flipImage(). As parameters it takes an image object created by any image color (including imagecreatetruecolor that we’ve used in the past), and something called a “mode”. The mode is apparently one of three constants: IMG_FLIP_HORIZONTAL, IMG_FLIP_VERTICAL, and IMG_FLIP_BOTH. We didn’t have to enter the mode. I wonder if flipping horizontally is the default?

The next two lines look like they could be complicated:

$gradient = new Imagick(); $gradient → newPseudoImage($reflection → getImageWidth() + 10, $reflection → getImageHeight() +, “gradient:transparent-black”);

The first line not so much. This is standard stuff we’ve seen: creating a new imagick object using said function, and storing it in a variable.

The second line looks daunting. The entire thing is a function called newPseudoImage. This function is of the imagick extension. The three parameters are an integer for columns in the new image, integer for columns in the new image, and something called a pseudoString.

For the columns we are using getImageWidth() on the $reflection object and adding 10 (10 is a pixel integer value for an offset?). The same is being done with getImageHeight. The last parameter appears to be setting a gradient to the image. Regarding pseudo-images:

http://www.imagemagick.org/script/formats.php

Imagick supports image format specifications for images prepared with algorithms, or I /O targets. So this last parameter is allowing us to generate this new image object as a pseudo-image of the GRADIENT type?

That’s all for tonight. Will continue with specified file tomorrow or the next day. I’ve found this one more interesting than normal because reasons.

March 17th, 2016

Abandoning what (little) work I have on my own project. Now we have an official project to work on!!!1!one! I’ll also be abandoning the previous explanation of the mudkip charcoal drawing file. I’ll only return to it in the event I need filler to meet my opus word count quota. It’s not that I don’t want to finish the entry, but I feel having my opus walk hand in hand with projects could prove valuble.

This entry will be going over the file as it stands now, what we completed in class. The file is called montecarlopi.php

We start off with four variable declarations. $iterations is a very large number, $radius is 1.00, and radiussquare (representing the math formula for finding the area of a circle). $count is initially set to zero, as is $init.

The for loop is doing some interesting stuff.

For ($iters = 0; $iters < $iterations; $iters++)

So we are going to run the for loop code block with the iters variable is less than iterations. Incrementing iters by one whenever the code block is run. The code block

{ $x = lcg_value(); $y = lcg_value();

$isin = ($x * $x) + ($y * $y); If ($isin ⇐ $radiusSquare) { $init = $init + 1; } }

The only thing unfamiliar is the lcg_value() function. The rest is logical or mathematical formulas I have long since forgotten.

Lcg_value returns pseudo random numbers in the range of 0 to 1. Outputs pseudo random float values in said range. So we are storing very tiny positive numbers in x and y, and squaring them on the next line and adding them together, giving us the result of isin (which represents whether or not the point generated is inside the circle). If the calculated isin value is less than or equal to the radiusSquare (1), init is incremented by one.

The value of init is later used to calculate pi, which I don’t currently understand. Since our objective is a visual representation of the points being plotted in the circle and square, it is irrelevant if I understand how pi is being calculated. Had to brush up on my maths. Here is some useful info: -radius: distance from the outside edge of a circle to the middle point -Diameter: The distance from one side of the circle to the other (r^2) -Circumference: the perimeter of the circle -Pi is the ratio of a circle’s circumference to its diameter. Regardless of the size of the circle, pi is always the same number. You get pi by dividing the circumference by its diameter.

-The program is attempting to calculate pi by plotting many points on the circle, and using those points and their relationships to one another to approximate pi.

Update: I think I get how the montecarlo thinger is working! Source http://mathfaculty.fullerton.edu/mathews/n2003/montecarlopimod.html

They first calculate the ratio of the area of a square to the area of the circle. They use a circle with a radius of 1. The divide the formula for that circle’s area by the area of the square, and the return is pi/4 or .785….

So, to get pi, we can multiply the ratio by four.

They fill the square (and by extension the circle) with a lattice of points. The count of the points in the circle are 812, and outside the circle there are 212. So we end up with 812/812+212 =812/1024=.79296…*4 = 3.1718 (the approximation of pi). (Side note: why do I find this cool? I hate math!)

This is what our program is doing.

Okay, back on track. The goal for this entry will be to get a working image background. One step at a time.

Okay, I have a working image area with an example shape drawn. I added a header function to the top. In the last half I created the image object, a color, and drew a square. After those I added the imagepng and imagedestroy function.

Currently the image area is covering the pi calculations and the dot counters. That’s all the time I can spend on it today. I spent far too long trying to wrap my head around the monte carlo method. The goal for next time is to move the image area off of the pi calculation and point counter, get the shapes drawn, and begin my loop to draw the points.

March 20th, 2016

I have successfully written code that draws the shapes. The image area is 500×500 pixels. The shapes Are the same height and width. I didn’t use anything new to draw these, everything is pulled from older works and class projects. Imagefilledrectangle and imagefilledarc were used.

At this point it doesn’t really matter if my image is covering the pie calculations. My primary concern at this point is to get the dots drawn on the canvas.

At this point (3/20 10pm) I have broken my code moving the image work above the for loop that calculates the pi value. The images are no longer being drawn. Goal for tomorrow is to fix this, and begin a prototype for the loop that will draw my dots.

March 21st, 2016

Ok, took just a short time to debug my code today. There was a typo in the mixing of the color white. I’m not sure why that would cause the whole image to break. Maybe this is a question I can ask in class. Alright, moving on, time for the real fun.

Plan for this session: There’s going to be a slight problem in calculating where to plot the points. As it stands, the circle has a radius of one (and by extension, the square has a width / height of radius x radius). The points x and y values are always greater than zero but less than or equal to one. So if we’re translating that to pixels, we’d be talking about a very small image. So I’ll be playing with a version of the original file without shapes, and adjusting the size of the square and circle that would be visible to the human eye while also keeping correct mathematical approximation of pi.

So the bottleneck appears to be the lcd_value() function. I initially thought that entering some parameters into it would change the range of returned values, but that is not the case. According to the documentation there are no parameters to be passed to the function. So I’ll be looking for a different function to compute random values within a specific range. I think it’s time to visit old man rand() again.

Current iteration:

I’ve changed the value of the radius to 250, and the radiussquare to 2*radius. I figured this would make plotting the points easier. I’ve changed the lcd_value functions to rands. The range for the values is 1 to 499 so no dots are placed on the edge of the square. Current output of the pi calculation is nowhere near what it used to be. At the moment, with 32,000,000 iterations, I’m getting an approximated pi value of 0.006011. So this method looks like a no-go thus far.

So that was dumb maths by me. I’ve returned the value of the radius squared back to radius * radius. Brain fart over. Interesting to note: The combination of changing the value of radius to 250, changing the rand values to 1-500, and using the rand function to calculate x and y coordinates, has actually increased the number of iterations in the circle. One would expect the approximation of pi to be closer to the actual value, but the reverse appears true. This iteration has 6289597 iterations in the circle, but the pi approximation is 0.786199625. I need to check further down the code to see if I need to change other values along with the adjusted radius.

Okay, secondary brain fart over. For reasons unknown I was using the range 0-500 with rand, when the radius used was only 250. I’ve since changed the rand range to 0-250, and I get a pretty close approximation of pi! Currently sits at 3.131854125.

Alright, there’s some serious progress. I’ve used the imagesetpixel function to print the points to the screen. For the x and y coordinates of the function I’ve used their values in the same manner as in the isin calculation ($x*$x, $y*$y). I’m getting points overlaid on the drawing of the square and circle, and they vary slightly every time the page is loaded. A particular concern I have is that a large chunk of points seem to be congregating in the upper left hand corner of the screen. I’m not sure if this is a function of rand or not.

Goal for the next session is to either make a new file and embed this code into an html document so the pi calculation is visible, or simply convert the existing file to an html file. Also, ask be sure to find out whether or not you are on the right track with this project.

April 2nd 2016

I missed last week’s blog entry, and I may have been short in the week before, so I’m going to try and make up for that moving forward.

As of my last entry I was working on our monte carlo pi class project, contained in themontecarlopi.php file. I have since completed the project, and will be outlining the changes made since the last entry. I will avoid repeating previously outlined material where possible.

I had left of in a place where I thought the project was completed, and all I had to do was insert the pi calculations back onto the image somehow.

To draw the dots I was using the rand function with a customized number range of zero to five hundred to calculate the random points needed for the pi calculation. For reasons, rand wasn’t plotting all of the points in the image. Probably a mistake that lay within my selected range, or just the fact that rand is awful. I had switched to rand because I’m bad at maths, and thought that the number ranges provided by rand would be a quicker way to plot the numbers (because the lcgvalue function returns values between zero and one, which wouldn’t be visible to an unaided eye). At the suggestion of Matt, I implemented the original lcgvalue function, and multiplied it by 500 to make the output values fit within my five hundred pixel viewable area.

This resulted in the correct image output. All three hundred and twenty thousand iterations were plotted to the image, resulting in the dots being very dense in the image. Creating an almost sand blasted look to the image.

Instead of importing my php over to an html file to display the pi calculations, I simply overlaid the text on the image. Using the imagestring function, I printed out the $iterations and $init variables along with strings at the bottom of the image area (which I had extended an extra 200 pixels to accommodate the text). All that’s left now is to submit the file.

To round out this entry, I’m going to outline a VERY small project I tinkered with one day in class. It could turn into a full-fledged project if I could find the extra time, but as it stands it’s pretty simple. It’s a bit of code that takes input text and outputs a hashed string. In internet security, data is run through a hashing algorithm to create something called a digest. Digests are used for comparisons after the data has been sent. The data arrives at the recipient along with a digest that is generated by the sender. The receiver runs the data through the same hashing algorithm used by the sender, and compares the two digests. If the digests are the same, the receiver knows that the data has not been tampered with. At least, that’s my understanding of the process.

It starts with the html file hasher.html. Inside it is a simple form with a text input area, with the name “sha”, and the action is set to a file called hashingalgo.php. When the text is entered it is sent to the hashingalgo file for processing.

Inside hashingalgo.php I store the input text in a variable called $sha using $_POST (the text from hasher.html). The line after that I’m using a function called hash, which takes two parameters. One parameter is the hashing algorithm to use, in this case I am using SHA256 hashing. The second parameter is the data to hash, which is the input text.

Then I echo out a string and the hashed text. The returned hashed text will always be the same length regardless of what is entered into the input field. After further inspection, it appears the hash is the same every time regardless of what is entered.

Plans for moving forward with this project:

I plan to add in some more code to output digests from several different hashing algorithms, just to see the differences in output. More research needs to be done with the hash function to make sure I’m using it properly.

For a project with more substance, I’m going to research the possibility of encrypting text using php functions. Since hashing isn’t really encrypting, I think creating some php code that could encrypt / decrypt text would be really interesting.

April 4th 2016

Beginning note: don’t forget to cover the font stuff

Some notes for beginning encryption and decryption testing in php:

Mcrypt_encrypt(cipher, key, data, mode, iv)

Cipher is a constant entered as a string or variable. Ciphers used for this are located in the following link. Be on the lookout for the ones discussed in network security:

http://php.net/manual/en/mcrypt.ciphers.php

Key: the key that will be used to encrypt the data. Doesn’t appear to be any constants like the ciphers. It appears as though you make your own key? In the example, a very long seemingly random string is entered into the pack() function. Like so:

$key = pack('H*', “bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3”);

Pack takes two parameters: the “format” and the string you are packing. Formatting types are found here:

http://php.net/manual/en/function.pack.php

In the example the string is being formatted using the H constant, packed into a hex string. The * is a value that tells the interpreter to continue the formatting for all of the data. There is a quick php file I’ve whipped up to test a few outputs of the pack function, and it’s called packex.php. Embarrassingly enough, I don’t remember off the top of my head how to access my lab46 files through a browser. Review of the output will have to wait until I get back to my notebook where the address is written.

I have found random key generation applications online which may be used for my keys in the future. The documentation recommends that the key should be random binary. As recommended, I may try to generate my own key using scrypt, bcrypt, or PBKDF2 to convert a string into a key. I’ll cover that once I get to my code to avoid fluff.

Data: The data that will be encrypted. It is yet unknown whether or not this can be a string. Assuming at this time that using a variable instead of the raw data would be better.

Mode: predefined constants, which can be found here http://php.net/manual/en/mcrypt.constants.php

The example from the documentation $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,

                               $plaintext, MCRYPT_MODE_CBC, $iv);

The example is using MCRYPT_MODE_CBC. CBC stands for cipher block chaining. There are four block cipher modes: CBC, OFB, CFB, and ECB. CBC offers increased security, according to the documentation. There’s also NOFB, which is a specialized and more secure block cipher, and STREAM, which can use stream ciphers.

Iv: According to the documentation, this parameter is used to initialize the CBC, CFB, OFB, and some STREAM algorithms. If the algorithm needs an iv value and one is not supplied, the function will return a warning.

http://php.net/manual/en/function.mcrypt-encrypt.php

Ending note: don’t forget to cover the font stuff

4-6 entry

I have a functional prototype of my encryption code. A lot has happened since the 4-4 entry, and my understanding of the material has expanded. The prototype is messy, but I’ll cover the important bits. I’ll also be outlining my plans for a more refined, finished product. I’d like to potentially implement something more personalized, and less stolen from the example in the documentation. I’ll see what I can come up with.

The script starts with using the pack function on a randomly generated 16 byte key in hex format. The key is generated from : https://www.random.org/bytes/

One thing I never mentioned above was what the pack function does. It packs the given number into a binary string, which will later be used in the encryption.

After that we are using strlen() to find the length of the key, and storing it in the variable keysize. On the very next line we are echoing out the key length along with astring.

On line 23 I defined the plain text string that will be encrypted, and it’s stored in the variable $plaintext.

On line 27 I start my work with the IV, which stands for initialization vector. These numbers tend to be random and are only used once, and never repeated. It’s used along with the key to encrypt the data. On line 27 we are using mcrypt_get_iv_size() to find out what size IV we need when encrypting our data. It takes two parameters: the cipher, and the encryption mode (mode was covered earlier). The cipher used in the example is the Rijndael 128, also known as AES128 (advanced encryption standard, it uses 128 bit encryption keys).

April 8th 2016

We are storing the IV size in the variable $ivsize. We create the iv in the very next line. Using the aptly named mcrypt_create_iv() function, using our $ivsize and a constant MCRYPT_RAND. The second parameter are one of a set of three constants which represent the source of the iv. In this instance, we are using the MCRYPT_RAND the built in php random number generator.

The next line is the actual encryption function, the previously mentioned mcrypt_encrypt. Using all of the parameters mentioned earlier (cipher, key, data, encryption mode, and iv).

On line 33 I’ve used some syntax I don’t quite understand

$encrypted = $iv . $encrypted;

The documentation says “prepend the iv for it to be available for decryption”. It seems similar to dot notation from java, but I’m wondering if it’s necessary?

Test: It appears as though commenting out that line doesn’t break the program, but it does appear to affect the content being echoed out. It deletes part of the message. NOTE: The encrypted text changes appearance every page refresh, as expected. Cool!

April 11th 2016

Last time I left off at line 33 of the packex.php code. Since then I've moved on from that file, and I actually have working prototypes of the encryption / decryption websites. I'll continue with the packex file for now, and move on to my prototypes later.

The next line that does work is line 37. On this line we have:

$ctencoded = base64_encode($encrypted);

On this line we see the base64_encode function working on the ciphertext output by our encryption function. The documentation page for this particular function states that it converts 8-bit text to allow it to be transported through “layers that are not 8-bit clean”. Whatever that means.

(researched from wikipedia) Base 64 encoding encodes binary text into something readable / representable / transferable. The binary data is converted into ASCII strings, essentially. The implementation of base 64 is such that the 64 characters are members of a subset common to most encodings, and are also printable (viewable on screen I assume). According to both wikipedia and php documentation, this leaves the characters least likely to be unmodified through transit (both sources cite e-mail) systems that are not “8 bit clean”. Again, whatever that means.

This “8 bit clean” hullabaloo has to do with message encoding, transport, and representation. I'd love to continue down this rabbit hole, but I have an opus to write. Submitted work > general curiosity. At present time we'll leave it at “base64_encode lets us read the unreadable”.

The next functional line is simply echoing out the encoded ciphertext for the user. Using that fantastic dot notation stuff again.

Line 44 we are using a substring function for some reason. Since most of this is pulled from the example in the documentation, it looks like we are splitting up the concatenated string that we created on line 33. So that's why the printed string is so long. The echo out on line 39 is printed both the IV and the ciphertext?

After looking into it, that line and several others were unnecessary. The example was faffing about concatenating keys, ciphertext, and all sorts of other things unnecessary for my purposes. I've since deleted those, which helped clean up my code and aid in my understanding.

The next useful line is line 52, which is using the mcrypt_decrypt() function. Is is nearly identical the the encrypt function. It takes the encryption type, the key, the encrypted text, mode, and iv. It then outputs the decrypted data.

The last line in the code is printing out the decrypted message.

Discovery note: This is a little early in the opus, but I figured I needed to document this before I forget about it later.

In my prototype encryption / decryption applications I've run into an issue. They function perfectly fine, but the decryption page prints out garbled symbols, nonsense, or otherwise unreadable text that I've named “artifacts”. The whole decrypted message is present, but there always seems to be a handful of artifacts preceding it.

In an attempt to discover why, I've run an experiment inside of the packex.php file. In it I am testing the encode/decode base64 functions to see if the artifacts are being generated via the encoding and decoding process. At the end of the file I take the base64 encoded ciphertext and run it through the base64 decode function, and then use the resulting ciphertext in the mcrypt_decrypt function. The results are then printed out to see if there are any artifacts similar to my prototype html apps. There are no artifacts printed out by the packex page, therefore the issues must lie inside of my prototypes. I'll begin troubleshooting those after I've outlined the prototypes here.

April 15th 2016

Trumpets and applause! I’ll now document the prototypes for my encryption code! In order to avoid filler I won’t repeat (in detail) code / functions outlined previously in my packedex.php file. I’ll go over them simply, with the most focus on stuff I’ve not yet covered.

Overall, my resplendent project consists of four pieces: encrypt_app.html, encrypt.php, decrypt_app.html, and decrypt.php. Both of the HTML files are simple web pages that have a simple text input field which point to their respective php action files.

Encrypt_app.html takes a simple text string as input, whatever text of any length (well not ANY length, but I’ve tested text as long as a paragraph our two and it functions). The action of the form points to encrypt.php where the text input is encrypted.

Upon further inspection, the longer entries of text generate longer outputs of ciphertext (duh). I’ve input text as long as 5 paragraphs with no errors. Note: the ciphertext printed out by long blocks of text is super long and nearly unusable because it prints off the page and is difficult to copy for the decryption page.

The encrypt.php, as opulent as it is, is very much like the packex.php file, and uses the same methods to encrypt the text. Using the $_POST[‘input’] stuffs we’ve used in other html files, we are transporting the text to be encrypted into the php file.

The key is a fixed 16byte key we used before (I have discovered a way to generate a random key on every usage, and will cover that later).

The next several lines are junk we’ve seen before. Echo statements outputting the key, line breaks, and the user’s input text. Boring trivial stuff we understand already, no changes here.

It’s not until we get to the IV generation code where we shift gears, and some changes occur. As I’ve synopsisized previously, I had an issue where the encrypted text was being deciphered and output with some unreadable artifacts along with it (after more adjustments and troubleshooting, the total decrypted text was garbled and not totally readable). I discovered that I was using a different randomly generated IV in the encryption, and a different totally random IV in the decryption. To remedy this I encode the IV into base 64 and print it out to the screen, which the user later uh… uses to decrypt their text.

Most of the rest of the file is stuff we’ve used before. The text is encrypted the same as packex.php using the mcrypt_encrypt function, encoded into base 64, and printed out to the user to be decrypted later.

At the bottom I have echoed out a link to the decryption html page “decrypt_app.html.

April 19th 2016

Time is winding down, and I’ve not had the dedication to my journal entries that I wish I had. Catching up with my journal, cranking out EoCE, and other coursework will be a herculean task. I live for the frantic mad dash intensity that the end of the semester provides. Bring it on.

I’ll begin by covering the second part of my encryption code: the decryption part. This may not take much space, so when I get to the end I’ll hit the ground running with something else. The file is called decryptapp.html

The decryption HTML page is much the same as the encryption page. Simple text entry forms that point to a php file for their action. Originally, this file had only one text input for the ciphertext that needs to be decrypted. Subsequent testing and iterations, as mentioned earlier, found that I needed to be using the same IV. A text input was added, and now the user has to enter both the IV and the ciphertext for the encryption to function. Note: not entering an IV throws an error. Error handling could be a feature to include in another iteration of this code. Surely php must have error handling code like java (and I’m not calling you Shirley).

Indeed, all the code in the decrypt.php file is stuff we’ve seen before. 1. The input is brought in using $_POST. 2. The key is packed and stored. 3. The IV is decoded back into binary from base 64. 4. Mcrypt_Decrypt uses all previously discussed variables / constants to decrypt the ciphertext. 5. The decoded text is printed to the page for the user.

If we follow Yogi’s creed of “Build something, scale it up, and make it better”, what are some features to include in a future iteration? I have noticed that the code will allow you to encrypt an empty string. Perhaps some kind of if /else statement could be included to check whether or not the user has entered text, and output an error message in the event the text field is bupkis? The aforementioned error handling would be another thing. Also, a way to transfer over the IV to the decryption app would be great. The copy and pasting is a bit laborious for a simple web widget.

Okay, so I’ve totally covered the functional prototype (which, from here on out will be known as the “beta test”). I’ve also been experimenting with some other functions that could make the beta test a bit more elegant and interesting, so I’m going to muse over some of them. Right now.

In my mighty quest of epic php stuffs I stumbled onto a few functions. I was looking for a solution to generating a random key for my decryption app, instead of using a fixed key every time. I ran into someone suggesting “microtime()” in conjunction with rand (I think, it’s been awhile and the page has been lost in the sands of forgetfulness). Some combination of rand and microtime was used to generate a pseudorandom number. Microtime simply prints out the current unix timestamp in microseconds. I abandoned this method after experimentation, which is just as well. This method could have required extensive legwork in the form of conversion and implementation to fit my design.

In microtime’s place, I have instead been experimenting with a function that seems purpose built for my purposes: openssl_random_pseudo_bytes(). This lovely named function generates a random string of bytes. In its simplest form, it takes only one parameter: a number indicating the size in bytes of the random string generated. This is perfect for my purposes, as I can simply plug in 16 to get the corresponding length for my selected encryption algorithm. Note: I would, at some point, like to include some kind of if / else code so the user could select several features for the encryption process. Algorithm used, method used, etc… I feel this would strengthen my understanding of conditional statements (a loop would be nice too), and logical statements are currently my biggest weakness. Basic if / else not so much, but more complicated conditionals such as nested if / else statements, and loops, have been my Achilles heel since last spring when I was taking Joe’s object oriented programming course. Time willing…

Efforts to use this function in conjunction with previous functions yielded no dysfunction at this junction, therefore my compunction to explore malfunctions was not met with injunction (I cheated and used rhymezone.com). The only roadblock now is to implement this into a finished product elegantly. Again, I have yet to implement a way to transport information from the encryption files into the decryption files. Matt suggested that I use the same POST stuff we’ve been using. But… how do I do that if the content I wish to transport is coming from a php file? How would one transport content from a php file, at the very least, into another HTML file? Let alone possibly transferring the key, IV, and ciphertext from one php file to another.

All these possibilities will be explored at a later date. I’ve yet to even get started on the research for the topic, so the task seems daunting. Hopefully by next entry I’ll have something.

April 21st 2016

I’ve discovered that my chosen encryption function has actually been abandoned since 2007. A kind fellow at the bottom of the mcrypt_encrypt page explains this, and links to a very compelling article on why mcrypt_encrypt is bad:

https://paragonie.com/blog/2015/05/if-you-re-typing-word-mcrypt-into-your-code-you-re-doing-it-wrong

The article suggests a different encryption method: open_ssl. Most of the article over my head at this point, but there are a few takeaways. Most notable, the open_ssl method is easier to read and implement. Open ssl automatically pads the plain text you are decrypting. Padding is essentially using nonsense bits of data to pad short messages to better fill the container they are being sent in, and padding can also make it harder do crack (I think). It’s faster than what I was using. All this, and more!

I was running out of steam regarding this project, but this may just be the boost I need. I'll take a look at this and see if there's anything new and interesting I can do with this. If not, I may just need to find something else to tinker with until the semester is over.

I've decided to add some simple error handling to my encryption and decryption prototypes in the event I abandon them in the future. At first glance (I've done like, two seconds of research) php errors are handled using if / else statements. So, I threw an if / else statement into my decryption page testing whether or not the IV is an empty string. If the IV is an empty string, I am echoing out an error message and a link back the the decryption page. A few notes: the comparison for the IV looks like this

if($iv = “ ”). It appears that there must be a space between the quotes for the interpreter to see it as an empty string. I tried an iteration where it was just two quotes with no space, and the error message for no IV was printed out.

Secondly, the echoed out link back to the decryption page (the one that prints as a result of the error) doesn't work. When the link is clicked, the browser thinks for a moment and spits an error out. “The site can't be reached. Lab46's DNS address could not be found”. This is odd, because the echoed out link that leads to the same page on the encryption app functions perfectly fine.

I'm in the mood for more testing and error handling, but I've gotta eat and wrap up the systems analysis presentation for tomorrow. It's a strange thing that I've come to prefer tinkering with code than any other coursework. Probably because coding is more problem solving and discovery, and the other stuff is monotonous busywork.

Note: Oldschool blues (Blues Roots genre on spotify) seems to be the least distracting music to code to. Excellent finding, because any music or video is usually too distracting. I've been craving background noise, so hopefully this works out.

April 22nd 2016

Tumbling down the rabbit hole of research. Started researching ssl_encrypt, and I'm speedily losing myself in something similar to a youtube binge.

At present moment, I am playing with print_r and how it differs from echo.

In the file “sslex.php”, a file originally intended to experiment / compare the differences between mcrypt and openssl, I have printed out three strings using echo, print, and print_r. Visually on the page their output isn't different.

Crawling the web for differences led me here: http://stackoverflow.com/questions/1647322/whats-the-difference-between-echo-print-and-print-r-in-php

Print and echo are almost functionally identical, with a few subtle differences. Print has a return value of 1, which allows it to be used in calculations / functions (?). Echo actually has room for multiple parameters.

http://php.net/manual/en/function.echo.php

Okay, back to open_ssl versus mcrypt_encrypt. We've covered a few reasons why open_ssl is better, let's see if I can discover some on my own.

Firstly, there is no difference between the number of parameters taken. Openssl takes the data, method, password, options, and password. Mcrypt takes cipher, key, data, mode, and IV.

April 25th 2016

Openssl_get_ciphermethods is the first openssl type thinger I’ve experimented with. The method is used on line one of the sslex.php file. Apparently, it accesses all available cipher methods. I’ve stored them in a variable, and I’m printing them out using print_r. What we get is a massive array with 164 entries. Das a lot of cipher methds! Most of which I have yet to see anywhere. This really reveals the scope of encryption technology, and the depth of what is out there. I’m finding this topic more interesting as I go along with this research.

I’ve noticed that openssl_encrypt takes a parameter called “password”. What is this nonsense about? Research to follow.

NOTE: Some of the contributor notes at the bottom have me thinking- would it be possible to encrypt an entire file using php? I have to assume it is possible! How else are files shared between servers and clients securely? This could be an idea for an end of semester project, instead of this research wheel-spinning rut I’m stuck in. I think I’m going to pop smoke on this research paper trail and begin exploring this idea right away. Ho! What about some double encryption action? Could I write php code that encrypts text entered by a user and outputs it into a file, and then some code to encrypt the file? That would be pretty stellar. Side note: from here on out this entry is going to be injected with as much military slang as I can remember from my serving days.

Alright, after plugging away for a bit here’s what I have. I’m currently trying to get a string printed out to an existing file using to file_put_contents. When this code attempts to run, I get a permissions error. The same type of error was encountered when I tried to use fopen to create a file when the code is run instead of using a preset file. These methods will be covered later in detail once I get them functioning, but right not I need to eat an apple and get to class.

Thanks to Matt and his chmod hooyah, the output works now. chmod 606 was used to change the permissions on the output file to allow write access (along with some awkward command “touch”, of which I am completely out of my pay grade) I will continue to plug away and get a functioning prototype before I cover it here. Goals: Successfully encrypt a string, output that string to a file, and encrypt that file using openssl.

NOTE: In my most recent iteration / experimentation of my previous encryption work, I was using openssl_random to generate a key for mcrypt. Openssl encryption was under my nose the whole time?!

April 27th 2016

Hunger induced stupor has left me unable to write code very well (forgot my lunch and too busy to hit the cafeteria). So instead of writing code I will document my current progress on my ssl encryption playground. Fun!

Open ssl seems a smidge more convenient than the mcrypt method. It uses the previously documented objects as parameters. I was getting a very frustrating error for some of it. It was “Error on line 37: open_sslencrypt() expects parameter 4 to be long, string given in 'filename'”. It was particularly frustrating because the message is kind of cryptic. My parameter 4, at the time, was the IV. The IV was the correct length, so the error was really throwing me off.

It turns out, I was missing a parameter. I thought one of them was optional, the “options” (haha). The two options are “OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING”, both of which are completely cryptic sounding. Instead, as shown in the example at the top of the page, I used a 0. This apparently satisfies the need for that particular parameter.

My initial idea of encrypting text, dumping it into a file, and then encrypting the file may be too ambitious this late in the game. It could have been a potential project had I intercepted this idea earlier, but as it stands the code requires quite a bit of moving parts. I'm afraid that I wouldn't have time to cover everything to aid in understanding. We'll see…

I have figured out how to write data into an existing file. The code for creating the file and printing text to the new file doesn't work because of permission functions. Maybe I could morph this into an input / output exercise? (We may have done some I/O stuff earlier in the semester)

The current method used for writing to an existing file is actually pretty easy at the basic level, I've been using file_put_contents. It takes only two parameters: the data to be written and the file object.

May 2nd 2016

Well, half of my dream has been realized. I've successfully used openssl encryption to encrypt a string and output it to an existing file. Using all the same output functions previously covered: open_sslencrypt and file_put_contents. As it stands, the new string overtires the old. If one were so inclined there is probably a constant or different method that appends new text after the text that was previously there.

Yep, after looking at the documentation there is a parameter constant that can be used to append data to the file instead of overwriting it (the documentation calls it a “flag”). The flags are added after the other parameters (file object and data). The flag used to append data instead of overwriting is FILE_APPEND.

Interestingly, file_put_contents is a simplified method to interact with files. A different method would be to use the three functions fopen, fwrite, and fclose. All of these take their own parameters, but it's essentially a longer way to do exactly what file_put_contents does (I think).

I did throw down some quick php code in windows to test fopen outside of our unix environment. I wasn't able to use php to create a file because of write permissions. So I whipped up some fast code to create a file with fopen and dump some plain text into it. There must be something more to writing and interpreting php code in windows. When I use the file address in the address bar of a browser all I see is a text version of the file. No output file is created.

I did attempt to use the command here http://php.net/manual/en/install.windows.commandline.php To execute the code from the command line. I got the error message “php.exe” is not recognized as an internal or external command, operable program or batch file“. So I assume there needs to be some installation required for this command to work. More research to follow.

Well obviously there's an installation required. Right above the command to run the file is a link that says “You should read the manual installation steps first!”. I've done a great job at ignoring that crucial piece of direction.

I'll have to attempt to install required PHP tools when I get home.

Also, I may have potentially found a solution to my file permissions issue. There is a PHP function that changes the chmod values of a file! So, potentially, I could use this function to change the permissions of the file I am creating as it is being created. I whipped up some quick code but I can't test it because I forget how to access my files from a browser. I'm super great at this. I'll debug and test the code once I get to class.

blog/spring2016/cjann/journal.txt · Last modified: 2016/05/02 13:44 by cjann