Friday, January 17, 2014

PHP Test for Beginners

If you're currently learning PHP (the programming/scripting language) then keep reading, we've put together a little beginners quiz just for you. Some of these questions are more about trivia and tips rather than actual language questions, so if you're not a beginner, consider reading along anyway, we'll try to keep it interesting.

1. What is a simple way to check your PHP version and configuration?

2. What is a way to get the IP address of the server?

3. What is a simple way to get the first character in the string variable $strx?

4. The file fxfunc.php is an include file and contains no HTML. How many tags should be present after the opening PHP tag?

5. How can I make an if statement without using a closing brace (})?

6. What is the difference between null and NULL?

7. When making an class, how do you make a member function the constructor so it is called on creation?

8. What is a simple way to print a string as text rather than HTML when it may contain tags?

9. Imagine you have found a bug in your program. You are printing values from an array, using something similar to implode, but they print in the wrong order, such as printing key 0, then 2, then 1. How do you fix it with minimal code?

10. register_globals doesn't exist in new versions of PHP, why?




1.
Answer: Create a PHP file containing PHP tags with the phpinfo() function inside. You'll want to view the file in a browser since it will usually show a properly formatted HTML page.

Example of wrong/poor answer: Fetch the version with phpversion() and configuration options with ini_get(). (Not Simple)

2.
Answer: In almost all cases it is in the $_SERVER['SERVER_ADDR'] variable.

Example of wrong/poor answer: $_SERVER['REMOTE_ADDR'] (This would be the client's IP and not usually the server's)

3.
Answer: There are multiple acceptable answers. $strx[0] or $strx{0} are the same so both are good. Slightly more complex is substr($strx, 0, 1) or other string functions.

Example of wrong/poor answer: $strx[1] (Second character)

4.
Answer: Presumably no tags should be there past the opening PHP tag. As recommended in the manual, you can and should omit the closing PHP tag to make sure no whitespace shows up. It's not required though.

Example of wrong/poor answer: (Depends on if you agree with the answer above.)


5.
Answer: There are multiple answers, one is that as long as the if statement has one nested statement then it doesn't need opening and closing braces. If you do have multiple statements you can use if(): and endif; rather than the more common if(){ and }.

Example of wrong/poor answer: (Multiple lines without any closing syntax would be wrong.)

6.
Answer: Technically null is a variable type and NULL is a value and is the only value for null types. That's what the manual describes, but probably won't matter when you are writing code, just consider it trivia, and also remember $var = NULL; seems to be the official way to assign it.

Example of wrong/poor answer: null is never used (It is invalid or non-traditional in some languages)

7.
Answer: Name the constructor member function __construct().

Example of wrong/poor answer: Name  it construct(), init() or the class's name. (It's possible to get other language's syntax confused with PHP's)

8.
There are probably a lot of ways, but the answer we were looking for is the htmlentities() function. It makes sure that text appears as text and is not interpreted as tags or hidden characters.

Example of wrong/poor answer: Enclosing it in an element (such as pre or textarea) in an HTML document. (This could result in breaking the element tags or causing other issues.)

9.
Answer: Use the ksort() function on the array before it is printed, possibly with the SORT_NUMERIC flag.

Example of wrong/poor answer: (Sorting by looping and assigning a new array by numbers probably isn't a good choice)

10.
Answer: This is another bit of trivia. register_globals was made off by default in 2002 and it has generally (often emphatically) been suggested that it remain off. The reason that it was considered a problem was that it caused variables, GET and POST variables, to appear as normal variables. It had a tendency to increase bugs and vulnerabilities. Perhaps more importantly it encouraged the writing of confusing code with variables being used that may or may not have been defined, and that always needed register_globals. It was removed in 2012 along with safe_mode (source: PHP entry in Wikipedia).

Monday, January 13, 2014

JQuery Primer

JQuery is a library for JavaScript (browser based JavaScript technically). Think of JQuery as something that extends JavaScript's functions and features. JQuery improves any program that must work with web page elements by allowing the programmer to use less code, and avoid some possibilities for bugs and other difficulties (in theory a
nyway). On the other hand, if your JavaScript code doesn't interact with the web page much, if it is all math or string handling, then JQuery won't be worth adding to the project.

AJAX with JQuery


