Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Monday, October 27, 2014

25 Laravel Tips and Tricks

25 Laravel Tips and Tricks

by 1 Comment
Gift
Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.
There was a period of time, not too long ago, when PHP and its community were, for lack of better words, hated. Seemingly, the headline joke of every day was one that related to how terrible PHP was. Let's see, what new PHP-slamming blog article will be posted today?
Yes, sadly enough, the community and ecosystem simply weren't on the same level as other modern languages.
Yes, sadly enough, the community and ecosystem simply weren't on the same level as other modern languages. It seemed that PHP was destined to live out its dominating lifespan in the form of messy WordPress themes.
But, then, quite amazingly, things began to change - and quickly, too. Like a witch stirring the pot, innovative new projects began popping out of nowhere. Perhaps most notable of these projects was Composer: PHP's definitive dependency manager (not unlike Ruby's Bundler or Node's NPM). While, in the past, PHP developers were forced to wrangle PEAR into shape (a nightmare, indeed), now, thanks to Composer, they can simply update a JSON file, and immediately pull in their desired dependency. A profiler here, a testing framework there... all in seconds!
In the crowded PHP framework world, just as CodeIgniter began to fizzle out, Taylor Otwell's Laravel framework arose out of the ashes to become the darling of the community. With such a simple and elegant syntax, building applications with Laravel and PHP was - gasp - downright fun! Further, with version 4 of the framework leveraging Composer heavily, things finally seemed to be falling into place for the community.

Want migrations (version control for your database)? Done. How about a powerful Active-Record implementation? Sure, Eloquent will do the trick quite nicely. What about testing facilities? Of course. And routing? Most certainly. What about a highly tested HTTP layer? Thanks to Composer, Laravel can leverage many of the excellent Symfony components. When it comes right down to it, chances are, if you need it, Laravel offers it.

While PHP used to be not dissimilar from a game of Jenga - just one block and away from falling to pieces - suddenly, thanks to Laravel and Composer, the future couldn't look any brighter. So pull out some shades, and dig into all that the framework has to offer.
Laravel offers one of the most powerful Active-Record implementations in the PHP world. Let's say that you have an orders table, along with an Order Eloquent model:
1
class Order extends Eloquent {}
We can easily perform any number of database queries, using simple, elegant PHP. No need to throw messy SQL around the room. Let's grab all orders.
1
$orders = Order::all();
Done. Or maybe, those orders should be returned in order, according to the release date. That's easy:
1
$orders = Order::orderBy('release_date', 'desc')->get();
What if, rather than fetching a record, we instead need to save a new order to the database. Sure, we can do that.
1
2
3
$order = new Order;
$order->title = 'Xbox One';
$order->save();
Finished! With Laravel, tasks that used to be cumbersome to perform are laughably simple.
Laravel is unique in that it can be used in a number of ways. Prefer a simpler, more Sinatra-like routing system? Sure, Laravel can offer that quite easily, using closures.
1
2
3
4
5
Route::get('orders', function()
{
    return View::make('orders.index')
        ->with('orders', Order::all());
});
This can prove helpful for small projects and APIs, but, chances are high that you'll require controllers for most of your projects. That's okay; Laravel can do that, too!
1
Route::get('orders', 'OrdersController@index');
Done. Notice how Laravel grows with your needs? This level of accomodation is what makes the framework as popular as it is today.
What do we do in the instances when we must define relationships? For example, a task will surely belong to a user. How might we represent that in Laravel? Well, assuming that the necessary database tables are setup, we only need to tweak the related Eloquent models.
01
02
03
04
05
06
07
08
09
10
11
12
13
class Task extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}
 
