Web Coding & Development All-in-One For Dummies book cover

Web Coding & Development All-in-One For Dummies

By: Paul McFedries Published: 05-15-2018

Speak the languages that power the web

With more high-paying web development jobs opening every day, people with coding and web/app building skills are having no problems finding employment. If you're a would-be developer looking to gain the know-how to build the interfaces, databases, and other features that run modern websites, web apps, and mobile apps, look no further. Web Coding & Development All-in-One For Dummies is your go-to interpreter for speaking the languages that handle those tasks.

Get started with a refresher on the rules of coding before diving into the languages that build interfaces, add interactivity to the web, or store and deliver data to sites. When you're ready, jump into guidance on how to put it all together to build a site or create an app.

  • Get the lowdown on coding basics
  • Review HTML and CSS
  • Make sense of JavaScript, jQuery, PHP, and MySQL
  • Create code for web and mobile apps

There's a whole world of opportunity out there for developers—and this fast-track boot camp is here to help you acquire the skills you need to take your career to new heights!

Articles From Web Coding & Development All-in-One For Dummies

page 1
page 2
page 3
29 results
29 results
What Is a Local Web Development Environment and Do You Need One?

Article / Updated 10-12-2018

Local web development environments are a useful tool for web coders. In programming circles, an integrated development environment (IDE) is a collection of software programs that make it easy and efficient to write code. Most development environments are tailored to a particular programming language and come with tools for editing, testing, and compiling code (that is, converting the code to its final form as an application). In the web coding game, there aren’t IDEs, per se, but there is a similar beast called a local web development environment, which is also a collection of software. It usually includes the following: A web server A relational database management system (RDBMS) to run on the web server A server-side programming language An interface for controlling (starting, stopping, and so on) the web server An interface for accessing and manipulating the RDBMS The key point to grok here is that this is a “local” web development environment, which means that it gets installed on your PC or Mac. This enables you to build and test your web development projects right on your computer. You don’t need a web hosting service or even an Internet connection, for that matter. Everything runs conveniently on your computer, so you can concentrate on coding and leave the deployment of the site until you’re ready. Do you need a local web development environment? Okay, if it’s possible to use a simple text editor to develop web pages, why not do just that? After all, every Windows PC and Mac in existence comes with a pre-installed text editor, and there are lots of free third-party text editors ripe for downloading, so why bother installing the software for a local web development environment? To be perfectly honest, a local web development setup isn’t a must for everyone. Certainly if all you’re doing for now is getting started with a few static web pages built using HTML, CSS, and JavaScript, then you don’t yet need access to the back end. Similarly, if you’re building websites and web apps for your own use and you already have a web host that gives you access to MySQL and PHP, then you can definitely get away with using just your trusty text editor. However, there are two major exceptions that pretty much require you to build your web stuff locally: If you’re building a website or app for someone else and you don’t have access to their web server. If you’re building a new version of an existing website or app, which means that you don’t want to mess with the production code while tinkering (and therefore making mistakes) with the new code. That said, there’s also something undeniably cool about having a big-time web server purring away in the background of your computer. So, even if you don’t think you’ll need a full-blown web-development environment in the short term, think about installing one anyway.

View Article
Working with Images in a Mobile App

Article / Updated 07-12-2018

