Export and import MySQL databases through command line

command line

This method works for all database sizes, including very large ones.

You must be able to log into your server with SSH.

Export

1. Log into your server via SSH.
2. Use the command cd to navigate to a directory where your user has write access. Example:
cd /var/www/vhosts/example.com/httpdocs
3. Export the database by executing the following command:

mysqldump –add-drop-table -u admin -p`cat /etc/psa/.psa.shadow` dbname > dbname.sql

Once you execute this command, you will be prompted for your database password. Type in the password and hit enter. Your database will now start exporting. When it is done, you will see the command prompt again. If it is a large database, this may take a few minutes.
NOTE:
The following variables need to be replaced with your own information:

  • -u admin specifies the database username.
  • Username is “admin” and the password is a hashed version of your Plesk admin password.
  • dbname is the name of the database you are trying to export.
  • dbname.sql is the name you want to give your backup file, and can be whatever you want.
  • Omit the –add-drop-table argument if you plan to merge this backup with an existing database when you import it. This option means the backup will totally replace the old database when it is imported.

4. You can now download the resulting SQL file. Connect to your server with FTP, navigate to the directory where you created the dump file, and download it.
5. Remove the SQL file from your web-accessible directory, if you created it in a public folder. Otherwise, anyone can download it from the web.

Import

1. Use FTP to upload your SQL file to your server. You can upload it to your default FTP directory. See Step 1 in the “Export” instructions above for another suggestion. Alternately, you can use scp to upload your file via SSH.
2. Log into your server via SSH.
3. Use the command cd to navigate into the directory where you uploaded your backup file in Step 1. If you uploaded the backup into your public htttpdocs directory, go here:

1
cd /var/www/vhosts/example.com/httpdocs/

4. Import the database by executing the following command:

1
mysql -u admin -p`cat /etc/psa/.psa.shadow` dbname < dbname.sql

OR:

1
mysql -u admin -p`cat /etc/psa/.psa.shadow` dbname -e 'source dbname.sql'

Once you execute this command, you will be prompted for your database password. Type it in and hit enter. Your database will now import. It may take a few minutes if you have a large database. When the import is done, you will be returned to the command prompt.

NOTE:

  • Variables are the same as in Step 3 from the Export section above. Please check Step 3 in the “Export” section to make sure you are correctly replacing the example code with your own information.
  • dbname.sql is the actual name of your SQL file.
  • If you have a gzipped backup of your database, you can use this line instead:gunzip < dbname.gz | mysql -u admin -p`cat /etc/psa/.psa.shadow` dbname

    You can enter in your own username, database name, and backup file name, as before. dbname.gz is the name of your gzipped backup file. Use “unzip” instead of “gunzip” for zipped files.

5. Remove the SQL file from your web-accessible directory, if you uploaded it to a public folder. Otherwise, anyone can download it from the web.

If you get an error that looks like this:

Got Error: 1045: Access denied for user ‘admin@example.com’ (using password: YES) when trying to connect

You have entered an incorrect password. Please retype it carefully, or reset your password in the AccountCenter. See How can I change my Plesk admin password? for instructions.
If you get an SQL error during the import, you can force it to finish by adding “-f” to the command, which stands for “force.” For example:

1
mysql -f -u admin -p`cat /etc/psa/.psa.shadow` dbname &lt; dbname.sql

This can help you finish an import if you have a few corrupt tables, but need to get the database as a whole imported before you do anything else.

Embed Images from Google Maps In Emails & Blogs Without Using Screen Capture Software


It is now possible to embed live images of Google Maps in emails and other websites (like MySpace, Facebook or WordPress.com) that do not allow JavaScript.

Earlier you had to take a screenshot of the Google Maps and save that as an image file but that’s no longer necessary as this Static Maps Wizard will let you create a still but dynamic image of any location on Google Maps.
For instance, the map of Hyderabad above is not a screenshot but a live image served from Google Maps using this URL.

You can place the Google Maps image in any web page using the standard tag. For embedding maps in web emails (like Gmail), simply compose a new message and drag the Google Map on to the email body. Thanks Tom Manshreck.

Host your Podcasts on Google Drive for Free

If you are looking to publish your own audio or video podcasts, you’ll need space on a public web server to host the MP3 or MP4 files of your podcast. When a user subscribes to your podcast feed in iTunes, or another podcatcher app, the podcast files will be downloaded from this server to the user’s computer (or mobile phone).