When using asynchronous connections to the server it is recommended that you use JQuery. These connections can be done with JQuery's ajax() function which provides many features in a convenient format. You can define functions as part of the ajax() call to handle success and failure of the connection. A typical application of this system is to first prepare data for the server connection, send the data with ajax(), wait for the response from the server, and finally you may perform other tasks that are set up to run on completion. While waiting for a response from the server the browser is not locked and can perform other tasks, unless you specifically set it to be non-asynchronous. Some examples of ways that this system can be used are:
Checking if a username exists
Searching a database
Getting a specific time period of records from a database
Saving user preferences to the server
Fetching the next section of items in a product catalog

HTML Elements and JQuery

A major reason to use JQuery is that it helps manipulate HTML elements. Even if it's only a little easier to do things the JQuery it's often worth it, and there are many reasons including cross-browser compatibility. HTML elements are anything you see on a web page, and of course it also includes elements in HTML that you don't see like the page description meta tag. You can edit, create, delete, and sometimes move these elements and change the web page completely. For a simplified example, suppose you wanted to take a particular <div> tag and put red text inside it. In your JavaScript code, first you would find the div tag and assign it to a variable. You now have the variable div_tag, and you can add text to it in JQuery with the html() function (note that this function replaces the current contents of the tag rather than appending). It has the text now but it isn't red. Use JQuery's css() function to add a color to div_tag (basically you are editing it's style attribute). I skipped over the part about how we find a particular div, and we're going to cover that now, because that's the really important thing to learn about JQuery.

Selectors and JQuery

Selectors are a syntax entered as strings into JQuery functions to find something. By default it searches the current HTML document, but selectors can be used on any text. To get you started with the selector syntax let's go back to the previous example where we want to assign a particular div to the variable div_tag so we can manipulate it. I'm using the $ sign in place of the word JQuery, because this is a common and acceptable way to abbreviate JQuery in code, but it's the same, JQuery() or $().
div_tag = $('div');
This assigns a div element to the variable div_tag right? Almost right, it actually selects all div tags and now div_tag is basically equal to all div tags. It's normal to be able to treat a group of elements as a variable like this, but we want to reduce that group to 1 element.
div_tag = $('div').eq(0);
That basically says, find all div tags, and give us the first, which is the one at index 0. That might work fine, but let's assume the div we want is the following HTML, and at an unknown position in the document:
<div id="message"></div>
Selecting an element with a particular id is easy, if you've used CSS this may not surprise you.
div_tag = $('#message');
That returns the element with the id attribute set to message, similar to the above example. There is only supposed to be 1 of each id in a document, and if that rule is broken then you will get multiple tags selected this way. The complete code for our example is:

div_tag = $('#message');
div_tag.html("Our new message...");
div_tag.css("color", "red");



Other Things to Do With JQuery

Events

Javascript can have code defined for events such as key presses. You can more easily make an action occure when a user presses a key if you are using JQuery.

Effects
Setting black text to red is just the beginning, JQuery can automate various effects that can make your web page animated and interactive.

jQuery UI
JQuery UI can give you greatly enhanced forms and other user interfaces providing widgets, themes, and more in a single package.

Plug-ins
If JQuery alone can't do something there's probably a plug-in for it that can. Extending JQuery can give you a powerful toolkit and may allow you to simplify your on page JavaScript to just a few lines. You can easily extend JQuery yourself with JavaScript code.

Tuesday, January 7, 2014

Apache htaccess

In this post we are going to quickly go through some explanations and techniques relating to .htaccess files. This information should help you diagnose problems or make quick adjustments without having to know everything. .htaccess is an Apache feature, so this post applies to Apache servers, and you can check the Apache documentation for details not covered here. Other servers might also implement .htaccess files, but you would have to check for the particular brand.

.htaccess files...

The file must be named .htaccess exactly, nothing before the dot. If you are trying to make the file on Windows you might find you can't name a file that, Windows will show a message saying you need a name before the extention, that means text before the "dot". Consider getting a program called Notepad++, it can save files with the .htaccess name on Windows and is good for editing them. The file is just plain text, and is in theory a list of commands, each command taking up one line.

You upload the file to...