When planning a mobile web app, you always need to consider the impact of images, both on your design and on your users. Making images responsive On the design side, you need to ensure that your images scale responsively, depending on the screen width or height. For example, if the user’s screen is 1,024 pixels wide, an image that’s 800 pixels wide will fit no problem, but that same image will overflow a 400-pixel-wide screen. You create responsive images with the following CSS rule: image { max-width: 100%; height: auto; } Here, image is a selector that references the image or images you want to be responsive. Setting max-width: 100% enables the image width to scale smaller or larger as the screen (or the image's container) changes size, but also mandates that the image can’t scale larger than its original width. Setting height: auto cajoles the browser into maintaining the image’s original aspect ratio by calculating the height automatically based on the image’s current width. Occasionally, you’ll want the image height to be responsive instead of its width. To do that, you use the following variation on the preceding rule: image { max-height: 100%; width: auto; } Delivering images responsively On the user side, delivering images that are far larger than the screen size can be a major problem. Sure, you can make the images responsive, but you’re still sending a massive file down the tubes, which won’t be appreciated by those mobile surfers using slow connections with limited data plans. Instead, you need to deliver to the user a version of the image file that’s appropriately sized for the device screen. For example, you might deliver the full-size image to desktop users, a medium-sized version to tablet folk, and a small-sized version to smartphone users. That sounds like a complex bit of business, but HTML5 lets you handle everything from the comfort of the tag. The secret? The sizes and srcset attributes. The sizes attribute is a collection of expression-width pairs: The expression part specifies a screen feature, such as a minimum or maximum width, surrounded by parentheses. The width part specifies how wide you want the image displayed on screens that match the expression. For example, to specify that on screens up to 600 pixels wide you want an image displayed with a width of 90vw, you'd use the following expression-width pair: (max-width: 600px) 90vw A typical sizes attribute is a collection of expression-width pairs, separated by commas. Here’s the general syntax to use: sizes="(expression1) width1, (expression2) width2, etc., widthN" Notice that the last item doesn’t specify an expression. This tells the web browser that the specified width applies to any screen that doesn’t match any of the expressions. Here’s an example: sizes="(max-width: 600px) 90vw, (max-width: 1000px) 60vw, 30vw" The srcset attribute is a comma-separated list of image file locations, each followed by the image width and letter w. Here's the general syntax: srcset="location1 width1w, location2 width2w, etc."> This gives the browser a choice of image sizes, and it picks the best one based on the current device screen dimensions and the preferred widths you specify in the sizes attribute. Here's a full example: The sizes and srcset attributes don't always work the way you might expect. For example, if the browser finds that, say, the large version of the image is already stored in its cache, then it will usually decide that it’s faster and easier on the bandwidth to just grab the image from the cache and scale it, instead of going back to the server to download a more appropriately sized file for the current screen.

View Article
Going Mobile Faster with jQuery Mobile

Article / Updated 07-12-2018

It's safe to say that jQuery makes web development faster, easier, and even more pleasurable. Now let’s talk briefly about yet another jQuery library: jQuery Mobile, which offers widgets optimized for mobile web apps. What is jQuery Mobile? Most folks nowadays have a mobile device of some description, which means that most people are used to doing our digital duties using mobile interfaces. These interfaces include standard mobile elements such as fixed headers and footers, navigation bars, list views, tabs, switches that turn on and off, and hidden menus invoked by a “hamburger” icon. Coding elements such as these is possible, but it would be a ton of work. Fortunately, you can skip all of that because the hardcore geeks at jQuery Mobile have done it all for you. jQuery Mobile is a set of mobile-optimized widgets that make it easy for you to design your mobile web app to have the look and feel of a native mobile app. Best of all, the jQuery Mobile components work just like the jQuery UI widgets. Now all you have to do is incorporate jQuery Mobile into your app. Adding jQuery Mobile to your web app jQuery Mobile consists of two files: A JavaScript (.js) file that you add to your page by using a </code> tag with a reference to the external script file.</li> <li>A CSS (<code>.css</code>) file that you add to your page by using a <code><link rel="stylesheet"></code> tag with a reference to the external CSS file.</li> </ul> How do you get these files? You have three ways to go about it: <ul> <li><strong>Download the files and use the default jQuery Mobile styles.</strong> In this case, surf to <u><a href="http://jquerymobile.com/download/">jquerymobile.com/download</a></u> and click the ZIP File link. The file you get will have a name like <code>jquery.mobile-1.<em>x</em>.<em>y</em>.zip</code>, where <em>x</em> and <em>y</em> denote the current version. Decompress the ZIP file and then copy the jquery.mobile-1.<em>x</em>.<em>y</em>.min.js and <code>jquery.mobile-1</code>.<em>x</em>.<em>y</em>.min.css files to your mobile web app's JavaScript and CSS folders. Then set up your <code><link></code> and <code><script></code> tags to reference the files:</li> </ul> <pre class="'code""><link rel="stylesheet" href="/css/jquery.mobile-1.<em>x</em>.y.min.css"> <script src="/js/jquery.mobile-1.<em>x</em>.<em>y</em>.min.js"> (Remember to replace x and y with the actual version numbers of your downloaded file.) Use custom jQuery Mobile styles. In this case, surf to themeroller.jquerymobile.com and use the ThemeRoller app to set your custom colors, fonts, and other styles. Click the Download Theme ZIP File button, type a theme name, and then click Download ZIP. Decompress the downloaded ZIP file, copy the CSS file from the Themes folder, and then add it to your mobile web app's CSS folder. Then set up your tag to reference the file: Replace custom with the custom theme name you provided. Note that this only gives you the CSS for jQuery Mobile. You still need to download the jQuery Mobile JavaScript file. Link to a remote version of the file. Several content delivery networks (CDNs) store the jQuery Mobile files and let you link to them. Here are the tags to use for Google's CDN: Again, in both cases, be sure to replace x and y with the actual version numbers of the latest version of jQuery Mobile. You also need to add jQuery to your page. However, currently, jQuery Mobile is only compatible with version 2 of jQuery, so be sure to link to that version, not version 3.

View Article
What Is Mobile-First Web Development?

Article / Updated 07-12-2018

When you develop a web page to look good and work well on a desktop-sized screen, there are a number of responsive tricks you can employ to make that same code look good and work well on a mobile device screen: You can use percentages for horizontal measurements. You can use relative units such as em and rem for vertical measurement and font sizes. You can use media queries to remove elements when the screen width falls below a specified threshold. That third technique — the one where you remove stuff that doesn't fit on a smaller screen — is known in the web coding trade as regressive enhancement (RE). RE has ruled the web development world for many years, but lately there’s been a backlash against it. Here’s why: RE relegates mobile screens to second-class web citizens. RE leads to undisciplined development because coders and designers inevitably stuff a desktop-sized screen with content, widgets, and all the web bells and whistles. What’s the solution? You’ve probably guessed it by now: progressive enhancement, which means starting with content that fits on a base screen width and then adding components as the screen gets bigger. When that original content represents what’s essential about your page, and when that base screen width is optimized for mobile devices — especially today’s most popular smartphones — then you’ve got yourself a mobile-first approach to web development.

View Article
Setting Up the Back End to Handle Users

Article / Updated 07-12-2018

Before your web app is usable, you’ll need set up the back end to handle users. Most web apps that manage users need to implement at least the following tasks: Signing up new users: Includes not only capturing the user’s email address (to use as a username) and password, but also sending out a verification email to make sure the user isn’t a bot or spammer Signing in users: Enables each user to access her own data Signing out users: Prevents others from accessing a user’s account when his computer is left unattended Updating user data: Enables each user to change her password and to reset a forgotten password Deleting users: Enables a user to remove his account and data from the server Here’s the bird’s-eye view of what you’ll be doing: Build a class for handling user interactions. That class includes one method for each of the preceding tasks. Provide the user with an interface for signing up, signing in, signing out, modifying account data, and deleting the account. To start processing a user task, set up an event handler for each account-focused interface element. If you’re using a sign-in form, for example, then you might set up a submit event handler for that form. Use each event handler to send the form data to a single PHP script via Ajax. Importantly, that form data includes the value of a hidden field that specifies the type of “user verb” being performed (sign up, sign in, reset password, and so on). In the PHP script, create a new object from the class of Step 1, check the user verb sent by the Ajax call, and then call the corresponding class method. For example, if the event is signing up a new user, the script would call the class method that handles creating new user accounts. Starting the web app's user class The class for your web app’s users needs to do at least the following three things: Accept a parameter that references the current MySQLi object. Define a method for each of the user verbs. Define any helper functions required by the user verbs. With these goals in mind, here’s the skeleton class file: _mysqli = $mysqli; } // Here are the user chores we need to handle public function createUser() { } public function verifyUser() { } public function signInUser() { } public function sendPasswordReset() { } public function resetPassword() { } public function getDistanceUnit() { } public function updateDistanceUnit() { } public function deleteUser() { } } ?> The class declares the private property $_mysqli, which it uses to store the current instance of the MySQLi object (created earlier in the initialization.php script). Store this file in private/classes/user_class.php. To create an instance of this class, you'd use a statement similar to the following: $user = new User($mysqli); Creating a user handler script The various user verbs will be initiated via Ajax calls to a single PHP script. Each Ajax call needs to specify the user verb required, and the PHP code routes the request to the corresponding method in the User class. Here’s the PHP script, which you can save as public/handlers/user_handler.php: createUser()); break; // Sign in an existing user case 'sign-in-user': $server_results = json_decode($user->signInUser()); break; // Send a request to reset a user's password case 'send-password-reset': $server_results = json_decode($user->sendPasswordReset()); break; // Reset a user's password case 'reset-password': $server_results = json_decode($user->resetPassword()); break; // Get the user's distance unit case 'get-distance-unit': $server_results = json_decode($user->getDistanceUnit()); break; // Update distance unit case 'update-unit': $server_results = json_decode($user->updateDistanceUnit()); break; // Delete a user case 'delete-user': $server_results = json_decode($user->deleteUser()); break; default: $server_results['status'] = 'error'; $server_results['control'] = 'token'; $server_results['message'] = 'Error: Unknown user verb!'; } } // Create and then output the JSON data $JSON_data = json_encode($server_results, JSON_HEX_APOS | JSON_HEX_QUOT); echo $JSON_data; ?> After initializing the app by including initialization.php, the code also includes the User class file. The code then sets up an array named $server_results, which holds the results that the script sends back to the front end: $server_results['status'] will be either success or error. $server_results['message'] holds the success or error message to display. The code next runs through a series of checks: making sure a verb was passed, making sure a token value was passed, and then comparing that token value with the session token. If the code gets past those tests, a switch() statement runs through the possible values for $_POST['user-verb'] and calls the corresponding User method.