class User extends Eloquent {
    public function tasks()
    {
        return $this->hasMany('Task');
    }
}
And, with that, we're done! Let's grab all tasks for the user with an id of 1. We can do that in two lines of code.
1
2
$user = User::find(1);
$tasks = $user->tasks;
However, because we've defined the relationship from both ends, if we instead want to fetch the user associated with a task, we can do that, too.
1
2
$task = Task::find(1);
$user = $task->user;
Often, it can be helpful to link a form to a model. The obvious example of this is when you wish to edit some record in your database. With form model binding, we can instantly populate the form fields with the values from the associated table row.
01
02
03
04
05
06
07
08
09
10
11
{{ Form::model($order) }}
    <div>
        {{ Form::label('title', 'Title:') }}
        {{ Form::text('title') }}
    </div>
 
    <div>
        {{ Form::label('description', 'Description:') }}
        {{ Form::textarea('description') }}
    </div>
{{ Form::close() }}
Because the form is now linked to a specific Order instance, the inputs will display the correct values from the table. Simple!
Too many database queries, and, very quickly, your application can become like molasses. Luckily, Laravel offers a simple mechanism for caching these queries, using nothing more than a single method call.
Let's grab all questions from the database, but cache the query, since it's not likely that this table will be updated frequently.
1
$questions = Question::remember(60)->get();
That's it! Now, for the next hour of pages requests, that query will remain cached, and the database will not be touched.
You'll encounter situations when multiple views require a certain variable or piece of data. A good example of this is a navigation bar that displays a list of tags.
Too keep controllers as minimal as possible, Laravel offers view composers to manage things like this.
1
2
3
4
View::composer('layouts.nav', function($view)
{
    $view->with('tags', ['tag1', 'tag2']);
});
With this piece of code, any time that the layouts/nav.blade.php view is loaded, it will have access to a variable, $tags, equal to the provided array.
Laravel takes a dead-simple approach to authentication. Simply pass an array of credentials, likely fetched from a login form, to Auth::attempt(). If the provided values match what is stored in the users table, the user will instantly be logged in.
01
02
03
04
05
06
07
08
09
10
$user = [
    'email' => 'email',
    'password' => 'password'
];
 
if (Auth::attempt($user))
{
    // user is now logged in!
    // Access user object with Auth::user()
}
What if we need to log the user out - perhaps, when a /logout URI is hit? That's easy, too.
1
2
3
4
5
6
Route::get('logout', function()
{
    Auth::logout();
     
    return Redirect::home();
});
Working RESTfully in Laravel has never been easier. To register a resourceful controller, simple call Route::resource(), like so:
1
Route::resource('orders', 'OrdersController');
With this code, Laravel will register eight routes.
  • GET /orders
  • GET /orders/:order
  • GET /orders/create
  • GET /orders/:order/edit
  • POST /orders
  • PUT /orders/:order
  • PATCH /orders/:order
  • DELETE /orders/:order
Further, the companion controller may be generated from the command line:
1
php artisan controller:make OrdersController
Within this generated controller, each method will correspond to one of the routes above. For examples, /orders will map to the index method, /orders/create will map to create, etc.
We now have the necessary power to build RESTful applications and APIs with ease.
While, yes, PHP is by nature a templating language, it hasn't evolved to become an overly good one. That's okay, though; Laravel offers its Blade engine to fill the gap. Simply name your views with a .blade.php extension, and they will automatically be parsed, accordingly. Now, we can do such things as:
1
2
3
4
5
6
7
@if ($orders->count())
    <ul>
        @foreach($orders as $order)
            <li>{{ $order->title }}</li>
        @endforeach
    </ul>
