Limit Download Speed With PHP

http://code.google.com/p/phptraining/source/browse/trunk/download_limited.php















class DownloadLimited
{
 /**
 * Send the local file to client with limit download rate as user view file name
 *
 * @param string $localFile file to send
 * @param string $userViewFileName filename client will see
 * @param float $downloadRate download limit speed in kb/s (ex: 50 kb/s)
 * @return no return
 */
 function sendFile($localFile,$userViewFileName,$downloadRate)
 {
 /** check file exists
 * @see file_exists
 */
 if(!file_exists($localFile))
 {
 throw new Exception('File not found execption file :'.$localFile.' not found');
}
/** check file is file
* @see is_file
*/
if(!is_file($localFile))
{
 throw new Exception($localFile.' not is a file');
}
if(!is_readable($localFile))
{
 throw new Exception('file '.$localFile.' not readable ');
}
// send headers
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($localFile));
header('Content-Disposition: filename='.$userViewFileName);

// flush header content
flush();
// open file stream
$file = fopen($localFile, "r");
while(!feof($file))
{

 // send the current file part to the browser
 print fread($file, round($downloadRate * 1024));

 // !important flush the content to the browser
 flush();

 // !important sleep one second
 sleep(1);
}

// close file stream
fclose($file);


}
/**
* Send the string data to client with limit download rate as user view file name
*
* @param string string data to send include ascii,utf-8 character
* @param string $userViewFileName filename client will see
* @param float $downloadRate download limit speed in kb/s (ex: 50 kb/s)
* @return no return
*/
function sendString($data,$userViewFileName,$downloadRate)
{
 // send headers
 header('Cache-control: private');
 header('Content-Type: application/octet-stream');
 header('Content-Length: '.strlen($data));
 header('Content-Disposition: filename='.$userViewFileName);
 // flush header content
 flush();

 $start=0;
 $sendSize=0;
 while($sendSize {
 $sendSize=round($downloadRate*1024);
 print substr($data,$start,$sendSize);
 $start=$sendSize;
 // !important flush the content to the browser
 flush();

 // !important sleep one second
 sleep(1);
}
}
}

Determine The First Day Of Week And The First Day Of Month

1. Determine the first day of week (Monday)












To find Monday of next week, we change 'last' to 'next'.
To determine the distance of current day with the first day of week, we use function:
<?php
echo floor((strtotime ("now")- strtotime("last Monday"))/86400);
?>
2. Determine the first day of month
<?php
$day = date('Y-m-d', strtotime(date('Y-m-01', strtotime("now"))));
return $day;
?>

Or:
<?php
$date = date("01/m/Y");
echo $date;
?>
Good luck!
Select Top Percent Records MSSQL, MySQL

Select Top Percent Records MSSQL, MySQL

Returning TOP records

Microsoft SQL Server
SELECT TOP 10 column FROM table
My SQL
- SELECT column FROM table LIMIT 10

Returning TOP PERCENT Records

Microsoft SQL Server
- SELECT TOP 50 PERCENT * FROM table
MySQL
SELECT @percentage := ROUND(COUNT(*) * 50/100) FROM table;
  PREPARE STMT FROM 'SELECT * FROM table LIMIT ?';
  EXECUTE STMT USING @percentage;
How To Setup SVN in BlueHost Host

How To Setup SVN in BlueHost Host

1. Request bluehost for access by ssh
2. Connect to server bt ssh client (PuTTY, Bitvise)
3. Setup
~$mkdir _src
~$cd _src
_src$wget http://subversion.tigris.org/downloads/subversion-1.4.6.tar.gz
_src$wget http://subversion.tigris.org/downloads/subversion-deps-1.4.6.tar.gz
_src$tar -xzvf subversion-1.4.6.tar.gz
_src$tar -xzvf subversion-deps-1.4.6.tar.gz
_src$cd subversion-1.4.6
_src/subversion-1.4.6$cd apr
_src/subversion-1.4.6/apr$./configure --enable-shared --prefix=$HOME
_src/subversion-1.4.6/apr$make && make install
_src/subversion-1.4.6/apr$cd ../apr-util
_src/subversion-1.4.6/apr-util$./configure --enable-shared --prefix=$HOME \
--with-expat=builtin --with-apr=$HOME \
--without-berlekey-db
_src/subversion-1.4.6/apr-util$make && make install
_src/subversion-1.4.6/apr-util$cd ../neon
_src/subversion-1.4.6/neon$EXTRA_CFLAGS="-L/usr/lib64 -fPIC"
_src/subversion-1.4.6/neon$CFLAGS="-L/usr/lib64 -fPIC"
_src/subversion-1.4.6/neon$./configure --prefix=/home/zzzzz/system --enable-shared
_src/subversion-1.4.6/neon$make && make install
_src/subversion-1.4.6/neon$cd ..
_src/subversion-1.4.6$./configure --prefix=/home/zzzzz/system --with-expat=builtin
_src/subversion-1.4.6$/$make && make install
Note : 
"~" sign represent root folder of user.
"$" sign separator execute command and folder (just type the following commands $ sign).