View Article
Creating the App Startup Files for Your Web App

Article / Updated 07-12-2018

All web apps perform a number of chores at the beginning of any task. On the back end, these initialization chores include starting a user session and connecting to the database, and on the front end the startup includes outputting the app's common HTML (especially the section) and including the app’s common components, such as a header and footer. Rather than repeating the code for these startup chores in every file, you should create two files — one for the back end initialization and one for the front end’s common code — and then include the files as you begin each web app task. Creating the back-end initialization file When performing any task, a typical web app must first run through a number of back-end chores, including the following: Setting the error reporting level Starting a session for the current user, if one hasn’t been started already Creating a token for the session Including common files, such as a file of constants used throughout the app Connecting to the database, if the app uses server data You should store this file in your web app’s private/common/ directory.: $_SESSION['token_expires']){ $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(16)); $_SESSION['token_expires'] = time() + 900; $_SESSION['log_id'] = 1; } // Include the app constants include_once 'constants.php'; // Connect to the database $mysqli = new MySQLi(HOST, USER, PASSWORD, DATABASE); // Check for an error if($mysqli->connect_error) { echo 'Connection Failed! Error #' . $mysqli->connect_errno . ': ' . $mysqli->connect_error; exit(0); } ?> This code cranks up the error reporting to 11 for the purposes of debugging, starts a new session, creates a session token (if needed), includes the constants file (which contains the database credentials), and then connects to the database and creates a MySQLi object. Note, too, that $_SESSION['log_id'] was set to 1, but this is temporary. You want to use error_reporting(E_ALL | E_STRICT) when you’re developing your web app because you want the PHP processor to let you know when something’s amiss, either as an error (E_ALL) or as non-standard PHP code (E_STRICT). However, you certainly don't want your app’s users to see these errors or warnings, so when you’re ready for your web app to go live, edit initialization.php to follow this statement: error_reporting(E_ALL | E_STRICT) with these statements: ini_set('display_errors', 0); ini_set('log_errors', 1); ini_set('error_log', '../private/logs/error_log'); These statements configure PHP to not display errors onscreen, but to log them to a file, the name and path of which is specified in the final statement. Creating the front-end common files Each page of your web app has a common structure. For example, the top part of each page includes the following elements: The DOCTYPE and the tag The head element, including the tags, page title, CSS tags, and JavaScript </code> tags</li> <li>An event handler for jQuery's <code>ready</code> event</li> <li>The <code><body></code> tag</li> <li>Common page elements, such as the <code><header></code>, <code><nav></code>, and <code><main></code> tags</li> </ul> Here's an example, which is named <code>public/common/top.php</code>: <pre class="code"><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FootPower! | <?php echo $page_title ?></title> <link href="css/styles.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> $(document).ready(function() { }); In this code, note that the page title is given by the following inline PHP: The idea here is that each page will set the $page_title variable just before including top.php, which enables you to define a custom title for each page. For example, the home page might do this: Note that this same title also gets inserted in the page header element, within the tag. Most web apps also include a sidebar — defined by an tag — that includes info common to all pages, such as a description of the app, instructions for using the app, the latest app news, or a newsletter sign-up form. For this sidebar, create a separate file called, say, public\common\sidebar.php and include your code: Your sidebar text and tags go here Finally, you need a file to handle the common elements that appear at the bottom of each page, including the closing tag, a footer, and the and closing tags. For this code, create a separate file called, say, public\common\bottom.php and add your code: Copyright Your Name The footer uses the PHP statement echo date('Y') to output the current year for the Copyright notice. This file also adds references to the app's two external JavaScript files: data.js and user.js. Adding these at the bottom of the page (instead of the usual place in the page's head section) ensures that your JavaScript code can work with the elements added to the page on the fly. Building the app home page With the initialization files in place, it’s time to build the skeleton for the app’s home page. At the moment, this page is nothing but PHP: ="code"> Main app content goes here Save this file as index.php in the web root directory.