@endif
Because Laravel makes use of Composer, we instantly have PHPUnit support in the framework out of the box. Install the framework and run phpunit from the command line to test it out.
Even better, though, Laravel offers a number of test helpers for the most common types of functional tests.
Let's verify that the home page returns a status code of 200.
1
2
3
4
5
public function test_home_page()
{
    $this->call('GET', '/');
    $this->assertResponseOk();
}
Or maybe we want to confirm that, when a contact form is posted, the user is redirected back to the home page with a flash message.
01
02
03
04
05
06
07
08
09
10
11
12
public function test_contact_page_redirects_user_to_home_page()
{
    $postData = [
        'name' => 'Joe Example',
        'email' => 'email-address',
        'message' => 'I love your website'
    ];
 
    $this->call('POST', '/contact', $postData);
 
    $this->assertRedirectedToRoute('home', null, ['flash_message']);
}
As part of Laravel 4.1 - scheduled to be released in November, 2013 - you can easily write an Artisan command to SSH into your server, and perform any number of actions. It's as simple as using the SSH facade:
1
2
3
4
SSH::into('production')->run([
    'cd /var/www',
    'git pull origin master'
]);
Pass an array of commands to the run() method, and Laravel will handle the rest! Now, because it makes sense to execute code like this as an Artisan command, you only need to run php artisan command:make DeployCommand, and insert the applicable code into the command's fire method to rapidly create a dedicated deployment command!
Laravel offers an elegant implementation of the observer pattern that you may use throughout your applications. Listen to native events, like illuminate.query, or even fire and catch your own.
A mature use of events in an application can have an incredible effect on its maintainability and structure.
1
2
3
4
5
Event::listen('user.signUp', function()
{
    // do whatever needs to happen
    // when a new user signs up
});
Like most things in Laravel, if you'd instead prefer to reference a class name, rather than a closure, you can freely do so. Laravel will then resolve it out of the IoC container.
1
Event::listen('user.signUp', 'UserEventHandler');

As an application grows, it can be difficult to view which routes have been registered. This is especially true if proper care has not been given to your routes.php file (i.e. abusive implicit routing).
Laravel offers a helpful routes command, which will display all registered routes, as well as the controller methods that they trigger.
1
php artisan routes
Think about when a user signs up for your application. Likely, a number of events must take place. A database table should be updated, a newsletter list should be appended to, an invoice must be raised, a welcome email might be sent, etc. Unfortunately, these sorts of actions have a tendency to take a long time.
Why force the user to wait for these actions, when we can instead throw them into the background?
1
Queue::push('SignUpService', compact('user'));
Perhaps the most exciting part, though, is that Laravel brilliantly offers support for Iron.io push queues. This means that, even without an ounce of "worker" or "daemon" experience, we can still leverage the power of queues. Simply register a URL end-point using Laravel's helpful php artisan queue:subscribe command, and Iron.io will ping your chosen URL each time a job is added to the queue.