Where do you host the podcast files? If you have signed up for a web hosting account, you can use the rented space to host the podcast files else you may consider using Google Drive – it is free, you can host both audio and video podcast files and there are no known bandwidth restrictions.

Free Podcast Hosting on Google Drive

Here’s how you can use your Google Drive to host your podcast in two minutes.
We will first create a Podcast folder in Google Drive to store the podcast files and then make this folder public so anyone can download the episodes stored in this Google Drive folder. Any video file that you upload to this folder in Drive will have a public URL that you can use in your Podcast XML feed.

Click here and authorize the script to access to your Google Drive. The script will create a new public folder in your Google Drive for hosting the files.
Go to
drive.google.com in your desktop browser and upload one or more podcast files in the new Podcasts folder that you created in Step #1.
Once the files have been uploaded, open that folder link in your browser (
see example) and you should see a list of all the uploaded podcast files.
Right-click any podcast file (see the above screenshot) to copy the file’s URL which you can then paste in your podcast RSS feed –
see example).

The podcasts will be served from googledrive.com.

Other than the actual podcast episodes, you may also upload art work, logos and other image files that may be required for submitting your Podcast into the iTunes store.

A Simple Way to Protect Images from ‘Casual Copying’

If you don’t want other people to download images from your website, don’t put them online because – the way the web works – it is almost impossible to prevent someone from copying or saving your images.

However there’s one little trick that may discourage the less-technical people from casually copying, or even hot-linking, to your web images. To give you an example, try saving the following image to your computer using the standard “save as” option.

The “save picture” option under right-click is still available for the above image but instead of downloading the actual photograph, all it would save is a blank image. Also, the URL for the image (under Properties) would appear as some junk characters (it’s called a data URI) and thus would deter the non-techies from hotlinking to that image.
Here’s how you may implement something similar for your own images:
The standard embed code for an image looks something like this:

1
<img src="photograph.jpg" alt="" width="500" height="250" />

What you need to do is change the value of the src attribute to point to a blank image and then add a new style attribute to render the actual image. Also make sure that the value of the height and the width parameters are exactly the same as the actual image.

1
<img style="background-image: url('photograph.jpg');" src="data:image/gif;base64, R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt="" width="500" height="250" />

This is like overlaying a completely transparent screen over your photograph and anyone trying to save the image will end up downloading that screen instead of the image.

Obviously, there are simple workarounds to get around the above method. For instance, a copy of the full image will still be available in your browser’s cache. You may look at the HTML source or may even save the image using screen capture but again, these techniques may not always be known to the non-technical users of your website.

How to change magento admin password through phpmyadmin ?

It seems like the password must be typed and not copy/paste at least on the install part. good to know ;o)

The default login is : admin The default password is : 123123
If you are having troubles and want to reset it to a different password, just run at your sql database:

1
SELECT * FROM admin_user;

Then, find the username you want to modify in the listing provided – ‘admin’ in this example. Then, to update the password, type:

1
 UPDATE admin_user SET password=CONCAT(MD5('qXpassword'), ':qX') WHERE username='admin';

‘qX’ would be changed to whatever you want it to be and same goes for ‘password’
You can also do this in phpMyAdmin, find the admin_user field and choose MD5 when updating password.
If you want to add a new admin user, you must not only create a new entry in the table ‘admin_user’, but you also have to insert an entry in the table ‘admin_role’ which has to be associated with the user by the field ‘user_id’.

Create an Admin Interface in Laravel

Nowadays, you’d be hard-pressed to find a PHP developer who doesn’t know about Laravel. If you are one of these people, visit the Laravel site ASAP! The framework is insanely popular in the PHP community these days because of the thought that has gone into it to make it easy to use and robust as hell! We will demonstrate its easy-of-use by building an admin interface that we can use to manage our users in some fake application we have already built. Let’s do it!

The Files

We need to download the files locally and get our project configs set up. Let’s do this really quick. Run the following command to download the files and all its dependencies. I’m assuming you have composer downloaded globally on your machine.
1composer create-project laravel/laravel useradmin
This will create a directory called useradmin, put all of Laravel’s files in it, and then download all of Laravel’s dependencies. Next, we need to fill in our configs. Go into the config files and fill in what’s necessary. I always fill in URL and timezone in app.php and the MySQL info in database.php.
EDIT: Thanks to Triggvy Gunderson for pointing out the following two extra steps to take. You should change the debug option to true when in development to make sure you can see a helpful error screen. Also, make sure to make the app/storage directory writable by executing the following from the root of your project:
1chmod -R 777 app/storage
Now that all that initial setup is done, let’s create and seed our database.