View Article
Planning Your Web App for Accessibility

Article / Updated 07-12-2018

When planning a web app, the thoughtful developer remains aware at all times that the people who visit and use the app come with different abilities. When planning a web app, the ethical developer understands that, even though every person is different, they all have an equal right to use the app. When you give everyone equal access to your web app, you're making your app accessible. Planning for accessibility means taking the following impairments into account: Visual: Includes full or partial blindness, color-blindness, and reduced vision. Auditory: Includes full or partial deafness, difficulty hearing, the inability to hear sounds at certain frequencies, and tinnitus. Motor: Includes the inability to use a pointing device such as a mouse, restricted movement, lack of fine motor control, excessive trembling or shaking, and slow reflexes or response times. Cognitive: Includes learning disabilities, focusing problems, impaired memory, and extreme distractibility. An accessible design is the right choice ethically, but it’s also the right choice practically because a significant percentage (estimates range from 5 to 20 percent) of the people who use your web app will exhibit one or more of the above disabilities in varying degrees. Fortunately, as long as you build your app with equal access in mind from the get-go, adding accessible features takes very little effort on your part. Before you get started, it’s a good idea to crank up a screen reading application so that you can test out how your web app works when “heard.” If you use Windows, start up the Narrator utility; if you’re on a Mac, fire up the VoiceOver utility. web app accessibility is a massive topic, but for our purposes you can boil it down to implementing the following techniques: Include alternative text for all images. For the visually impaired, a screen reader reads aloud the value of every tag’s alt attribute, so important or structural images should include a brief description as the alt value: You don't need to add an alt value for purely decorative images, but you must include the alt tag (set to an empty string: alt="") or your HTML code won't validate. Add an ARIA label to all form fields. ARIA stands for Accessible Rich Internet Applications, and it’s a technology for adding accessibility to web apps. When you add the aria-label attribute to an , , or </code> tag, the screen reader reads that attribute's text:</li> </ul> <pre class="code"><input type="radio" id="pony-express" name="delivery" value="pony" aria-label="Pony express delivery option"></pre> <ul> <li><strong>Add a label for all form fields.</strong> Adding the <code><label></code> tag — either by using the <code>for</code> attribute to reference the <code>id</code> of the corresponding field, or by surrounding the field with <code><label></code> and <code></label></code> tags — enables the user to select the field by also clicking the label. This increases the target area for clicking, which helps users with unsteady hands. Be sure to add a label for every <code><input></code> tag, as well as each <code><select></code> and <code><textarea></code> tag:</li> </ul> <pre class="code"><label for="user-email">Email address</label> <input id="user-email" type="email"></pre> <ul> <li><strong>Use headings hierarchically.</strong> All page headings should use <code><h1></code> through <code><h6></code> tags, where that order reflects the hierarchy of the heading structure: <code><h1></code> is the top-level heading in a section of the page, <code><h2></code> is the second-level heading in that section, and so on. Don't skip heading levels (say, by jumping from <code><h2></code> to <code><h4></code>).</li> <li><strong>Use semantic HTML5 page tags.</strong> These include <header>, <nav>, <main>, <article>, <section>, <aside>, and <footer>. These so-called <em>landmarks</em> help assistive technologies make sense of your web app. You should also add ARIA role attributes to these tags, as follows:</li> </ul> <pre class="code"><header role="banner"> <nav role="navigation"> <main role="main"> <article role="contentinfo"> <section role="contentinfo"> <aside role="complementary"> <aside role="note"> <footer role="contentinfo"></pre> <p style="padding-left: 30px;">Wait: two <code>role</code> possibilities for the <code><aside></code> tag? Yep: Choose the <code>role</code> value that best fits the content of the sidebar.</p> <ul> <li><strong>Add ARIA roles to non-semantic elements.</strong> If your app uses non-semantic elements, such as a jQuery UI or jQuery Mobile widget, you can alert assistive technologies to what the widget does by adding the <code>role</code> attribute and setting it equal to the widget's function in the app. Some example <code>role</code> values are <code>dialog</code>, <code>menu</code>, <code>menubar</code>, <code>progressbar</code>, <code>scrollbar</code>, <code>slider</code>, <code>tab</code>, <code>tablist</code>, <code>tabpanel</code>, and <code>toolbar</code>. For example, here's how you’d add the various tab-related roles to jQuery UI’s Tabs widget:</li> </ul> <pre class="code"><div id="my-tabs"> <ul role="tablist"> <li><a href="#my-tab-1" role="tab">This</a></li> <li><a href="#my-tab-2" role="tab">That</a></li> <li><a href="#my-tab-3" role="tab">The Other</a></li> </ul> <div id="my-tab-1" role="tabpanel"> This is the first tab's content. </div> <div id="my-tab-2" role="tabpanel"> This is the second tab's content. </div> <div id="my-tab-3" role="tabpanel"> Yep, this is the third tab's content. </div> </div> </pre> <p class="article-tips tip">Check out <a href="https://developer.mozilla.org/en-US/docs/web/Accessibility/ARIA/ARIA_Techniques">Mozilla Developer Network’s Using ARIA page</a> to see a complete list of ARIA roles.</p> <ul> <li><strong>Ensure your app’s colors have sufficient contrast.</strong> If text colors too closely match the background color, the text will be hard to decipher, particularly for the visually impaired.</li> </ul> <p class="article-tips tip">Once your app is on the web, you can check its accessibility by heading over to the <a href="http://wave.webaim.org">Web Accessibility Evaluation Tool (WAVE)</a>. Paste your web app’s address into the text box and press Enter/Return to see a report.</p>