Simple steps to faster performance!
When validation is required (and when isn't it), Laravel again comes to the rescue! Using the Validator class is as intuitive as can be. Simply pass the object under validation, as well as a list of rules to the make method, and Laravel will take care of the rest.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
$order = [
    'title' => 'Wii U',
    'description' => 'Game console from Nintendo'
];
 
$rules = [
    'title' => 'required',
    'description' => 'required'
];
 
$validator = Validator::make($order, $rules);
 
if ($validator->fails())
{
    var_dump($validator->messages()); // validation errors array
}
Typically, this type of code will be stored within your model, meaning that validation of, say, an order could be reduced to a single method call:
1
$order->isValid();

Especially when first learning Laravel, it an be helpful to tinker around with the core. Laravel's tinker Artisan command can help with this.
As part of version 4.1, the tinker command is even more powerful, now that it leverages the popular Boris component.
1
2
3
4
5
$ php artisan tinker
 
> $order = Order::find(1);
> var_dump($order->toArray());
> array(...)
Think of migrations as version control for your database. At any given point, you may "rollback" all migrations, rerun them, and much more. Perhaps the true power rests in the power to push an app to production, and run a single php artisan migrate command to instantly construct your database.
To prepare the schema for a new users table, we may run:
1
php artisan migrate:make create_users_table
This will generate a migration file, which you may then populate according to your needs. Once complete, php artisan migrate will create the table. That's it! Need to roll back that creation? Easy! php artisan migrate:rollback.
Here's an example of the schema for a frequently asked questions table.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
public function up()
{
    Schema::create('faqs', function(Blueprint $table) {
        $table->integer('id', true);
        $table->text('question');
        $table->text('answer');
        $table->timestamps();
    });
}
 
public function down()
{
    Schema::drop('faqs');
}
Notice how the drop() method performs the inverse of up(). This is what allows us to rollback the migration. Isn't that a lot easier that wrangling a bunch of SQL into place?
While Laravel offers a number of helpful generators, an incredibly helpful third-party package, called "Laravel 4 Generators," takes this even further. Generate resources, seed files, pivot tables, and migrations with schema!
In this previous tip, we were forced to manually write the schema. However, with the generators package enabled, we can instead do:
1
php artisan generate:migration create_users_table --fields="username:string, password:string"
The generator will take care of the rest. This means that, with two commands, you can prepare and build a new database table.
Laravel 4 Generators may be installed through Composer.
As noted earlier, there are number of instances when it can be helpful to write custom commands. They can be used to scaffold applications, generate files, deploy applications, and everything in between.
Because this is such a common task, Laravel makes the process of creating a command as easy as it can be.
1
php artisan command:make MyCustomCommand
This command will generate the necessary boilerplate for your new custom command. Next, from the newly created, app/commands/MyCustomCommand.php, fill the appropriate name and description:
1
2
protected $name = 'command:name';
protected $description = 'Command description.';
And, finally, within the command class' fire() method, perform any action that you need to. Once finished, the only remaining step is to register the command with Artisan, from app/start/Artisan.php.
1
Artisan::add(new MyCustomCommand);
Believe it or not; that's it! You may now call your custom command from the terminal.
Laravel leverages the facade pattern heavily. This allows for the clean static-like syntax that you'll undoubtedly come to love (Route::get(), Config::get(), etc.), while still allowing for complete testability behind the scenes.
Because these "underlying classes" are resolved out of the IoC container, we can easily swap those underlying instances out with mocks, for the purposes of testing. This allows for such control as:
1
Validator::shouldReceive('make')->once();
Yep, we're calling shouldReceive directly off of the facade. Behind the scenes, Laravel makes use of the excellent Mockery framework to allow for this. This means that you may freely use these facades in your code, while still allowing for 100% testability.
Because building forms can frequently be a cumbersome task, Laravel's form builder steps in to ease the process, as well as leverage many of the idiosyncrasies related to form construction. Here are a few examples:
1
2
3
4
5
{{ Form::open() }}
    {{ Form::text('name') }}
    {{ Form::textarea('bio') }}
    {{ Form::selectYear('dob', date('Y') - 80, date('Y')) }}
{{ Form::close() }}
What about tasks, such as remembering input from the previous form submission? Laravel can do all of that automatically!
At the core of Laravel is its powerful IoC container, which is a tool that assists in managing class dependencies. Notably, the container has the power to automatically resolve classes without configuration!
Simply typehint your dependencies within the constructor, and, upon instantiation, Laravel will use PHP's Reflection API to intelligently read the typehints, and attempt to inject them for you.
1
2
3
4
public function __construct(MyDependency $thing)
{
    $this->thing = $thing;
}
As long as you request the class out of the IoC container, this resolution will take place automatically.
1
$myClass = App::make('MyClass');
An important note is that controllers are always resolved out of the IoC container. As such, you may free typhint your controller's dependencies, and Laravel will subsequently do its best to inject them for you.
While a single environment might work for small projects, for any applications of size, multiple environments will prove essentials. Development, testing, production...all of these are essential and require their own configuration.
Maybe your test environment uses a database in memory for testing. Maybe your development environment uses different API keys. Likely, your production environment will use a custom database connection string.
Luckily, Laravel makes our job simple once again. Have a look at bootstrap/start.php in your app.
Here's a basic demonstration of setting both a local and production environment, based upon the browser's address bar.
1
2
3
4
$env = $app->detectEnvironment(array(
    'local' => array('localhost'),
    'production' => array('*.com')
));
While this will work, generally speaking, it's preferred to use environment variables for this sort of thing. No worries; this is still doable in Laravel! Instead, simply return a function from the detectEnvironment method on the container object.
1
2
3
4
$env = $app->detectEnvironment(function()
{
    return getenv('ENV_NAME') ?: 'local';
});
Now, unless an environment variable has been set (which you will do for production), the environment will default to local.
Advertisement
Laravel, yet again, takes a dead-simple approach to configuration. Create a folder within app/config that matches your desired environment, and any configuration files within it will take precedence, if the environment name matches. As such, to, say, set a different billing API key for development, you could do:
1
2
3
4
5
<?php app/config/development/billing.php
 
return [
    'api_key' => 'your-development-mode-api-key'
];
The configuration switcharoo is automatic. Simply type Config::get('billing.api_key'), and Laravel will correctly determine which file to read from.
When it comes to education, the Laravel community, despite its relatively young age, is a never-ending well. In little over a year, a half-dozen different books - related to all matters of Laravel development - have been released.

Monday, May 6, 2013

php - display image & security

Hi

I think you want to :
  1. deny access to the image/ directory
  2. put this script outside the image/ directory

    CODE --> show.php

    <?php
    header("Content-type: image/jpeg");
    readfile("image/$_GET[image].jpg");
    ?>
  3. access "/image/baby.jpg" with http://example/show.php?image=baby
Of course the simple solution would be to just set up your web server and do no programming. But probably I do not fully understand your idea.

Tuesday, August 21, 2012

Teach Yourself How to Code - From life hacker

Programmer 101: Teach Yourself How to Code

You've always wanted to learn how to build software yourself—or just whip up an occasional script—but never knew where to start. Luckily, the web is full of free resources that can turn you into a programmer in no time.
Since the invention of the internet, programmers have been using it to discuss software development techniques, publish tutorials, and share code samples for others to learn from and use online. If you're curious about how to become a programmer, you can get off to a running start using tons of great free web-based tutorials and resources.

First Things First: Don't Get Hung Up on Choosing a Language

Programmer 101: Teach Yourself How to CodeA common pitfall for beginners is getting stuck figuring out which programming language is best to learn first. There are a lot of opinions out there, but there's no one "best" language. Here's the thing: In the end, language doesn't matter THAT much. Understanding data and control structures and design patterns does matter very much. Every language—even a simple scripting language—will have elements that you'll use in other languages as well and will help you learn. In classes I took to get my degree in Computer Science, I programmed in Pascal, Assembly, and C—languages I never actually got paid to program in professionally. I taught myself every language I've used in my career, reusing concepts I already knew, and referring to documentation and books to learn its syntax. So, don't get hung up on what language to learn first. Pick the kind of development you want to do, and just get started using one that works.
There are several different kinds of software development you can do for various platforms, from the web to your desktop to your smartphone to a command line. In this article, we'll outline some of our favorite starter tutorials and resources for teaching yourself how to program for each major platform. We're going to assume you're a savvy user, but a newb when it comes to wrangling code snippets, so we'll keep things at the beginner level. Even just following through a beginner programming tutorial, you'll be happy to see how far you can get.

Desktop Scripting

The easiest way to try your hand at programming for your Windows or Mac desktop is to start with a scripting or macro program like AutoHotkey (for Windows) or Automator (for Mac). Right now hardcore coders throughout the Lifehacker readership are yelling at their monitors, saying that AHK or AppleScript are not "real" programming. That may be true—technically these types of tools just do high-level scripting. But for those new to programming who just want to get their feet wet, automating actions on their desktop, these free tools are a fantastic way to start—and you'd be surprised at how much you can do with them.
Programmer 101: Teach Yourself How to CodeFor example, Adam developed the standalone Windows application we all know and love, Texter, using AutoHotkey, so this scripting language is capable of far more than just small-scale automation projects. To get started with AutoHotkey, check out Adam's tutorial on how to turn any action into a keyboard shortcut using AutoHotkey. (Then, check out the source code for Texter to see the innards of a full-fledged AHK-based Windows application.)

Web Development

Instead of being bound to specific programming languages and the look and feel of a particular operating system, you can put your killer application in the browser and run it in the cloud, as a webapp. Welcome to the wonderful world of web development.
HTML and CSS: The first thing you need to know to build any web site is HTML (the page markup that makes up web pages) and CSS (the style information that makes that markup look pretty). HTML and CSS are not true programming languages—they're just page structure and style information. However, you should be able to author simple HTML and CSS by hand before you begin building web applications, because a web page is the frontend to every webapp. This HTML tutorial is a good place to start.
JavaScript: Now that you can lay out a static web page with HTML and CSS, things get fun—because it's time to learn JavaScript. JavaScript is the programming language of the web browser, the magic that makes dynamic in-page effects go. JavaScript is also the stuff of bookmarklets, Greasemonkey user scripts, and Ajax, so it's the key to making all sorts of web goodies. Start learning JavaScript here.
Programmer 101: Teach Yourself How to CodeServer-side scripting: Once you're good at making things happen inside a web page, you're going to need to put some dynamic server action behind it—and for that, you'll need to move into a server-side scripting language, like PHP, Python, Perl, or Ruby. For example, to make a web-based contact form that sends an email somewhere based on what a user entered, a server-side script is required. Scripting languages like PHP can talk to a database on your web server as well, so if you want to make a site where users can log in and store information, that's the way to go. Excellent web development site Webmonkey is full of tutorials for various web programming languages. See their PHP Tutorial for Beginners. When you're ready, check out how to use PHP to talk to a database in WebMonkey's PHP and MySQL tutorial. PHP's online documentation and function reference is the best on the web. Each entry (like this one on the strlen function) includes user comments at the bottom which are often as helpful as the documentation itself. (I happen to be partial to PHP, but there are plenty of other server-side scripting languages you might decide to go with instead.)
Programmer 101: Teach Yourself How to CodeWeb frameworks: Over the years, web developers have had to solve and resolve the same problems and rewrite similar code to build dynamic web sites. To avoid making everyone reinvent the wheel for every new web development project, some programmers have come up with development frameworks that do some repetitive work for you. The popular Ruby on Rails framework, for example, takes the Ruby programming language and offers a web-specific structure for getting common web application tasks done. In fact, Adam used Rails to build his first serious (and impressive!) web application, MixTape.me. Here's his take on how to build a web site from scratch with no experience. Other popular web development frameworks include CakePHP (for PHP programmers), Django (for Python programmers), and jQuery (for JavaScript).
Web APIs: An API (Application programming interface) is a programmatic way for different pieces of software to talk to one another. For example, if you want to put a dynamic map on your web site, you want to use a Google Map instead of building your own custom map. The Google Maps API makes it easy to programmatically include a map in a page with JavaScript. Almost every modern web service you know and love has an API that lets you include data and widgets from it in your application, like Twitter, Facebook, Google Docs, Google Maps, and the list goes on. Integrating other webapps into your web application via API's is the final frontier of rich web development. Every good, major web service API offers thorough documentation and some sort of quick start guide to try it out (here's Twitter's, for example). Go crazy.

Command Line Scripting

If you want to write a program that takes textual or file input and outputs something useful, the command line is the right place to do it. While the command line isn't as sexy or good-looking as a webapp or desktop app, for rapid development of quick scripts that automate processes, you can't beat it.
Several scripting languages that work on a Linux-based web server also work at the command line, like Perl, Python, and PHP—so learning one of those baddies makes you conversant in two contexts. My path never took me too far down the Perl road, but I taught myself Python using the excellent and free online book, Dive into Python.
Programmer 101: Teach Yourself How to Code
If becoming a Unix ninja is one of your programmer goals, you absolutely must get good at shell scripting with bash. Bash is the command line scripting language of a *nix environment, and it can do everything from help you set up automated backups of your database and files to building out a full-fledged application with user interaction. Without any experience writing bash scripts beyond a dozen lines, I wound up developing a full-on personal to-do list manager in bash, Todo.txt CLI.

Add-ons

Nowadays, modern webapps and browsers are extensible with with bits of software that bolt onto them and add features. Add-on development is gaining in popularity as more developers look at existing software, like Firefox or WordPress, and think "But if only it could do THIS..."
You can do a whole lot in any web browser with just a mastery of HTML, JavaScript, and CSS. Bookmarklets, Greasemonkey user scripts, and Stylish user styles are created with the same bits of code that make regular web pages, so they're worth learning even if you just want to tweak an existing site with a small snippet of code.
More advanced browser add-ons, like Firefox extensions, let you do more. Developing Firefox extensions, for example, requires that you're conversant in JavaScript and XML (markup that's similar to HTML, but way more strict in format). Back in 2007 I ran down how to build a Firefox extension, a skill I picked up after I stumbled upon a free tutorial.
Many free and well-loved web applications offer an extension framework as well, like WordPress and MediaWiki. Both of those apps are written in PHP, so comfort with PHP is a prerequisite for getting started. Here's how to write a plug-in for WordPress. Developers who want to ride the cutting edge of Google Wave can get started writing gadgets and bots in HTML, JavaScript, Java, and Python. I wrote my first Wave bot following this quick start tutorial in one afternoon.