The Database

We need to create our database table to hold our users in, and then we will seed it with some data for us to play with. Run the following command to get some boilerplate code written for us to make our table.
1php artisan migrate:make create_users_table –create=users
If you go to /app/database/migrations, there will be a new migration file waiting for you. Let’s fill it out.

1
2
3
4
5
6
7
8
<!--?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table-&gt;increments('id');&lt;br ?--> $table-&gt;string('username');
$table-&gt;string('email');
$table-&gt;string('password');
$table-&gt;string('first_name');
$table-&gt;string('last_name');
$table-&gt;timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop(‘users’);
}

}

This is all we need to create our database table! Piece of cake. Now let’s seed the table to give us some fake data to play with later.

1
 

‘username’ => ‘doctorv’,
’email’ => ‘darthv@deathstar.com’,
‘password’ => Hash::make(‘thedarkside’),
‘first_name’ => ‘Darth’,
‘last_name’ => ‘Vader’,
‘created_at’ => new DateTime(),
‘updated_at’ => new DateTime()
]);

DB::table(‘users’)->insert([
‘username’ => ‘goodsidesoldier’,
’email’ => ‘lightwalker@rebels.com’,
‘password’ => Hash::make(‘hesnotmydad’),
‘first_name’ => ‘Luke’,
‘last_name’ => ‘Skywalker’,
‘created_at’ => new DateTime(),
‘updated_at’ => new DateTime()
]);

DB::table(‘users’)->insert([
‘username’ => ‘greendemon’,
’email’ => ‘dancingsmallman@rebels.com’,
‘password’ => Hash::make(‘yodaIam’),
‘first_name’ => ‘Yoda’,
‘last_name’ => ‘Unknown’,
‘created_at’ => new DateTime(),
‘updated_at’ => new DateTime()
]);
}

}

Make sure to uncomment the line in DatabaseSeeder.php so that our seed file will actually be called. Lastly, run the following command to run the migrations and then seed the database.
1php artisan migrate –seed

The Login Page

Now, we should try to block off the admin area from people who shouldn’t be able to have access. Let’s add the logic for this into our application. Make your routes.php look like the below:

1
2
1 <!--?php &lt;br ?--> 2
3 Route::controller('/', 'HomeController');

That line creates a “controller” route in our application. This means we can create a route by editing our controller, not our routes file. For example, in our HomeController, we could set up a route that is picked up when we send a PUT request to the url /example by making a method called putExample. Let’s get into it. Make your HomeController look like the following:

1
 

{
return Redirect::intended(‘/user’);
}

return Redirect::back()
->withInput()
->withErrors(‘That username/password combo does not exist.’);
}

public function getLogin()
{
return Redirect::to(‘/’);
}

public function getLogout()
{
Auth::logout();

return Redirect::to(‘/’);
}

}

Here we are setting up the login routes to display the login form and process it. The getIndex route simply returns a view to display, which we will make in a moment. We then set up a route to handle the input we receive from the login form. It uses the Auth::attempt to login the user. This method is another example of Laravel making our job easier! It tests the given credentials against credentials in the database. The table to use is stated in the auth.php config file. It will automatically log the user in and return true if the user credentials check out. If not, we are redirecting back to the previous page (our login page) with the given input and with an error message to let the user know what’s up. We also create a login route that redirects back to our home page. Lastly, we create a logout route that will log a user out using Laravel’s Auth::logout function and then redirect to our home page.
Now that we have the routes created, let’s create the views. We only need one view for this controller. We need to put it in the app/views/home/ directory. We will call it index.blade.php. Laravel uses the blade template engine, which allows us to keep our views readable but powerful. Put the following code in app/views/home/index.blade.php.

1
@extends('layouts.master')

@section(‘title’) Login @stop

@section(‘content’)

@if ($errors->has())
@foreach ($errors->all() as $error)

{{ $error }}

@endforeach
@endif

Login

{{ Form::open([‘role’ => ‘form’]) }}

