Home > Tags > web applications
Page 1

Common PHP File Upload Restrictions

From family photos to business documents, file uploads power many of the major web applications. A typical HTML form that allows the user to upload a file may look like this:

<html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> File Name: <input type="file" name="file" id="file" />  <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>

In this case, the only field displayed on the form is the “file” field.  This field allows the user to browse their hard drive for the file they wish to upload. The enctype “multipart/form-data” specifies that the field should be filled with binary data, as from a file, rather than typed input from the user. PHP applications allow users to upload files through its $_FILES object. Developers can use the $_FILES object to check on the properties of an uploaded file:

$_FILES["file"]["name"] – the name of the uploaded file $_FILES["file"]["type"] – the type of the uploaded file $_FILES["file"]["size"] – the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] – the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] – the error code resulting from the file upload

For files that upload successfully, the value of $_FILES["file"]["error"] is 0. However, some developers may want to place restrictions on the files users can upload.

File Type

Developers can use the $_FILES["file"]["type"] property to limit the types of files uploaded to those in use for specific applications. For instance, businesses may wish to restrict file types to documents, spreadsheets and presentations, but not allow users to post photos, videos or executable programs.

<?php if (($_FILES["file"]["type"] != "application/msword") || ($_FILES["file"]["type"] != "application/vnd.ms-excel ") || ($_FILES["file"]["type"] != "application/vnd.ms-powerpoint"))   {   echo "Invalid file type";   } ?>

File Size

Network administrators may also choose to limit the size of files users can upload to a server in order to reduce bandwidth usage. Developers can set limits on the size of a file a user can upload.

<?php if ($_FILES["file"]["size"] < 25000)) // Max File Size: 25KB   {   echo "File size exceeds maximum.";   } ?>

Upload Timed Out

Another method that administrators use to conserve bandwidth is to limit the time that a page can use to upload a file. Most PHP applications time out after 30 seconds, but the developer can set the time to as little or as much as needed by changing either the php.ini file on the server or setting the time in the application itself. PHP.INI File max_input_time 300

PHP Script

<?php // code to upload file to temporary directory ini_set('max_input_time', 300); // code to move file to new directory ?>...
more →
Eric Wilson says: I would say understanding how to securely store and access an uploaded file is more important than how you upload it. For...

Learning LESS: Put It Into Action

We’ll finish our Learning LESS series today as we talk about putting your LESS into action on your web projects. Today’s post will be slightly different than previous posts, as we won’t really showcase new techniques and code examples as much as we’ll talk about how to use LESS, projects you can work on to jump start your LESS development and more.

Blog Series Roadmap

An Introduction Using Variables Using Mixins Using Nested Rules Using Functions Divide and Conquer Put It Into Action

Coding With LESS

If you read our introduction to the Learning LESS series, you saw that I recommend compiling all of your LESS locally, and simply linking to one CSS stylesheet. Two of the top programs to do this is LESS.app and CodeKit, both from Incident57.

LESS.app

LESS.app is a free application that will detect all of the LESS files in your web folder, and compile them to CSS. You can set specific output folders and select which LESS files you actually want to compile (this comes in handy if you’ve divided up your LESS into smaller modular files and import them all into one stylesheet). Additionally, you can minify your CSS from this application, saving your precious file size (but don’t even think about editing your CSS file).

CodeKit

CodeKit is the next generation of the LESS.app and has a $20 price tag attached to it (to help the creator pay off his student loans, so in reality, it aint that bad). CodeKit compiles LESS perfectly, but does a lot more. It also compiles Sass, Stylus, Haml, Coffeescript, JavaScript and Compass files. Granted, I don’t know much about those other file types (other than JavaScript), but … CodeKit can compile them! Additionally, CodeKit has a pretty awesome feature where when you save your code, your browser will automatically refresh to reflect the changes, and it does it with some cool CSS3 animations.

LESS Projects

If you want to get a jump start on using LESS in your projects, I’d recommend grabbing an open source project that already utilizes LESS. It’s the best way to dig into the techniques and tricks that experienced and expert web developers use on their projects. I’ll run through a series of projects that I utilize on a daily basis that uses LESS.

Bootstrap, from Twitter

Bootstrap, from Twitter is one of the most popular open source projects on the web right now. Developed by Mark Otto and Jacob from Twitter, Bootstrap is a set of HTML, CSS and JavaScript components for baseline user interface components and interactions, including a responsive design, UX items such as buttons, forms, and more.

Bootstrap uses LESS as the basis for all of their styles, and really divides up their code into small, modular files, which becomes extremely maintainable and easy to understand.