The place on the server where the .htaccess file goes depends on the folders and files you want it to have an effect on. The effect it has is based on the commands in it, effects such as password protection, redirects, or URL rewriting. These effects are applied to the folder the .htaccess file is in, and any subfolders including folders and files in them. Therefore a .htaccess file in your root directory affects the whole website. There are exceptions though, otherwise this would be a little inflexible. If you have another .htaccess file in a subfolder it overrides the previous one, and it's effect extends to subfolders too.

Your First Command

Here's a simple command you can put in a file to get you started, or to test if .htaccess is operating normally.

redirect /my-path/my-file.php http://mywebsite.com

Replace the first path with the full path of the file to redirect. Replace the second path, the URL after the next space, with your website URL. It should now redirect to the destination URL. There are numerous other tasks that can be performed with commands, such as URL rewrites, custom error pages, MIME type and extension overrides, and blocking particular bots (or referrers or IP addresses).

Web Hosting Posts Blog: Fortunelight

This blog is written by Fortunelight Web Hosting  and is intended for readers who use web hosting or work on websites in some way. These posts are generally aimed at beginners and are there to help with general things and are written in a common language manner rather than emphasizing tech vocab.

Some programming topics will be covered in upcoming blog posts such as a JQuery introduction. If the technology of the web interests you please subscribe/bookmark, and if you need to contact us you can use our support contact.

Friday, January 3, 2014

Use JavaScript on Your Website

JavaScript is an interpreted programming language. In this post we are going to go through the basic ways to use JavaScript without trying to boggle the mind of the reader with the finer details of JavaScript programming. Consider it an introduction to the technology that should leave you with a grasp of what JavaScript is all about (but not a language/syntax guide).

What's in a name...

The name JavaScript is sometimes a source of confusion. It should not be viewed as a relative of Java, Java Server Pages, etc. It does qualify as a scripting language, and has a lot in common with popular scripting languages like PHP. Technically they could be used for the same tasks. However, in this post we are focusing on common usage of web programming, which brings us to our next topic.

Client Side Code
JavaScript can be used for many things and in many ways but the most common is to automate or program some aspect of web browsing. The PHP language can also be used for many things, but it's focus is producing or processing web pages (It's even implied in the name, he H in PHP stands for hypertext). In the common usage of these 2 languages PHP is doing it's work on web page data before it reaches your browser. PHP is running on the server, meaning the computer hardware hosting the web site. Your computer, for the most part, doesn't pay attention to what happens before it gets the web page data, it may not be aware that PHP or another programming language is being used. A web page, produced with or without PHP, may use JavaScript as well. The JavaScript will not run on the server but will wait until your browser receives it. Then the browser will decide to run the JavaScript code. Your computer, or the browser it's self, could be called the client, so that means the JavaScript was client side code.

JavaScript can be in an HTML Document

JavaScript can be used inside an HTML document and can be as minimal as a single command. For example, you could have a standard .htm file on your server and normally no programming would be needed. Then imagine you wanted to print todays date. You would add the following inside your HTML document:
<script>
var currentTime = new Date();
document.write(currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear());
</script>


The first line starts the JavaScript block. Sometimes the tag says <script type="text/javascript">, but in modern HTML5 documents it's officially acceptable, and probably best, to just use <script>. The second line is needed to initialize the date features we will use (technically we call it "creating a new Date object"). The third is getting and writing the date. The final part is a tag to leave the JavaScript block, meaning what comes after is HTML.

JavaScript Files


Have no fear, JavaScript files are as easy to work with as any other file containing web page code, and you can just enter JavaScript into a text editor, no script tags needed. JavaScript files are ".js" files. It's usually still intended to interact with a web page, so add something like this to the HTML document:
<script src="script.js"></script>
In this case the file is called "script.js", and is assumed to be in the same folder. In your case you will need to make a JavaScript file and enter a proper path.

Sometimes JavaScript files are included to provide features (functions, classes etc.) that a website will use in the HTML portion of the page, these features could include:
Date Selection Dialog Boxes
Plots/Graphs
Spell Check
Color Pickers
Lightboxes
Slideshows
Clocks
Arrangeable Tables
Fetching Data From the Server

When a downloadable file provides features and usable code it may be called a library, plug-in, or widget depending on the situation. One thing a lot of code relies on is a library called JQuery. It can be a lot easier to code JavaScript when you have Jquery included, and you often can access more features. Look for our upcoming article on JQuery.