{{ Form::label(‘username’, ‘Username’) }}
{{ Form::text(‘username’, null, [‘placeholder’ => ‘Username’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password’, ‘Password’) }}
{{ Form::password(‘password’, [‘placeholder’ => ‘Password’, ‘class’ => ‘form-control’]) }}
{{ Form::submit(‘Login’, [‘class’ => ‘btn btn-primary’]) }}

{{ Form::close() }}

@stop

Nothing crazy happening here. We are creating a form that will submit to our route. By default, Laravel forms submit a POST request to the same URL we are on. This is perfect for the way we set up our login routes. At the top, you can see we are extending a layout. Let’s create that too. This is a good practice for making extendable routes in your applications. Use the layouts to create basic templates for your views so your main view files need the least amount of code in them. Layouts usually include the CSS and JavaScript files that are used in all views. Below is the layout I used. It should be in app/views/layouts/master.blade.php.

1
 

@yield(‘title’) | User Admin

 

 

@yield(‘content’)

 
This is a basic layout. It brings in Twitter Bootstrap and Font Awesome just to make our views look pretty. I’m not much of a designer. Bootstrap is my savior!
In your browser, navigate to your project. I set up a virtual host for mine. So, I go to http://local.useradmin.com. This loads up the login screen we created. Going great so far. Let’s test that we get an error if we don’t enter valid credentials. Enter anything crazy in the username and password fields and hit enter. You should be taken back to the same page with an error at the top and the username already filled in. Awesome-sauce. Now let’s make sure we can get logged in. Log in with one of the credentials we seeded our database with. I like the Darth Vader one, personally. Hit enter and…wait. What the hell? What’s this error? Well, we haven’t created that route yet. Laravel is kind enough to let us know what we did wrong. So let’s make that now!

The User Management

Now, we need to make the user management functionality. First, let’s add a convenience method to our User model that we will user in our admin view. Add the following method to your User model.

1
2
3
4
5
6
7
8
9
1 /**
2 * Get the user's full name by concatenating the first and last names
3 *
4 * @return string
5 */
6 public function getFullName()
7 {
8 return $this-&gt;first_name . ' ' . $this-&gt;last_name;
9 }

This is a method to return a user’s full name. This is just a convenience. I use this in all my projects. Now that we have this, let’s add a route to our routes file to expose our the user controller we will create to our application. Make your routes.php file look like the below.

1
2
3
1 <!--?php &lt;br ?--> 2
3 Route::resource('/user', 'UserController');
4 Route::controller('/', 'HomeController');

We added a resource route. This allows us to interact with our controller in a RESTful way. If you don’t know REST, then read up here! It just standardizes the way we interact with our application. Now, let’s create our controller. Let’s utilize Laravel’s command line utility Artisan and have it create some boilerplate code for us. Run the following command.
1php artisan controller:make UserController –except=show
This creates a RESTful controller for us. It can be found in app/controllers. It has all the methods in it we will use. Notice I passed the except option with a value of show. This tells Artisan that we want all the methods in our code except the show method. For our particular use, we don’t need a page just one user. For a better explanation of each of these methods, see the Laravel docs.
Let’s populate our controller with our functionality. Make it look like the below code.

1
 

}

/**
* Display a listing of the user.
*
* @return Response
*/
public function index()
{
$users = User::all();

return View::make(‘user.index’, [‘users’ => $users]);
}

/**
* Show the form for creating a new user.
*
* @return Response
*/
public function create()
{
return View::make(‘user.create’);
}

/**
* Store a newly created user in storage.
*
* @return Response
*/
public function store()
{
$user = new User;

$user->first_name = Input::get(‘first_name’);
$user->last_name = Input::get(‘last_name’);
$user->username = Input::get(‘username’);
$user->email = Input::get(’email’);
$user->password = Hash::make(Input::get(‘password’));

$user->save();

return Redirect::to(‘/user’);
}