Responsive Bones Theme for WordPress

If you’re into designing and developing for WordPress, might I suggest starting with Bones? There are a lot of WordPress starter themes out there, but in my opinion, not much do it better than Eddie Machado’s Bones.

The responsive version of Bones uses LESS to structure a responsively designed WordPress site, using CSS3 media queries to determine which LESS file is loaded into the compiler. It’s a pretty nifty system, and definitely worth a look if you’re looking at working with WordPress.

320 and Up Project

320 and Up is the ‘tiny screen first’ responsive boilerplate. This project is a perfect starting point for those looking to create a responsive website, but not building it straight into a CMS. If you’re just looking for a website, or will be looking to import it into another CMS like ExpressionEngine, 320 and Up is the place to be.

The project uses LESS to create a responsive framework for you to style up, starting with the smaller screens and working up, as opposed to designing for a desktop and scaling down. It’s an interesting concept, and definitely one to check out!

Conclusion

That wraps up our Learning LESS series here on DeveloperDrive. Thanks so much for reading, commenting and discussing. Do you have any other projects you know that use LESS that you use? Leave them in the comments below.

...
more →
BuiltInOneDay says: @Rick2079 @Stefan Hey guys just to follow up Alex is writing up an article on Sass and compass if you have not already been...

A Simple Way to Add Free News Content to Your Website Part 2

In the first part of this tutorial, detailed information was provided on utilizing RSS (Really Simple Syndication) coding to incorporate free news content and links into any web page.

It is recommended that you review Pt. 1, because it explains more about RSS and reveals how to integrate a basic newsfeed module using Google Feed API.

The goal of this tutorial is to furnish instructions on adding a larger news content module, a horizontal newsfeed, and a list-format style feed.

Let’s get started. The idea of incorporating free news content links into your website, blog, or online newsletter may sound intriguing, but you might want it to occupy a larger designated area than required for a small, four-link module. Also, rather than manually changing the RSS coding to accommodate different news sources, you’d prefer to list a number of them all at once. The perfect solution is a multiple-source newsfeed.

Vertical Newsfeed Module

To set the feed up, copy the coding below into the Head section of any web page. The entire set of lines should be slotted beneath the Title and Meta Tag areas, and just in front of the closing Head tag:

<style type="text/css"> @import url("http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css"); #feedControl { margin-top : 20px; margin-left: auto; margin-right: auto; width : 440px; font-size: 16px; color: #9CADD0; } </style> <script src="https://www.google.com/jsapi/" type="text/javascript"></script> <script src="http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js" type="text/javascript"></script> <script type="text/javascript"> function showControl() { var feeds = [ {title:'CNN', url:'http://rss.cnn.com/rss/edition_world.rss'}, {title:'NY Times', url:'http://feeds.nytimes.com/nyt/rss/World'}, {title:'Reuters', url:'http://feeds.reuters.com/Reuters/worldNews'}];...
more →
Querier says: Thank you for the helpful script. Would you please advise, how to change font size and font color for the first vertical RSS...

Learning LESS: Mixins

We continue on our journey of Learning LESS today as we dig into an extremely powerful component of LESS: Mixins. If you haven’t read our first two posts on the topic, check out Learning LESS: An Introduction and Learning LESS: Variables.

Blog Series Roadmap

An Introduction Using Variables Using Mixins Using Nested Rules Using Functions Divide and Conquer Put It Into Action

So let’s introduce LESS Mixins, and showcase some of what you can do with them.

What is a Mixin?

A Mixin in LESS is basically a common group of CSS properties grouped into one, which can then be inserted into various other LESS selectors. You can think of it like a variable, with several different properties.

Any ideas where this might come in handy? [Answer. CSS3.] And you’ll be very impressed at how powerful the mixins can be, as we have both Mixins and Parametric Mixins that can take a variable. You can also mixin Mixins with Mixins. And yes, I believe that is a grammatically correct sentence.

So starting with a basic Mixin, let’s create a scenario that you might use this in a web design project. Let’s say that the design you’re building uses a standard sans-serif font for the body copy, and a different serif font for headers. Instead of writing each font in each class (which could become cumbersome to manage if certain headers use different fonts), you can set the fonts within a mixin and include that class in other classes.

For this, we’ll create three classes, a serif class, sans-serif class and a monospace (code) class. Additionally, for the example, I’m going to throw in two variables which we learned in part two of our series. Let’s take a look at the code.

// Variables @baseFontSize: 14px; @baseLineHeight: 21px; .serif { font-family: Georgia, 'Times New Roman', serif; } .sans-serif { font-family: Helvetica, Arial, sans-serif; } .monospaced { font-family: 'Courier New', monospace; }