4. Configuration
~$nano -w .bash_profile 

(file .bash_profile in root folder. Eg: /home/bitjsc/.bash_profile)
Change this file
Find PATH=$PATH:$HOME/bin
Change to PATH=$PATH:$HOME/bin:$HOME/system/bin
Save it(Ctrl+X)

5. Test
- Logout
- Login
- Type : svn help
- Is success?

Good luck
How To Create A Website With Cakephp

How To Create A Website With Cakephp


  1. Introduction
  2. Download framework
  3. Setup and configure cakePHP
    1. Setup
    2. Configure
  4. Example about using cakePHP to manage customer in application web "Manage motel".
    1. Create database
    2. Coding
    3. Operating model
    4. Model
    5. Controller
    6. View
    7. Complete all features of module "Manage motel"
1. Introduction

CakePHP is a framework for php that is to provide a framework for developer use php to progress web applications fast, powerful without losing flexibility. And the more important is cakePHP is free. You can read about it from http://cakephp.org. To use it, developer must have basic knowlegde about PHP and HTML, ... You can see detail about content and some example on http://manual.cakephp.org.

2. Download Framework

Click to below link to download cakePHP framework (select stable release):

3. Setup and configure cakePHP

3.1. Setup

To use it, you need to setup some software: 
- A HTTP server (Ex : Apache, IIS) - cakePHP only support PHP version 4 or more.
- Database: cake php support database systems: MySql, PostgreSQl.

This guide based on "AppServ Version 2.5.7 for Windows" include : 
Apache Web Server Version 2.2.3
PHP Script Language Version 5.1.6
MySQL Database Version 5.0.24a
phpMyAdmin Database Manager Version 2.9.0.2

After download cakephp, you extract zip file to folder and copy to Apache Server folder.(Eg :  C:\AppServ\www\MyCake)

Example:
/MyCake
/app
/cake
/vendors
.htaccess
index.php

3.2. Configure

To cakePHP can work with database, you need to configuring database.php file, in default, this file is not exist. To configure it :
- Open database.php.default in /app/config
- Save as with name is database.php
- Change something:
var $default = array('driver' => 'mysql',
'connect' => 'mysql_connect',
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'project_name',
'prefix' => );
With username, password is username, password to login MySql's database.
The convention of naming database table:
- Cake table name should be in the form of multiple (eg: users, customers, students ... ).
- Table must have key with name is 'id'.
- If you use relationship , foreign key have name table name (remove s) + _ + id (eg : user_id , user without s +  "_" sign + id).

After setup and configure cakePHP, check cakePHP did setup or not , you can test by opening web browser and type : http://localhost/MyCake/. Attention to 2 lines : Your database configuration file is present. Cake is able to connect to the database. Determine if you have connected to your database Cake or not.

I will talk about features, as well as the Operating model of cakePHP, how to write a web application using cakePHP through below example :

4. Using cakePHP to manage customer in web application "Manage motel".
4.1. Create database

- Create customers with fields: 

+ id : INT, AUTO_INCREMENT,  PRIMARYKEY
+ name : NVARCHAR
+ age : INT
+ address: NVARCHAR

- Coding : Open editor and create files with content below and save them with path :

+ customer.php -> C:\AppServ\www\MyCake\app\models\
<?php
class Customer extends AppModel
{
var $name = 'Customer';
}
?>
+ customers_controller.php -> C:\AppServ\www\MyCake\app\controllers
<?php
class CustomersController extends AppController
{
var $name = 'Customers';
function index()
{
$this->set('customers', $this->Customer->findAll());
}
}
?>
+ index.thtml -> C:\AppServ\www\MyCake\app\views\customers\ (create customers folder in /app/views)
<h1>Customer Manager</h1>
<table>
<tr>
<th>Id</th><th>Name</th><th>Age</th><th>Address</th>
</tr>
<?php foreach ($customers as $cust): ?>
<tr>
<td><?php echo $cust['Customer']['id']; ?></td>
<td>
<?php echo $html->link($cust['Customer']['name'], '/customers/view/'.$cust['Customer']['id']);?>
<?php echo $html->link(
'Delete',
"/customers/delete/{$cust['Customer']['id']}",
null,
'Are you sure?'
)?>
<?php echo $html->link('Edit', '/customers/edit/'.$cust['Customer']['id']);?>
</td>
</td>
<td><?php echo $cust['Customer']['age']; ?></td>
<td><?php echo $cust['Customer']['address']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<p><?php echo $html->link("Add Customer", "/customers/add"); ?>
After complete 3 page, we are going to test . Open web browser and type :  http://localhost/MyCake/customers  you will see result. So, you created a first simple application about using cakePHP to create a web application. Next, i will explain the Operating model of cakePHP, how to create a page and how to use variable, function ...

4.2. Operating model

As i have introduced, cakePHP is a framework, so it's operating model is similar 3 classes model (MVC) in object-oriented programming. With first class is view, next is controller class and last is model class. Model class will communicate with our database.

4.4. Model