/**
* Show the form for editing the specified user.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$user = User::find($id);

return View::make(‘user.edit’, [ ‘user’ => $user ]);
}

/**
* Update the specified user in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
$user = User::find($id);

$user->first_name = Input::get(‘first_name’);
$user->last_name = Input::get(‘last_name’);
$user->username = Input::get(‘username’);
$user->email = Input::get(’email’);
$user->password = Hash::make(Input::get(‘password’));

$user->save();

return Redirect::to(‘/user’);
}

/**
* Remove the specified user from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
User::destroy($id);

return Redirect::to(‘/user’);
}

}
That’s alot. I’ll walk through this kind of quickly for the sake of brevity. At the top, I create a construct method for our controller. This will be fired each time or controller is created. I used the beforeFilter method in it. This will fire the given filter whenever this controller is created. For this particular case, I only want to make sure the user is logged in. This filter is supplied to us by Laravel out of the box. If a user is not logged in, it will send them to the /login page. This is why we created the login route in our HomeController that redirects to our homepage. Otherwise we would get an error.
In the index, we get all our users and pass them to our main view. The create method displays the form to add a new user. The store method grabs the input given in the request and saves the user to the database. The edit method grabs the user specified in the URL and sends that user to the view to be edited. The update method grabs the user and updates its attributes. Then saves the changes and redirects back to the main user screen. Lastly, the destroy method destroys the user specified in the URL and then redirects to the main user screen.
The only thing left is to make our views. Let’s do it. The first one should be our main index page. Let’s put it in app/views/user/index.blade.php.

1
 

@extends(‘layouts.master’)

@section(‘title’) Users @stop

@section(‘content’)

User Administration Logout

@foreach ($users as $user)@endforeach

Name Username Email Date/Time Added
{{ $user->getFullName() }} {{ $user->username }} {{ $user->email }} {{ $user->created_at->format(‘F d, Y h:ia’) }} Edit
{{ Form::open([‘url’ => ‘/user/’ . $user->id, ‘method’ => ‘DELETE’]) }}
{{ Form::submit(‘Delete’, [‘class’ => ‘btn btn-danger’])}}
{{ Form::close() }}

Add User

@stop
Again, we are extending our master layout. We are creating a table and using a foreach loop to iterate over each user that was passed into the view from the controller. We are outputting each of the attributes we keep in the database minus the password. We are also outputting two buttons – one to edit the user and one to delete them. Notice the edit button is just a link but the delete button is actually a form. This is because we need to send a delete request to our controller. This will ensure the destroy method is called. Because browsers don’t support the PUT or DELETE methods of forms, Laravel adds a hidden attribute to the form that lets the application know we are wanting to use the DELETE method. Also, notice we are using our helper method to output the user’s full name. We output a button after the table to add a new user. Lastly, we put a table at the top to logout. Alot of functionality for such a small file, huh?
Now, let’s build our new user form. This is simple.

1
 

@extends(‘layouts.master’)

@section(‘title’) Create User @stop

@section(‘content’)

@if ($errors->has())
@foreach ($errors->all() as $error)

{{ $error }}

@endforeach
@endif

Add User

{{ Form::open([‘role’ => ‘form’, ‘url’ => ‘/user’]) }}

{{ Form::label(‘first_name’, ‘First Name’) }}
{{ Form::text(‘first_name’, null, [‘placeholder’ => ‘First Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘last_name’, ‘Last Name’) }}
{{ Form::text(‘last_name’, null, [‘placeholder’ => ‘Last Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘username’, ‘Username’) }}
{{ Form::text(‘username’, null, [‘placeholder’ => ‘Username’, ‘class’ => ‘form-control’]) }}
{{ Form::label(’email’, ‘Email’) }}
{{ Form::email(’email’, null, [‘placeholder’ => ‘Email’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password’, ‘Password’) }}
{{ Form::password(‘password’, [‘placeholder’ => ‘Password’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password_confirmation’, ‘Confirm Password’) }}
{{ Form::password(‘password_confirmation’, [‘placeholder’ => ‘Confirm Password’, ‘class’ => ‘form-control’]) }}
{{ Form::submit(‘Login’, [‘class’ => ‘btn btn-primary’]) }}

{{ Form::close() }}

@stop
The code in this file should look very familiar. It looks just like our login form except there are more fields in it. Also, we had to overwrite the URL our form submits to. To stick with the RESTful interface, we need to submit a POST request to /user.
Lastly, let’s make the form to edit a user.

1
 

@extends(‘layouts.master’)

@section(‘title’) Create User @stop

@section(‘content’)

@if ($errors->has())
@foreach ($errors->all() as $error)

{{ $error }}

@endforeach
@endif

Edit User

{{ Form::model($user, [‘role’ => ‘form’, ‘url’ => ‘/user/’ . $user->id, ‘method’ => ‘PUT’]) }}

{{ Form::label(‘first_name’, ‘First Name’) }}
{{ Form::text(‘first_name’, null, [‘placeholder’ => ‘First Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘last_name’, ‘Last Name’) }}
{{ Form::text(‘last_name’, null, [‘placeholder’ => ‘Last Name’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘username’, ‘Username’) }}
{{ Form::text(‘username’, null, [‘placeholder’ => ‘Username’, ‘class’ => ‘form-control’]) }}
{{ Form::label(’email’, ‘Email’) }}
{{ Form::email(’email’, null, [‘placeholder’ => ‘Email’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password’, ‘Password’) }}
{{ Form::password(‘password’, [‘placeholder’ => ‘Password’, ‘class’ => ‘form-control’]) }}
{{ Form::label(‘password_confirmation’, ‘Confirm Password’) }}
{{ Form::password(‘password_confirmation’, [‘placeholder’ => ‘Confirm Password’, ‘class’ => ‘form-control’]) }}
{{ Form::submit(‘Login’, [‘class’ => ‘btn btn-primary’]) }}

{{ Form::close() }}

@stop

This form is almost exactly the same as the add user form. On this form, we have to overwrite the URL is submits to and also the method it uses. We want this one to submit a PUT request. We also use the model form method instead of the open method. This method does the same thing as the open method except we supply it with a user and it fills in the fields for us by default. This is perfect for an edit form. Thanks Laravel!

Wrapping Up

As you can see, Laravel makes doing common tasks super easy! One thing we should add to this is roles and permissions. We need a way to keep unauthroized users from access our user admin page. Right now, any signed-up user can access it. That isn’t very secure. To add roles and permissions to your project, see my other posts, Adding Roles to Laravel Users and Using Entrust to Add Roles and Permissions to Laravel 4, and check out my Laravel package Drawbridge. If this has wet your appetite for Laravel, check out the docs. It’s a great system to understand since it is the most popular right now. Leave a comment if you liked the article or just want to say, “Hi!”

Further Reading

How To Put Site Into Maintenance Mode

If you are using the Apache server, you can use.htaccess to control access of the directories within the server, and send a response code of the server status.
To put the website into maintenance mode, you can use the 503 status code, which indicates that the server is temporarily unavailable.
Before we specify anything in .htaccess, however, we need to create a new file in.html or .php format, and add a message in the file, e.g.
Sorry we are down for maintenance, but we’ll be back up shortly.
Style your page. Next, open the .htaccess file in your server, and add the following:

1
2
3
4
5
6
7
1. <IfModule mod_rewrite.c>
2. RewriteEngine on
3. RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
4. RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
5. RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]
6. RewriteRule .* /maintenance.html [R=503,L]
7. </IfModule>

This will set the server status code to 503, while also redirects visitors to the maintenance page. You can set your IP address with the following line RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000 so that you will still be able to access your website.

Exporting Data to a Downloadable CSV File with CakePHP

Generating a downloadable CSV file in CakePHP seems to be a bit of a stumbling block for many relatively new to using Cake. It doesn’t need to be challenging. There’s just a few basic steps you need to put in place.

As an example we’ll consider a User model that contains contact details of people who have register to our app. We want to create a CSV export of all the User data.

The Controller

Let’s start with the controller. We need to create an action in the User’s Controller for generating the CSV export:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
// app/Controllers/UsersController.php

class UsersController extends AppController {

    public function export() {

        $this->response->download("export.csv");

        $data = $this->User->find('all');
        $this->set(compact('data'));

        $this->layout = 'ajax';

        return;

    }

}

We’re calling

1
$this->response->download("export.csv")

to set the relevant headers. When you trigger the controller’s action from the browser it will start to download a file named ‘export.csv’ rather than attempt to display the view in the browser.

We then grab the data from the database and set it ready for the View.

Finally we set the View layout to use the AJAX layout, $this->layout = ‘ajax’. This might seem quirky, but it will ensure the View isn’t wrapped in any HTML markup. We just want to output the content of the View we are shortly about to put together.

The Route

As it currently stands the URL for our CSV export will be ‘users/export’; it would be nice to append that with the CSV extension. To do that we’re going to tell Cake to correctly parse CSV file requests. In our routes.php file (in app/Config/) add the following:-

1
Router::parseExtensions('csv');

This will now allow us to access our CSV export from the URL ‘users/export.csv’.

The View

Now we need to put together our View, making sure we correctly escape values being output:-

1
2
3
4
5
6
7
8
9
10
11
<?php

// app/Views/Users/export.ctp

foreach ($data as $row):
    foreach ($row['User'] as &$cell):
        // Escape double quotation marks
        $cell = '"' . preg_replace('/"/','""',$cell) . '"';
    endforeach;
    echo implode(',', $row['User']) . "\n";
endforeach;

This should be pretty self explanatory. We’re looping over all the rows in our

1
$data

array; escaping any double quotation marks in the values and then wrapping the value in quotation marks; and finally outputting the row delimiting values with commas and adding a new line break at the end.

Finally

Everything should now be setup, you’ll just want to be able to link to your CSV export from another View. If you’re parsing the file extension then you need to include this in the URL; so using the HtmlHelper we need to include the ‘ext’ parameter for the file extension:-

1
2
3
4
5
echo $this->Html->link('export', array(
    'controller' => 'users',
    'action' => 'export',
    'ext' => 'csv'
));

That should be it! Clicking on the ‘export’ link should start the browser downloading ourexport.csv file.

How to Create CakePHP Controller,Model and View by Bake console

CakePHP’s Bake console is easy and powerful tool to kick start your project. You will be able to step up a full working application in a few minutes using it.
In this tutorial, we will show you how to use CakePHP’s Bake console to generate model, controller and view codes by simple console commends.
Please note this tutorial requires basic understanding of CakePHP framework, at least you should be able to write a hello world application on your own.
If you have not yet used CakePHP, please read the offical Cookbook. – See more at:

Set Up Bake console

I have already setup a CakePHP project under :

1
C:\wampp\www\personal-tutorial

First thing we are going to do is to verify if Environment Variables is set properly in your windows machine.

Go to Command Prompt(I hope you know what ‘CMD’ is, do a Google search on ‘CMD windows’ if you have no idea.) in windows and type in “cake bake” from any path:

1
C:\Users\Chauhan&gt;cake bake

If you get following message:

1
2
3
C:\Users\xd&gt;cake bake
'cake' is not recognized as an internal or external command,
operable program or batch file.

You will need to set up the Environment Variables; specifically it is the Path variable. Follow the steps below:

  1. Locate ‘Path‘ Variable under System variables section of Environment Variables.
    If you do not know where this setting is, you can follow this link.
  2. Double click on ‘Path‘ variable and bring it up to edit. Before doing any editing, please backup its original value.
    Path variables are separated by ‘;”.
    What we need to do is to add a path pointing to “C:\wampp\www\personal-tutorial\cake\console\” folder.
    So at the end of existing Path value, we add “;C:\wampp\www\personal-tutorial\cake\console\“. Please pay extra attention to ‘;’ at the beginning of the added string.
  3. Finally click on ‘OK’ to save your setting. And restart Command Prompt (setting will only take effect on new Command Prompt). Type in “cake” to verify if it is working:
1
2
3
4
C:\Users\xd&gt;cake
Welcome to CakePHP v1.3.2 Console
---------------------------------------------------------------
******

Step Up Database table


We will need a database table for CakePHP console to generate the codes. Let us create table in our database:

1
2
3
4
5
CREATE TABLE `posts` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` INT( 250 ) NOT NULL ,
`content` TEXT NOT NULL
) ENGINE = InnoDB;

Bake model


Now open Command Prompt and CMD to “C:\wampp\www\personal-tutorial\app” as below:

1
C:\&gt; cd wampp\www\personal-tutorial\app

Then enter “cake bake” in the Command Prompt:

1
2
C:\&gt;cd xampp\htdocs\personal-tutorial\app
C:\xampp\htdocs\personal-tutorial\app&gt;cake bake

If you get a message similar to this:

1
2
3
4
5
6
Welcome to CakePHP v1.3.2 Console
---------------------------------------------------------------
App : app
Path: C:\xampp\htdocs\personal-tutorial\app
---------------------------------------------------------------
Your database configuration was not found. Take a moment to create one.

This means it is a fresh copy of CakePHP project you are working on, you are asked to create database configuration file (which is “app/config/database.php”). Just follow the instructions, it will automatically generate a database.php for you.

If you get a message similar to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Welcome to CakePHP v1.3.2 Console
------------------------------------------------
App : app
Path: C:\xampp\htdocs\personal-tutorial\app
------------------------------------------------
Interactive Bake Shell
------------------------------------------------
[D]atabase Configuration
[M]odel
[V]iew
[C]ontroller
[P]roject
[F]ixture
[T]est case
[Q]uit
What would you like to Bake? (D/M/V/C/P/F/T/Q)

This means you are ready to go. Just enter “Q” to quit first.

Now go back to Command Prompt and do “cake bake model post” as follow:

1
C:\wampp\www\personal-tutorial\app>cake bake model post

You should get message like similar to this:

1
2
3
4
5
6
C:\wampp\www\personal-tutorial\app>cake bake model post
Welcome to CakePHP v1.3.2 Console
---------------------------------------------------------------
App : app
Path: C:\wampp\www\personal-tutorial\app
---------------------------------------------------------------

Baking model class for Post…

Creating file C:\wampp\www\personal-tutorial\app\models\post.php
Wrote `C:\wampp\www\personal-tutorial\app\models\post.php`

You can download SimpleTest from http://simpletest.org

Baking test fixture for Post…

Creating file C:\wampp\www\personal-tutorial\app\tests\fixtures\post_fixture.php
Wrote `C:\wampp\www\personal-tutorial\app\tests\fixtures\post_fixture.php`
Bake is detecting possible fixtures..

Creating file C:\wampp\www\personal-tutorial\app\tests\cases\models\post.test.php
Wrote `C:\wampp\www\personal-tutorial\app\tests\cases\models\post.test.php`

Bake controller


Baking controller is similar to bake model. From the same Command Prompt above, enter “cake bake controller post scaffold” to bake the controller class. A few notes to take:

1
C:\wampp\www\personal-tutorial\app&gt;cake bake controller post scaffold

This will generate standard controller class which all CRUD methods implemented.

1
C:\wampp\www\personal-tutorial\app&gt;cake bake controller post

This will create a scaffolding controller, which means no functions will be defined in the controller, and view files will not be generated.

1
C:\wampp\www\personal-tutorial\app&gt;cake bake controller post scaffold admin

This will prepend “admin_” to each function. This is perfect if you are using any prefix routes. You can change “admin” to any value you needed.

You should get following message for a successful generation:

1
2
3
4
5
6
7
8
9
10
11
C:\wampp\www\personal-tutorial\app&gt;cake bake controller post
Welcome to CakePHP v1.3.2 Console
---------------------------------------------------------------
App : app
Path: C:\wampp\www\personal-tutorial\app
---------------------------------------------------------------
Creating file C:\wampp\www\personal-tutorial\app\controllers\posts_controller.php
Wrote `C:\wampp\www\personal-tutorial\app\controllers\posts_controller.php`
Bake is detecting possible fixtures..
Creating file C:\wampp\www\personal-tutorial\app\tests\cases\controllers\posts_controller.test.php
Wrote `C:\wampp\www\personal-tutorial\app\tests\cases\controllers\posts_controller.test.php`

Bake view


Bake view files is very straightforward. From the same Command Prompt above, and do

1
C:\wampp\www\personal-tutorial\app&gt;cake bake view post

This will generate corresponding views depends on your controller class. So make sure you follow the order correctly, first bake controller, then view.You should get following message for a successful generation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
C:\wampp\www\personal-tutorial\app cake bake view post

Welcome to CakePHP v1.3.2 Console
---------------------------------------------------------------
App : app
Path: C:\wamp\www\personal-tutorial\app
---------------------------------------------------------------

Creating file C:\wamp\www\personal-tutorial\app\views\posts\index.ctp
Wrote `C:\wamp\www\personal-tutorial\app\views\posts\index.ctp`

Creating file C:\wamp\www\personal-tutorial\app\views\posts\view.ctp
Wrote `C:\wamp\www\personal-tutorial\app\views\posts\view.ctp`

Creating file C:\wamp\www\personal-tutorial\app\views\posts\add.ctp
Wrote `C:\wamp\www\personal-tutorial\app\views\posts\add.ctp`

Creating file C:\wamp\www\personal-tutorial\app\views\posts\edit.ctp
Wrote `C:\wamp\www\personal-tutorial\app\views\posts\edit.ctp`

Finish


 

Now go and check folders “app/controllers”, “app/models” and “app/views”. You will find “posts_controller.php”, “post.php” and “app/views/posts”. They are all auto generated.

Open browser and head to “http://localhost/personal-tutorial/posts”

How to Reduce and clean the options table of wp session entries

Every visitor will have a temporary session stored on the options table. The session tokens are very small, it is a server side cookie store. The sessions automatically purge after 30 minutes of inactivity.

But when its not not purge automatically then it create a problem and your database size increase too much that effected your site speed.

So we should need to delete these entries manually or create a plugin for that i will show you how can be delete these through phpmyadmin command or by a plugin.

By Mysql command:

1
2
3
DELETE
FROM `wp_options`
WHERE option_name LIKE '_wp_session%'

You should create a plugin that will schedule an event that occurs daily:

1
2
register_activation_hook(__FILE__, 'my_activation');
add_action('my_daily_event', 'do_this_daily');

function my_activation() {
wp_schedule_event(time(), ‘daily’, ‘my_daily_event’);
}

function do_this_daily() {
$wpdb->query(
“DELETE FROM $wpdb->options
WHERE option_name LIKE ‘_wp_session%’

)
}