View Article
Understanding the Dangers to Your Web App

Article / Updated 07-12-2018

There are, it often seems, almost as many security exploits as there are lowlifes trying to compromise our web apps. However, the most common security dangers fall into four main categories: SQL injection, cross-site scripting, insecure file uploads, and unauthorized access. SQL injection Probably the most common exploit, SQL injection involves inserting some malicious code into an ordinary SQL command, such as a SELECT or DELETE statement. Consider the following sign-in form: User name: Password: When this form is submitted, a PHP script to sign in the user might look, in part, like this: That works fine as long as the user types a legit username and password, but what happens if some scoundrel types admin' # in the user field and nothing at all in the password field? Here's the resulting value of the $sql variable: SELECT * FROM users WHERE username='admin' #' AND password='' The key here is the hash symbol (#), which marks the beginning of a comment in an SQL command, meaning that the rest of the line is ignored. (Just so you know, MySQL also uses -- to mark the start of a comment.) That is, the actual SQL command that gets processed is this: SELECT * FROM users WHERE username='admin' Congratulations, some criminal has just signed in as the administrator! As another example, suppose your web app has a button that, when clicked, deletes an item from the current user's data. Your Ajax call might pass along a user-id and an item-id, meaning that your PHP script would do something like the following to remove the specified item: Looks fine from here, but suppose some fiend passes the following as the user-id value: whatever' OR 1=1 #. Assuming the item-id value is blank, here's the resulting $sql variable value: DELETE FROM items WHERE userid='whatever' OR 1=1 #' AND itemid='' Taking the comment symbol (#) into account, the actual command looks like this: DELETE FROM items WHERE userid='whatever' OR 1=1 The 1=1 part always returns TRUE, so the result is that the command deletes everything from the items table! Cross-site scripting (XSS) Cross-site scripting (usually shortened to XSS) is a way of surreptitiously forcing an innocent user to launch an attacker's malicious script. This most often happens when the malefactor uses a phishing email or similar ruse to trick the user into visiting a page that spoofs a form used on a legitimate site. For example, suppose the form asks the user to enter her credit card number and password. If this was a normal form submission and the user entered either the wrong credit card number of the wrong password, the PHP script on the server might redisplay the form to ask the user to try again: '; echo ''; ?> Notice, in particular, that this “helpful” script redisplays the credit card value (stored in the $cc variable) in the text field. Imagine, then, that our attacker’s spoofed form actually sends the following text instead of the credit card number: ">alert(&apos;Ha ha!&apos;); alert('Ha ha!'); What happens here? That’s right: The JavaScript code between the </code> and <code> tags executes. In the real world it's unlikely to just display an innocuous alert box. Insecure file uploads If your web app allows users to upload files — for example, you might want to allow each user to upload a small image to use as a profile avatar — then you open up a new can of security worms because a malicious user can: Upload huge files, which tax the server’s resources. Upload a nasty script instead of, say, an image. Overwrite existing server files. Unauthorized access If your web app requires users to sign in with a username (or email address) and password, then keeping those passwords secure is of paramount importance. Otherwise, an unauthorized interloper could sign in as a legitimate user and either destroy or tamper with that user’s data, post messages or other content under that user’s name, and even delete the user’s account.