In the example shown you customer.php file with writing code as above, cakePHP will understand that we want to create a model named Customer for use in our CustomersController. The variable $name is indicated to prevent our model coincides with the name of the function of php. And the Customer class will inherit the attributes and methods of AppModel classTo be able to understand the details of the model and using the properties and functions of the model you can refer:

4.5. Controller

Controller is used to manage the communication with the database, set the desired requirements to express our view on the handler for example by adding, deleting, editing and displays, ... , is where all the activities of its management model would be. In the example above (customers_controller.php), cakePHP understand the code above is that we will create a CustomersController used to manage the use and operation of CustomerModel. Similarly, CustomersController class will inherit from AppController class. Function index() will be processed when we call index.thtml page. Including methods set() is used to assign values to an array is returned from the method FindAll() at the Customer model. In the above example, the variable $customers table will bring an array of customer value is obtained from the Customers table from the database. To view details about the controller you can refer to: 

4.6. View

View the data which has been shown by our treatment. A view is seen as a template page. We can get data from the respective model. The data is transmitted via an array $ data. In the example above, is a view index.thtml. Sequel I will talk to detail view through the example above. Next we learn to the properties and methods in index.thtml:
<? php foreach ($customers table as $cust):?>
The $customers is that we have established with the method set() in the CustomersController example. It carries an array value as I said. $html is an object of class helpers will be discussed in the next section. Method link() is used to output an link similar href in HTML with the first parameter is the title to the links, the 2nd parameter is the url.

4.7. Complete all features of module "Manage motel"

I will add the functionality to add, edit, delete, show in our view. I add in customers_controller functions as follows:
<?php
class CustomersController extends AppController{
 var $name = 'Customers';
 function index(){
  $this->set('customers', $this->Customer->findAll());
 }
 function view($id){
  $this->Customer->id = $id;
  $this->set('customers', $this->Customer->read());
 }
 function add(){
  if (!empty($this->data)){
   if ($this->Customer->save($this->data)){
    $this->flash('Your customer has been saved.','/customers');
   }
  }
 }
 function delete($id){
  $this->Customer->del($id);
  $this->flash('The customer with id: '.$id.' has been deleted.', '/customers');
 }
 function edit($id = null){
  if (empty($this->data)){
   $this->Customer->id = $id;
   $this->data = $this->Customer->read();
  }
  else{
   if ($this->Customer->save($this->data['Customer'])){
    $this->flash('Your customer has been updated.','/customers');
   }
  }
 }
}
?>
Thus we have added 4 function in our CustomersController. The function will be called in the view. For example, we clicked the link on  Add Customer,  the function will be performed and shown in our view. You create add.thtml file with the following content:
<h1>Add Customer</h1>
<form method="post" action="<?php echo $html->url('/customers/add')?>">
 <p>
  Name:
  <?php echo $html->input('Customer/name', array('size' => '40'))?>
  <?php echo $html->tagErrorMsg('Customer/name', 'Name is required.') ?>
 </p>
 <p>
  Age:
  <?php echo $html->input('Customer/age', array('size' => '40'))?>
  <?php echo $html->tagErrorMsg('Customer/age', 'Age is required.') ?>
 </p>
 <p>
  Address:
  <?php echo $html->input('Customer/address', array('size' => '40'))?>
  <?php echo $html->tagErrorMsg('Customer/address', 'Address is required.') ?>
 </p>
 <p>
  <?php echo $html->submit('Save') ?>
 </p>
</form>
In "add" view line: 
<?php echo $html->input('Customer/name', array('size' => '40'))?>
will output a text input tag. With the command line above,  cakePHP will understand that we will use  "name" field in Customer model. The second parameter is attributes of the input tags in HTML. Similar to submit tags, TagErrorMsg() function will show the error messages in case of our data entry error. The error handling will be discussed in the following section. Similarly we create files edit.thtml, view.thtml as follows:

+ edit.thtml
<h3>Edit Your Customer</h3>
<form method="post" action="<?php echo $html->url('/customers/edit')?>">
 <?php echo $html->hidden('Customer/id'); ?>
 <p>
  Name:
  <?php echo $html->input('Customer/name', array('size' => '40'))?>
  <?php echo $html->tagErrorMsg('Customer/name', 'Name is required.') ?>
 </p>
 <p>
  Age:
  <?php echo $html->input('Customer/age', array('size' => '40'))?>
  <?php echo $html->tagErrorMsg('Customer/age', 'Age is required.') ?>
 </p>
 <p>
  Address:
  <?php echo $html->input('Customer/address', array('size' => '40'))?>
  <?php echo $html->tagErrorMsg('Customer/address', 'Address is required.') ?>
 </p>
 <p>
  <?php echo $html->submit('Save') ?>
 </p>
</form>
+ view.thtml
<h3>Your Customer</h3>
<h1>Name :<?php echo $customers['Customer']['name']?></h1>
<h1>Age :<?php echo $customers['Customer']['age']?></h1>
<h1>Address:<?php echo $customers['Customer']['address']?></h1>
Good luck!