Web Development for the Desktop

The best part about getting started programming in one context is when you can take those skills and apply them elsewhere. Learning web development first is a great way to start because now there are ways to put those skills to work on desktop applications, too. For example, Adobe AIR is a cross-platform run-time environment that lets you build your app once and release it to run on the desktop for every operating system AIR runs on. AIR apps are written in HTML, Flash, or Flex, so it lets you apply your web development skills in a desktop context. AIR is a great option for deploying desktop apps like one of our top 10 apps worth installing Adobe AIR for.

Mobile App Development

Mobile applications like the ones you run on your iPhone or Android smartphone are all the rage right now, so you may have dreams of striking it rich in the iTunes App Store with the next killer app. However, for the new coder, diving headfirst into mobile development can be a rough learning curve, since it requires comfort with advanced programming languages like Java and Objective C. However, it's worth checking out what iPhone and Android development looks like. Check out this simple iPhone application development example to get a taste of what iPhone developers do. Android apps are written in Java, and here's a friendly video tutorial of what building a "Hello Android" application workflow looks like.

Patience, Elbow Grease, Trial and Error

Good coders are a special breed of persistent problem-solvers who are addicted to the small victories that come along a long path of trial and error. Learning how to program is very rewarding, but it can also be a frustrating and solitary experience. If you can, get a buddy to work with you along the way. Getting really good at programming, like anything else, is a matter of sticking with it, trying things out, and getting experience as you go.
This article is just one self-taught programmer's top-of-mind recommendations for beginners. Experienced programmers: What did I miss? No matter your skill level, add your thoughts and recommendations for beginners to the comments.
Gina Trapani, Lifehacker's founding editor, thinks the best programmers are self-taught. Her weekly feature, Smarterware, appears every Wednesday on Lifehacker. Subscribe to the Smarterware tag feed to get new installments in your newsreader.

