codeigniter

codeigniter _remap extensive user


public function _remap($method, $params = array()){
if(method_exists($this, str_replace(‘-‘,’_’,$method))
{

  •      call_user_func_array(arrar($this, str_replace(‘-‘,’_’,$method)), $params)

}else{

  •       show_404();

}
}

Advertisements
codeigniter, jquery

CodeIgniter Uploadify problem


CodeIgniter Uploadify problem

I tried to implement Uploadify with CodeIgniter upload class, and had some issues with recognising proper mime types.

First issue was solved by extending application/config/mimes.php with code:

1 'gif'   =>   array('image/gif','application/octet-stream'),
2 'jpeg'  =>   array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
3 'jpg'   =>   array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
4 'jpe'   =>   array('image/jpeg', 'image/pjpeg', 'application/octet-stream'),
5 'png'   =>   array('image/png''image/x-png', 'application/octet-stream'),

You also need to extend Upload.php by uploading this extension:
Download
to application/library

Result from controller should looks like this

1   if ( ! $this->upload->do_upload('Filedata')) {
2                 $error = array('error' => $this->upload->display_errors());
3         } else {
4                 $data = $this->upload->data();
5         }
6 $return = array('name' => $data['file_name'],
7                 'size' => round($data['file_size'] * 100),
8                 'type' => $data['file_type']);
9 echo json_encode(array('Filedata' => $return));
codeigniter, mysql, php

Exporting your MySQL table data with PHPExcel + CodeIgniter


Exporting your MySQL table data with PHPExcel + CodeIgniter

http://www.facebook.com/plugins/like.php?channel_url=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%3Fversion%3D3%23cb%3Df195a68dc416bf4%26origin%3Dhttp%253A%252F%252Fwww.dannyherran.com%252Ff100e4067be86da%26relation%3Dparent.parent%26transport%3Dpostmessage&extended_social_context=false&href=http%3A%2F%2Fwww.dannyherran.com%2F2011%2F03%2Fexporting-your-mysql-table-data-with-phpexcel-codeigniter%2F&layout=button_count&locale=en_US&node_type=link&sdk=joey&show_faces=false&width=90 http://platform.twitter.com/widgets/tweet_button.html#_=1323938558067&_version=2&count=horizontal&enableNewSizing=false&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fwww.dannyherran.com%2F2011%2F03%2Fexporting-your-mysql-table-data-with-phpexcel-codeigniter%2F&size=m&text=Exporting%20your%20MySQL%20table%20data%20with%20PHPExcel%20%2B%20CodeIgniter&url=http%3A%2F%2Fwww.dannyherran.com%2F2011%2F03%2Fexporting-your-mysql-table-data-with-phpexcel-codeigniter%2F&via=DannyHerran

 

PHPExcel + CodeIgniter Most of the time my clients need to download data from their database tables. Exporting to CSV is a pain in the rear for users and it leads to confusion (you know the colon and semicolon stuff). Today, I decided to make a very small controller that is portable and efficient for exporting full MySQL tables to Excel 2003 using PHPExcel and CodeIgniter.

First of all, you need PHPExcel which should be installed as a CodeIgniter library. In order to do this, you should follow the steps posted in the CodeIgniter Wiki.

Once you have PHPExcel installed and configured, make a controller exactly like this one:

Code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Table_export extends Controller {
    function __construct()
    {
        parent::Controller();
        // Here you should add some sort of user validation
        // to prevent strangers from pulling your table data
    }
    function index($table_name)
    {
        $query = $this->db->get($table_name);
        if(!$query)
            return false;
        // Starting the PHPExcel library
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
        $objPHPExcel->setActiveSheetIndex(0);
        // Field names in the first row
        $fields = $query->list_fields();
        $col = 0;
        foreach ($fields as $field)
        {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
            $col++;
        }
        // Fetching the table data
        $row = 2;
        foreach($query->result() as $data)
        {
            $col = 0;
            foreach ($fields as $field)
            {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
                $col++;
            }
            $row++;
        }
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        // Sending headers to force the user to download the file
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Products_'.date('dMy').'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
    }
}

Whenever you need to export data from a MySQL table, you just need to call this controller and pass the table name as a parameter, sort of like http://www.yoursite.com/table_export/products. Obviously, you should always add some sort of security measure in order to prevent strangers from pulling all your table information. Just add some session protection to your constructor and you’re set.

codeigniter, php

renaming file and folders name with codeigniter


if ( ! $this->upload->do_upload())
{
return $this->upload->display_errors();
}
else
{
$res = $this->upload->data();

$file_path     = $res[‘file_path’];
$file         = $res[‘full_path’];
$file_ext     = $res[‘file_ext’];

$final_file_name = time().$file_ext;
 

// here is the renaming functon
rename($file, $file_path . $final_file_name);

}

codeigniter

Easy Reverse Routing with CodeIgniter


Easy Reverse Routing with CodeIgniter

By Kenny Katzgrau | Published: September 21, 2010

I really can’t stand hard-coding URLs in the views or controllers of my application — and I’m sure most other people can’t either. Here’s an extension for the CodeIgniter Router class that I wrote that gives you a nice way to write routes that are reversible and also have the ability to take parameters.

<?php

class MY_Router extends CI_Router
{
    private $_reverseRoutes = NULL;

    CONST ARR_ROUTE_POS      = 0;
    CONST ARR_ROUTE_NAME_POS = 1;

    function _parse_routes()
    {
		// Do we even have any custom routing to deal with?
		// There is a default scaffolding trigger, so we'll look just for 1
		if (count($this->routes) == 1)
		{
			$this->_set_request($this->uri->segments);
			return;
		}

		// Turn the segment array into a URI string
		$uri = implode('/', $this->uri->segments);

		// Is there a literal match?  If so we're done
		if (isset($this->routes[$uri]))
		{
			$this->_set_request(explode('/', $this->routes[$uri][self::ARR_ROUTE_POS]));
			return;
		}

		// Loop through the route array looking for wild-cards
		foreach ($this->routes as $key => $val)
		{
			// Convert wild-cards to RegEx
            //echo "$key --> ";
			$key = preg_replace('/\:\w+/', '[\w\-_]+', $key);
            //echo "$key <br />";
			// Does the RegEx match?
			if (preg_match('#^'.$key.'$#', $uri))
			{
				// Do we have a back-reference?
				if (strpos($val[self::ARR_ROUTE_POS], '$') !== FALSE AND strpos($key, '(') !== FALSE)
				{
					$val = preg_replace('#^'.$key.'$#', $val[self::ARR_ROUTE_POS], $uri);   
				}

				$this->_set_request(explode('/', $val));
				return;
			}
		}

		// If we got this far it means we didn't encounter a
		// matching route so we'll set the site default route
		$this->_set_request($this->uri->segments);
    }

    function _buildReverseRoutes()
    {
        $reverse_routes = array();

        foreach($this->routes as $route => $info)
        {
            # If this is a default route or scaffolding key, ignore it
            if(!is_array($info)) continue;

            $name = $info[self::ARR_ROUTE_NAME_POS];
            $reverse_routes[$name] = $route;
        }

        $this->_reverseRoutes = & $reverse_routes;
    }

    function reverseRoute($route_name, $args_keyval = array())
    {
        if($this->_reverseRoutes === NULL)
            $this->_buildReverseRoutes();

        if(!array_key_exists($route_name, $this->_reverseRoutes))
            show_error("No reverse route found for '$route_name'");

        $route = $this->_reverseRoutes[$route_name];

        foreach($args_keyval as $key => $val)
        {
            $route = str_replace("(:$key)", $val, $route);
        }

        return $route;
    }
}

Drop that into application/libraries, then rewrite your routes to look like this:

$route['users/(:username)']  = array('users/$1', 'user-homepage');
$route['companies/(:slug)']  = array('companies/$1', 'company-homepage');

Let me explain that.

CodeIgniter lets you use wildcards in your routes like (:any) or (:num). That’s no more with this extension. Basically, anything you put in (:[name]) format with be treated like (:any). That’s handy, and I’ll tell you why.

Once you rewrite you routes, you can now call a new method on the routing class when you need to, say, redirect the user to his homepage after login:

  # login was successful, and we now have a $user object
  $this->load->helper('url');
  redirect($this->router->reverseRoute('user-homepage', array('username' => $user->username));

The reverseRoute method takes two parameters: The route you want to send the use on, and any wildcards that you need to fill in the url. For the user-homepage route, there is a (:username) wildcard in the route. We can pass the appropriate fill-in for that wilcard with the second parameter with an associative key-value array.

A redirect to a company-homepage would look like:

  # ...
  redirect($this->router->reverseRoute('company-homepage', array('slug' => $company->slug));

Then in the future, if you feel like changing your routes, go no further than the routes file! Mucking around in views is a recipe for broken links.

 

source:

http://codefury.net/2010/09/easy-reverse-routing-with-codeigniter/

 

codeigniter

MSSQL Server 2005 and CodeIgniter


MSSQL Server 2005 and CodeIgniter

During development work on one of our larger projects, we uncovered some rather alarming problems when using php_mssql.dll in conjunction with SQL Server 2005 Express. Just by perusing some of the comments over at the PHP manual, you can see that we weren’t alone.

Refreshing the page would cause the mssql_connect function to fail. A further three or four refreshes would result in further failures, until suddenly one more refresh manages to establish a connection. This situation would repeat itself, and is completely random. Despite months of trying to track it down when we had spare time, we just could not get to the bottom of it.

A few months ago, a result began cropping up on Google that appeared to contain some answers. Part of Microsoft’s data programmability team announced they were working a new driver for PHP for use with SQL Server 2005. Excellent, we thought! Of course, we haven’t been able to use this driver in a production environment yet as it is still in beta and subject to change (and change it has). However, we’ve ran tests using the driver and so far, it does appear to be more stable. The only issue is that the symptom we were experiencing is very difficult to replicate (if nigh-on impossible), and so we cannot know for sure if the driver has alleviated the problem.

Parts of the project are written using an excellent framework known as CodeIgniter. We took the liberty of also writing an php_sqlsrv.dll compatible driver for it which you can download here. To use the driver, just unzip it into a folder called “system/database/drivers/sqlsrv” and change your database.php to reflect the changes (change the driver to “sqlsrv“). Hopefully this will help one person that was in the same boat as us!

The Microsoft SQL Server 2005 driver for PHP is a PHP 5 only extension. It allows the reading and writing of SQL Server data from within PHP scripts. The extension provides a procedural interface for accessing data in all editions (importantly, including Express) of SQL Server 2005 and also SQL Server 2000. The API makes use of PHP features such as PHP streams to read and write large objects.

 

reference:

http://www.kaweb.co.uk/blog/mssql-server-2005-and-codeigniter/

codeigniter, mysql, php

CodeIgniter/PHP + IIS + MySQL + MSSQL: It Works!


http://codefury.net/2011/01/codeigniter-php-iis-mysql-mssql/

CodeIgniter/PHP + IIS + MySQL + MSSQL: It Works!

By Kenny Katzgrau | Published: January 11, 2011

There are a lot of people out there who call themselves “LAMP” developers — short for Linux, Apache, MySQL, PHP. That’s the standard configuration for production PHP applications. Recently, I ended up having to build a CodeIgniter application on Windows, IIS, Mysql+MS-SQL, and PHP. Sound like there are bound to be issues? You bet, and it especially hurts because now I’m a real-live WIMP developer.

And what made it even more interesting was that due to constraints, I had to develop the application in Ubuntu and deploy to Windows for production.

Please keep in mind that I didn’t opt for this setup by choice. The servers to be used were already in place, and well, it just had to be this way. I’d imagine this unholy mix can be found on server farms somewhere around the seventh or eighth circle of hell.

Anyway, the point of this post is to document a few “gotchas” that came up along the way. At this point I should say that application is now happily humming along in production. I knew from the start that mixing all of the above would be a headache, but luckily, things worked out without sapping too much time. I should also say this before I start: Thanks to some great work done by others over the past 2 years, this setup was actually possible.

Gotcha #1: PHP and MSSQL on Ubuntu

Thank god this was so easy. In order to use the standard database functions like mssql_connect, mssql_query, etc, all I needed to do within my existing LAMP installation was run:

$ sudo apt-get install php5-sybase

And sh-bang, I could connect to SQL Server without an issue. From CodeIgniter, I set the database to use mssql as my driver, and I was home free.

Gotcha #2: PHP and MSSQL on Windows

For years, forums and IRC rooms were filled with hopeless requests to get these two to mix. In 2008, Microsoft wrote a driver to help PHP developers seamlessly connect to SQL Server. For Win-PHP installations, just install this gem: http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&FamilyID=80e44913-24b4-4113-8807-caae6cf2ca05 . Also, read up on the docs.

That driver uses a different API then the regular PHP mssql_* functions. In fact, it uses sqlsrv_* functions instead. So CodeIgniter can’t work with it out of the box. Luckily I found an excellent 2 and 1/2 year-old post by a guy who wrote the CodeIgniter driver to work with the Microsoft drivers. Just download the code, and drop it into system/database/drivers. Read up here: http://www.kaweb.co.uk/blog/mssql-server-2005-and-codeigniter/

One thing you will have to do to make it work with the latest version of CodeIgniter is create a dummy function in sqlsrv_driver.php. Just drop ‘function db_set_charset() { }’ somewhere in the class declaration.

As a side note, that driver would make a great addition to CodeIgniter Reactor.

Gotcha #3: mssql vs. sqlsrv

Notice that I had to use different drivers for connecting to SQL Server between Ubuntu and Windows. This is why it’s handy to use some sort of database abstraction class like the one that comes with CodeIgniter. All I had to do to switch between drivers when I deployed to the new environment was edit the configuration.

Also, query result fields that are fetched using PHP’s mssql driver come back as strings. The Windows sqlsrv driver gets fancy and hands back field values as objects. Your code won’t have to change for the most part, but beware that MSSQL ‘datetime’ fields come back as native PHP DateTime objects using sqlsrv_*, not strings. In the code, I ended up doing something like: if($date instanceof DateTime) return $date->format(…); else return $date;

Edit: Commenter Brian Swan and Twitter user Juozas Kaziukėnas have pointed out that the sqlsrv_ PHP driver will take a boolean ‘ReturnDatesAsStrings’ option in sqlsrv_connect() that specifies whether datetime fields come back as strings or objects. More info is here: http://msdn.microsoft.com/en-us/library/ee376928%28v=sql.90%29.aspx. Thanks guys!

Gotcha #4: File Permissions and Logging

As the author of WPSearch, a Wordress search plugin which does heavy work with the filesystem, I can say that the number one cause of broken installations is that the permissions are too strict. On Windows, files can appear to be 777 when viewing them via FTP, but on the Windows end, they are set as ‘Read Only’, or ‘Archive’. This throws a serious wrench into things.

When I first deployed to the production server, all I would get for responses was a blank page. Worst of all, the log wasn’t writing anything. After a trace through the CodeIgniter bootstrap, I found that the application died when the logging class was loaded. If your application’s logging threshold is set to write anything, and the logging fails, the application might just crap-out. This is different behavior than I’ve seen on linux, where you just won’t see logs appear in the logging directory, but the overall application still works fine.

Just turn off logging to make sure that empty responses aren’t the result of file permission errors.

Gotcha #5: No .htaccess Fo’ You!

I hadn’t known that I needed to drop the final application into an IIS instance from the start. I learned about that 1 day prior to the launch. Before that, I though I’d be rollin’ on Windows/Apache. Wrong!

IIS doesn’t use silly .htaccess files, which I had only used for standard URL rewriting/prettified URLs. I was forced to decide between converting the .htaccess to an IIS web.config file, or just ditch the prettified URLs. Since it was a small application, I went with the latter. Here’s a nice StackOverflow thread discussing a translation though: http://stackoverflow.com/questions/702526/translating-an-apache-htaccess-file-to-an-iis-web-config

Edit: Juozas had some comments here too: “@_kennyk_  about .htaccess vs web.config – you can actually import .htaccess in IIS URL Rewrite section.”

Gotcha #6: 2 Databases, 1 Application

This is more of a CodeIgniter issue. For this application I had to lookup data in a MySQL database, then use some of that information to pull rows from a MSSQL database. The hurdle revolves around having two concurrent database connections open in CodeIgniter.

You can’t really load the database in traditional CodeIgniter style, like $this->load->database(), or by autoloading it. Something like this doesn’t work:

$this->load->database('mysql-group-name');
# Do Stuff with mysql
$this->load->database('mssql-group-name');
# Do Stuff with mssql

Instead, you have to ask CodeIgniter to hand you back the actual database object with each connection. It’s a good idea to encapsulate each within the models where you’re using them. Do something like this:

class SomeMySQLModel extends Model {
  # the mysql db instance
  private $_db = NULL;

  function SomeMySQLModel() {
    $this->_db = $this->load->database('mysql-group', TRUE);
  }
}
class SomeMSSQLModel extends Model {
   # the mssql db instance
   private $_db = NULL;

   function SomeMSSQLModel() {
     $this->_db = $this->load->database('mssql-group', TRUE);
   }
 }

Gotcha #7: Mysterious lag time

IIS can exhibit some odd behavior regarding response times. When I was initially testing the application on my SliceHost dev server, I was getting pretty speedy responses in about ~100ms (keep in mind that I was connecting to both MSSQL and MySQL across the internet, not locally).

But when I moved to production, requests were taking 6 seconds each. Confused, I thought there must be some sort of bottleneck in the application. I used CodeIgniter’s profiling and benchmarking classes to investigate. I benchmarked the MySQL and MSSQL connections, queries, and overall application execution time.

The app was reporting that it was finishing responses within 100ms. So where was this strange delay coming from?

I then thought there might be some sort of redirect loop going on. From the shell, I ran:

$ time curl -v [address]

And something else became apparent. The full content of the page would come back, but there was a 6 second lag before the connection would finally close. After a little research on the Google, it turns out I’m not the only one who’s observed this with PHP and IIS: http://www.google.com/search?q=iis+php+response+lag

I would like to say I figured out why IIS was being so lame, but the in-house net-admin suggested moving the application to another production server on hand, where the issue mysteriously dissappeared. At that point, everyone was happy, so I didn’t look into it any further. I did read about some resolutions regarding DNS settings, and skipping name resolutions in the db configurations. That might have been it, but I’ll never know.

Recap:

Don’t willingly try this. That being said, everything worked out much better than it could have, and there were relatively easy solutions to the bumps along the way. If you have to put together a project like this, I highly suggest using some sort of database abstraction (or a framework like CodeIgniter), and planning out how you’ll work out URLs, permissions, and differing environments. Thinking these things over will save you a lot of time, and hopefully leave the stakeholders a whole lot happier.

This entry was posted in CodeIgniter, PHP Development, Tools and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
One headache that has an easier fix than you mentioned is setting the ReturnDatesAsStrings connection setting to 1. As you would expect, this setting makes the sqlsrv driver return dates as strings (instead of the default PHPDate object). The docs for connection settings are here: http://msdn.microsoft.com/en-us/library/ff628167(SQL.90).aspx