Showing posts with label [IT]CodeIgniter. Show all posts
Showing posts with label [IT]CodeIgniter. Show all posts

Friday, November 7, 2014

Basic http server authentication from mobile app via ajax

1. script for ajax 
function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}
$.ajax({
type: 'POST',
beforeSend: function (xhr){  xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));   },
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
url: 'http://www.gtatrade.ca/mobiletest',
data: ({name: "aaa"}),
success: function(data){alert(data.name);},
error: function(e, x, settings, exception){alert("error!!" + "," + e.staus + ","  + e.responseText + ","  + x + ","  + settings + ","  + exception);},
dataType: 'json'
});

*** If you send header every time, use ajaxSetup like below.
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));
    }
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
});

2. Server php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header("Access-Control-Allow-Origin: *"); // required for cross domain .. 
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
header("Access-Control-Allow-Origin: *");  // required for cross domain ..
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    $output = array("name"=>$_SERVER['PHP_AUTH_USER'], "pass"=>$_SERVER['PHP_AUTH_PW']);
    echo json_encode($output);
}

Saturday, June 14, 2014

[CodeIgniter] Remove the index.php in the URL and using sub folders for controller.

1. Edit .htacess file in www root folder.
This is what I have...

<IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On
  RewriteBase /
  # If your default controller is something other than 'welcome' you should probably change this.
  RewriteRule ^(welcome(/index)?|index(\.php)?)/?$ / [L,R=301]
  RewriteRule ^(.*)/index/?$ $1 [L,R=301]
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ /index.php/$1 [L]
  SetEnvIfNoCase X-Forwarded-For .+ proxy=yes
  SetEnvIfNoCase X-moz prefetch no_access=yes
  
  # Block pre-fetch requests with X-moz headers.
  RewriteCond %{ENV:no_access} yes
  RewriteRule .* - [F,L]
  # Fix for infinite redirect loops.
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [L]
</IfModule>

2. Make mod_rewrite enabled in apache configuration file(httpd.conf)
Just uncoment this line.
LoadModule rewrite_module modules/mod_rewrite.so

Make sure AllowOverride is set to All.
AllowOverride All

3. Extend the core Router class of CodeIgniter(for using controller sub folder)
You can obtain the MY_Router.php file at this link and save it to application/core/ folder.
https://degreesofzero.com/article/controllers-in-sub-sub-folders-in-codeigniter.html

4. Restart WAMP server.

5. Tips - If you want to add port based virtual hosts ....

Listen 8080
NameVirtualHost *:8080

<Directory />
#    Require all denied
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

<VirtualHost *:8080>
    ServerName localhost
    DocumentRoot "D:/admin"
</VirtualHost>



Sunday, April 20, 2014

Code igniter multiple file upload.

1. Prepare upload form view.

<< uploadview.php >>

<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h2> file upload example </h2>
Only image files(gif|jpg|png) can be accepted. <br /> <br />
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" /><br /><br />
<input type="file" name="userfile2" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>

2. Prepare uploadsuccess page view.

<< uploadsuccess.php >>

<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<table ><tr valign=top><td>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<img src="/uploads/<?php echo $upload_data["file_name"]?>">
</td><td>
<ul>
<?php foreach ($upload_data2 as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<img src="/uploads/<?php echo $upload_data2["file_name"]?>">
</td></tr></table>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>

3. Prepare upload controller.

<< upload.php >>

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

   function index()
   {
     $data['error'] = '';
     $this->load->view('uploadview', $data);
   }
   function do_upload()
   {
     $this->load->helper(array('form', 'url'));
     $config['upload_path'] = 'C:\wamp\www\uploads';
     $config['allowed_types'] = 'gif|jpg|png';
     $config['max_size'] = '100';
     $config['max_width']  = '1024';
     $config['max_height']  = '768';
     $this->load->library('upload', $config);

     $result = $this->upload->do_upload("userfile");
     if (!$result){
         $error = array('error' => $this->upload->display_errors());
         echo $this->upload->display_errors();
         $this->load->view('uploadview', $error);
         return;
     }
     $data = array('upload_data' => $this->upload->data());
     $result2 = $this->upload->do_upload("userfile2");
     if (!$result2){
         $error = array('error' => $this->upload->display_errors());
         echo $this->upload->display_errors();
         $this->load->view('uploadview', $error);
         return;
     }
     $data['upload_data2'] = $this->upload->data();
     $this->load->view('uploadsuccess', $data);
     }
}

4. You can find more information from this user-guide page.

http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

Thursday, March 27, 2014

Use code igniter [Code ignigter install and create helloworld app.]

1. Install code igniter.

  • go to code igniter site and click download button.
http://ellislab.com/codeigniter
  • Installation Instruction.(Please refer to Code Igniter user guide.)
  1. Unzip the package.
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  3. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
  4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
2. create hello world php.
  • create helloworld.php file in application/controllers folder with these codes.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Helloworld extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

   function index()
   {
     echo 'Hello world!';
   }
   function test()
   {
      echo 'Second hello world!';
   }
}
3. create hello world php with view.
  • update helloworld.php file with these codes.
   function index()
   {
    // echo 'Hello world!';
       $this->load->view('helloview');
   }
  • create helloview.php file in application/view folder with these codes.
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Hello World App</title>
</head>
<body>
    <h1>Hello World!</h1>
    <div >
        <p>My First CodeIgniter Application.
    </div>
</body>
</html>
4. passing parameters to view.

  • update helloworld.php file with these codes.
   function index()
   {
     // echo 'Hello world!';
  $data['message'] = 'Hello World!!!';
  $this->load->view('helloview', $data);
   }
  • update helloview.php file with these codes.
  <body>
    <h1><?php echo $message; ?></h1>