Thursday, July 5, 2012

Uploding big file in php

Uploading larger/bigger files is difficult using http because it uses UDP protocol. However in shared hosting environment it is difficult to upload just 3-4 MB files. In order to uplaod larger document you can set upload_max_filesize and post_max_size in your htaccess file. But in order to update seamlessly you need to increase the execution time as well.

Set the following values according to your choice.

php_value upload_max_filesize 10M
php_value post_max_size 11M
php_value max_execution_time 600
php_value max_input_time 200

Note: Please make sure to use this .htaccess file in the same directory.
Note: Always mention greater upload_max_size than post_max_size because a post contain additional data also. However it is totally based on your wish to use.
Upload files using HTTP:

Here goes the script

move_uploaded_file($_FILES['userfile']['tmp_name'], 'path_to_directory/'.$_FILES['userfile']['name']);

If this does not solve your problem then probably you need to “upload your file using ftp”. Here I am providing a simple code to upload your file using ftp.
Upload files using FTP:

Here goes the script

$path = "path_to_directory/";
$ftp_server = "ftp.example.com";
$ftp_user   = "USER";
$ftp_pass   = "PASSWORD";
$file=$_FILES['userfile']['tmp_name'];
$name=$_FILES['userfile']['name'];

// set up a connection to ftp server
$conn_id = ftp_connect($ftp_server);