View Article
Planning Your Web App for Responsiveness

Article / Updated 07-12-2018

A web app is something like the online equivalent of a desktop program, but that doesn’t mean you should build your web app to look good and work properly only on desktop-sized screens. Why not? For the simple reason that your app’s visitors will be using a wide range of device sizes, from PCs with gigantic displays several feet wide, all the way down to smartphones with screens just a few inches wide. On the modern web, one size definitely does not fit all, so you need to plan your app so that its user experience (UX, to the cognoscenti) — that is, what visitors see and interact with — is positive for everyone. To make your web app look good and operate well on any size screen, you need to plan your app with responsiveness in mind. A responsive web app is one that changes its layout, styling, and often also its content to ensure that the app works on whatever screen the reader is using. To see why you need to code responsively from the start of your web app, consider the two main non-responsive layouts you could otherwise use: Fixed-width: A layout where the width of the content is set to a fixed size. In this case, if the fixed-width is greater than the width of the screen, most of the time the user has to scroll horizontally to see all the content. No-width: A layout where the width of the content has no set width. You might think having no width would enable the text and images to wrap nicely on a small screen, and you’d be right. However, the problem is on larger screens, where your text lines expand to fill the browser width and, as you can see, those lines can become ridiculously long, to the point where scanning the lines becomes just about impossible. To work around these problems and to ensure your web app looks good on any screen size, you need to implement the following responsive techniques: Set the viewport: To ensure that your layout works well in smaller screens, use the following tag to tell the browser to set the viewport width to the width of the current device's screen, and to set the viewport’s zoom level to 1 (that is, not zoomed in or zoomed out). Liquid layout: A layout in which the overall width is set to a maximum (so that text lines never get too long to read), but the page elements have their widths set in percentages (or a similar relative measure such as viewport width: vw). Since even really old web browsers support percentages, this is a good fallback layout to use. For example: CSS: body { max-width: 800px; } article { width: 67%; } aside { width: 33%; } HTML: Flexible layout: A layout that uses flexbox to automatically wrap items when the browser window is too narrow to contain them. You set the container’s flex-wrap property to wrap, as shown in the following example: CSS: body { max-width: 800px; } main { display: flex; flex-wrap: wrap; } article { flex-grow: 2; flex-shrink: 0; flex-basis: 300px; } aside { flex-grow: 1; flex-shrink: 0; flex-basis: 150px; } HTML: Adaptive layout: A layout that changes depending on the current value of certain screen features, such as width. An adaptive layout uses a CSS feature called a media query, which is an expression accompanied by a code block consisting of one or more style rules. The expression interrogates some feature of the screen, usually its width. If that expression is true for the current device, then the browser applies the media query's style rules; if the expression is false, the browser ignores the media query’s rules. Here’s the syntax: @media (expression) { Style rules go here } Here’s an example that applies two style rules whenever the current screen width is less than or equal to 767px: @media (max-width: 767px) { header { height: 48px; } .site-title { font-size: 24px; } } Responsive images: Renders an image fluidly so that its size adjusts to different screen sizes. Ideally, you want the image to scale no larger than its original size to avoid ugly pixilation and jagged edges, and you want the width and height to maintain the original aspect ratio so that the image doesn’t look skewed when its size changes. You can achieve both goals by styling the image with the declarations max-height: 100%, which allows the image to scale but to grow no larger than its original size, and height: auto, which tells the browser to adjust the height automatically as the width changes. (Alternatively, you can set width: auto to get the browser to adjust the width automatically as the height changes). Here's an example: .aside-img { max-height: 100%; height: auto; } Responsive typography: Renders font sizes and vertical measures with the relative units em or rem rather than fixed-size pixels (px); renders horizontal measures in percentages (%) instead of pixels (px). Using relative measurement units enables the page typography to flow seamlessly as the screen size changes.