Pretty standard so far, right? By the way, the // denotes a comment in LESS and are not compiled with the LESS.app application. Standard CSS comments (/* */) will be compiled, but obviously not read. Let’s get into the meat ‘n potatoes of the Mixin.

Back to the code, check out how we format our paragraph tag.

p { font-size: @baseFontSize; line-height: @baseLineHeight; .serif; }

As you can see, we set the font-size and line-height using the variables we defined, which are pretty self explanatory. We then set our font by just calling the class serif within the properties for the paragraph. This mixin acts very much like a variable. The .serif mixin stores all of the properties in “.serif” and when compiled, all of the properties are then included in the paragraph properties.

Let’s look at the compiled version.

.serif { font-family: Georgia, 'Times New Roman', serif; } .sans-serif { font-family: Helvetica, Arial, sans-serif; } .monospaced { font-family: 'Courier New', monospace; } p { font-size: 14px; line-height: 21px; font-family: Georgia, 'Times New Roman', serif; }

The result of the compiled LESS is clean and streamlined CSS. What would happen if we simply changed the .serif to .sans-serif? So our LESS now reads:

p { font-size: @baseFontSize; line-height: @baseLineHeight; .sans-serif; }

And our output becomes:

p { font-size: 14px; line-height: 21px; font-family: Helvetica, Arial, sans-serif; }

That should give you a glimpse into how amazingly powerful making quick changes in LESS can be. But we’re not done yet, let’s take a look at Parametric Mixins.

Parametric Mixins

Parametric Mixins are just like regular mixins, but similar to functions they can accept parameters to attach to the code within the mixin. With these, you can set the parameter in your mixin or you can define a variable within your parameter for a default option.

This is perfect to use when you’re working with CSS3 properties and you need to declare your browser prefixes, but you can use the properties in different ways. For this example, we’ll use border-radius. Our mixin looks like this:

.border-radius(@radius) { -webkit-border-radius: @radius; -moz-border-radius:...
more →
Thomas says: if you add an empty pair of brackets to the class definition, it doensn't show up in the compiled CSS, so instead of .serif {...

Using HTML5 to Determine User Location

Geolocation is one of the most exciting features offered by HTML5.

Using some relatively simple JavaScript code, you can create Web applications that determine various aspects of the user location, including longitude, latitude and altitude plus more. Some Web applications can even provide navigation functionality by monitoring the user position over time, integrating with map systems such as Google Maps API.

As with all HTML5 functions, you cannot yet rely on browser support. Where browser support exists, it varies in depth and consistency. Essentially, you need to provide alternative functionality for users whose browsers do not fully support HTML5.

In this tutorial we’ll run through the basics of establishing user location. In practice, the browser may be getting its data from more than one possible source. For example it could be GPS data on a mobile device or simply IP address based data on any device connected to the Internet. However, your code does not need to concern itself with these details, you can simply retrieve and use the location data for the purposes of your own projects.

HTML5 Web Page

Use the following code to create an outline for your HTML5 page:

<!DOCTYPE html> <html> <head> <script> /*Location functions here*/ </script> </head> <body> </body> </html>

We will place the JavaScript Geolocation functions in the page head script section and some basic HTML elements for testing and demonstrating the functionality in the body section.

HTML Demonstration Elements

Add the following markup to your HTML body section:

<input type="button" value="get location" onclick="getUserLocation()"/> <div id="locationData"> Location data here </div>

You can call your Geolocation functions at any time, such as when the page loads, or in conjunction with jQuery document ready functions. To demonstrate, we’ll use the button to call the function and will write the location data into the div element, which has some simple placeholder text in it initially.

Get Position Function

The main method we will be using to determine user location is the getPosition method. Add the following function in the script section in your page head:

function getUserLocation() { //check if the geolocation object is supported, if so get position if (navigator.geolocation) navigator.geolocation.getCurrentPosition(displayLocation, displayError); else document.getElementById("locationData").innerHTML = "Sorry - your browser doesn't support geolocation!"; }

This function is called when the user clicks the button. The code first checks that the navigator Geolocation object is present, which means the browser supports it. If the Geolocation object is supported, the code uses it to call the getCurrentPosition method.

The getCurrentPosition method takes two parameters indicating callback functions. The first is a function to call when the Geolocation data is received, while the second is a function to call if an error is returned instead.

If the Geolocation object is not supported, the function simply writes an error message to the page div element.

When a site attempts to retrieve the user location data for the first time, the user’s browser will prompt them to determine whether or not they consent to share their data. The function will only proceed if they do consent.

Display Location Function

Next we need to implement the function we included as first parameter to the getCurrentPosition method call. This function will be passed the user location data when the browser receives it. Add the following after your getUserLocation function:

function displayLocation(position) { //build text string including co-ordinate data passed in parameter var displayText = "User latitude is " + position.coords.latitude...
more →
Oguzhan Cansever says: Thanks for your explanation how to get a user position. I think longitude and latitude are coordinates to find out a...

Common C# Build-Time Errors Part II: Inheritance and Interfaces

In our last lesson, we saw many of the most basic build-time errors in C#.

In this session, we will look at some of the errors related to:

classes subclasses inheritance

Once we address some of the more common errors we will take a look at how you can fix them.

#1 Hidden Method Name Creates Overload

This conflict arises when a base class and its subclass have a function of the same name

public class MyBaseClass { public void Function() { // function code goes here } { public class MySubClass : MyBaseClass { public void Function() { // function code goes here } } public class YourClass { public void YourFunction() { SubClass ysb = new MySubClass; ysb.Function(); } }

The function YourFunction() cannot access the MyBaseClass.Function() from MySubClass because MySubClass.Function() hides it.

If the MySubClass.Function() is supposed to be hidden, the line that creates MySubClass.Function() should contain the keyword “new” to differentiate it from the MyBaseClass.Function():

public class MySubClass : MyBaseClass { new public void Function() { // function code goes here } }

If the MySubClass.Function() is supposed to be inherited polymorphically from MyBaseClass, the line that creates MySubClass.Function() should contain the keyword “override” and the MyBaseClass.Function() line should contain the keyword “virtual” to allow for the override:

public class MyBaseClass { public virtual void Function() { // function code goes here } } public class MySubClass : MyBaseClass { public override void Function() { // function code goes here } }

#2 Cannot Inherit from Sealed Class, Method or Variable

Programmers typically seal classes to protect them from modification from inherited classes, so they do not define their classes that are expected to pass methods and variables through inheritance as sealed.

public class Xray { protected virtual void Function() { Console.WriteLine("Xray.Function"); } protected virtual void Function2() { Console.WriteLine("Xray.Function2"); } } // end of class Xray public class Yankee : Xray { sealed protected override void Function()...
more →

The XREF table for MySQL

The XREF, or cross reference table, is a database table that links records together. These tables are very good for normalization in your database. I almost always use an xref when I need an many to many relationship.

Usually XREF tables have only two columns with no Primary Key. That’s right, the two columns together make them unique. They are both Foreign Keys to other tables. A real life example of this would be in any standard CRM. Let’s go over this example right now.

Many CRM’s could have a table to store notes, and a table to store accounts. If you have one user managing many accounts, they may need to put the same note for all accounts they are managing. To connect these notes to the accounts we will use an xref table.

Create a schema called ‘test_db’. Now create our accounts and notes table:

CREATE TABLE `test_db`.`accounts` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(45) NOT NULL , `phone` VARCHAR(24) NULL , `fax` VARCHAR(24) NULL , PRIMARY KEY (`id`) , UNIQUE INDEX `id_UNIQUE` (`id` ASC) ) ENGINE = InnoDB; CREATE TABLE `test_db`.`notes` ( `id` INT NOT NULL AUTO_INCREMENT , `subject` VARCHAR(45) NOT NULL , `body` VARCHAR(256) NOT NULL , PRIMARY KEY (`id`) , UNIQUE INDEX `id_UNIQUE` (`id` ASC) ) ENGINE = InnoDB;

These tables should be created first, so that the ID’s in them actually exist when we create the foreign keys in our XREF table. We are going to name the XREF table account_notes_xref. This is preference, but really good practice, as it is a single account’s note’s. The notes will be displayed on the account so the account owns the notes.

You could also get away with account_notes, but for sake of the title, we will add xref to it. This also makes things easier to spot when looking through the database. So let’s make the table:

CREATE TABLE `test_db`.`account_notes_xref` ( `account_id` INT NOT NULL , `note_id` INT NOT NULL , PRIMARY KEY (`account_id`, `note_id`) , INDEX `acx_account_id` (`account_id` ASC) , INDEX `acx_note_id` (`note_id` ASC) , CONSTRAINT `acx_account_id` FOREIGN KEY (`account_id` ) REFERENCES `test_db`.`accounts` (`id` ) ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT `acx_note_id`...
more →
Disqus_eric says: "I almost always use an xref when I need an many to many relationship" This implies you can do a many-to-many w/out an xref. ...