//check for connection error
if(!$conn_id){
 echo “connection failed”;
}

// ftp login with username and password
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);

// check for login
if (!$login_result) {
       echo "Attempted to connect to $ftp_server for user $ftp_user.... failed";
} 

// upload the file to the path specified
$upload = ftp_put($conn_id, $paths.'/'.$name, $file, FTP_BINARY);

ftp_close($conn_id);

If you are having a shared hosting environment than probably your outbound ftp is disabled. In that case you need to upload using cURL. Yes cURL is a great library with great power. Almost all big site using cURL in some way. Check the following script.
Upload files using cURL:

Here is the simplest script

$ch = curl_init();
$file = $_FILES['userfile']['tmp_name'];
$fp = fopen($file, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://USER:PASSWORD@ftp.example.com/'.$_FILES['userfile']['name']);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file));
curl_exec ($ch);

if you need to change the file permission after upload use chmod. As,

chmod("path_to_file" ,0755);

Upload checking could be done using php inbuilt funtion file_exists. As,

file_exist($_SERVER[DOCUMENT_ROOT].'/path_to_file')

Wednesday, July 4, 2012

php code sniplet

Button with java script - msgbox
FUNCTION transfer_btn() {
   $fm="";
     $fm ="".
          "".
          "".
          "".
          "".
          ''.
          "".
          " ".
          "
&nbsp
"; return $fm; } Button with java script - carriage return clik
FUNCTION add_btn($i,$table_name,$scan_ftycode,$scrno,$productcode,$org_productcode,$lot) {

       if (strlen($this->stuffing_rowid)==0 || $this->stuffing_rowid==0 || $this->rec_lock=='Y') {
            return "";
       }
       $formname = "formE".$i;
       $ret="
"; $ret.= ""; $ret.= ''; $ret.= ""; $ret.= ""; $ret.= " "; $ret.="
"; return $ret; }

Monday, May 14, 2012

PHP

Display file size (Byte, MB,...)
 0.9){
        $filesize = $filesize / $decr;
        $step++;
    }
    return round($filesize,2).' '.$prefix[$step];
    } else {

    return 'NaN';
    }
  
}
?>
ftp

Upload image to database
////
/*

$result[name]
"; } ?> //// //// "; ?> */
Download image
            $filename = 'dummy.zip';
            $filename = realpath($filename);

            $file_extension = strtolower(substr(strrchr($filename,"."),1));

            switch ($file_extension) {
                case "pdf": $ctype="application/pdf"; break;
                case "exe": $ctype="application/octet-stream"; break;
                case "zip": $ctype="application/zip"; break;
                case "doc": $ctype="application/msword"; break;
                case "xls": $ctype="application/vnd.ms-excel"; break;
                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                case "gif": $ctype="image/gif"; break;
                case "png": $ctype="image/png"; break;
                case "jpe": case "jpeg":
                case "jpg": $ctype="image/jpg"; break;
                default: $ctype="application/force-download";
            }

            if (!file_exists($filename)) {
                die("NO FILE HERE");
            }

            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);
            header("Content-Type: $ctype");
            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".@filesize($filename));
            set_time_limit(0);
            @readfile("$filename") or die("File not found.");
Upload image w/ YUI pgrogress bar