View Article
How to Code Form Submission

Article / Updated 07-12-2018

There’s one form event that you need to know about when coding dynamic web forms with HTML5 forms and it’s a biggie: the submit event, which fires when the form data is to be sent to the server. Here's the general syntax: $(form).submit(function(e) { Submit code goes here }); form: A selector that specifies the form you want to monitor for the submit event. e: This argument represents the event object. You'll rarely, if ever, allow the submit event to occur directly. Instead, you’ll want to intercept the submit so that you can gather the data and then send it to the server yourself using an Ajax call. Handling the submit event yourself gives you much more control over both what gets sent to the server and how what gets sent back from the server gets processed. Triggering the submit event Here's a list of the various ways that the submit event gets triggered: When the user clicks a button or input element that resides within a tag and has its type attribute set to submit When the user clicks a button element that resides within a tag and has no type attribute When the user presses Enter or Return while a form element has the focus, and either a button or input element resides within the tag and has its type attribute set to submit, or a button element resides within the tag and has no type attribute When your code runs jQuery's .submit() method: $(form).submit(); form: A selector that specifies the form you want to submit Preventing the default form submission You control the form submission yourself by sending the data to the server with an Ajax call. The submit event doesn't know that, however, and it will try to submit the form data anyway. That’s a no-no, so you need to prevent the default form submission by using the event object’s preventDefault() method: $('form').submit(function(e) { e.preventDefault(); }); Preparing the data for submission Before you can submit your form data, you need to convert it to a format that your server's PHP script can work with. The format depends on the Ajax request method you want to use: GET: This format requires a string of name=value pairs, separated by ampersands (&). To convert your form data to this format, use jQuery’s serialize() function: $(form).serialize(); form: A selector that specifies the form you want to work with POST: This format requires an array of key: value pairs, separated by commas (,). To convert your form data to this format, use jQuery's serializeArray() function: $(form).serializeArray(); form: A selector that specifies the form you want to work with For example: var formData = $('form').serialize(); Most commonly, your code stores the result of the serialize() or serializeArray() function in a variable, and that variable gets submitted to the server. Submitting the form data Now you're almost ready to submit the data. As an example, here’s some HTML code for a form and div that you can use to output the form results: First name: Last name: Nickname: Submit Now here’s the JavaScript/jQuery code that submits the form (using .get() in this case) and processes the result (which just echoes back the form data): $('form').submit(function(e) { // Prevent the default form submission e.preventDefault(); // Convert the data to GET format var formData = $(this).serialize(); // Submit the data using an Ajax GET request $.get('php/echo-form-fields-get.php', formData, function(data) { // Show the data returned by the server $('.output').html(data); }); }); Don’t forget to validate your form!

View Article
page 1
page 2
page 3