Archive for August 2011

create table in php with mysql

connection.inc.php :

<?php
$host='localhost';
$user_name='root';
$password='';
@$con = mysql_connect("$host","$user_name","$password");
if ($con)
 {echo '<br>host coonected<br>';}
else
  {
  die('Could not connect ');
  }
?>

creation_table.php :
<?php

require 'connection.inc.php';

if (mysql_select_db('test'))
echo '<br>database selected<br>';
if(mysql_query("create table test(sno varchar(3),name varchar(15))",$con))
  {
  echo "<br>table created<br>";
  }
else
  {
  echo '<br><br>table not created :'.mysql_error();
  }

mysql_close($con);
?>

run " creation_table.php"

output :

host coonected

database selected


table created

Upload the image to server

class UPLOAD
{
var $directory_name;
var $max_filesize;
var $error;
var $file_name;
var $full_name;
var $file_size;
var $file_type;
var $check_file_type;
var $thumb_name;
var $tmp_name;

function set_directory($dir_name = ".")
{
$this->directory_name = $dir_name;
}

function set_max_size($max_file = 3000000)
{
$this->max_filesize = $max_file;
}

function check_for_directory()
{
if (!file_exists($this->directory_name))
{
mkdir($this->directory_name,0777);
}
@chmod($this->directory_name,0777);
}

function error()
{
return $this->error;
}

function set_file_size($file_size)
{
$this->file_size = $file_size;
}

function set_file_type($file_type)
{
$this->file_type = $file_type;
}

function get_file_type()
{
return $this->file_type;
}

function set_temp_name($temp_name)
{
$this->tmp_name = $temp_name;
}

function set_file_name($file)
{
$this->file_name = $file;
$this->full_name = $this->directory_name."/".$file;
}
/*
* @PARAMS :
* $uploaddir : Directory Name in which uploaded file is placed
* $name : file input type field name
* $rename : you may pass string or boolean
* true : rename the file if it already exists and returns the renamed file name.
* String : rename the file to given string.
* $replace =true : replace the file if it is already existing
* $file_max_size : file size in bytes. 0 for default
* $check_type : checks file type exp ."(jpg|gif|jpeg)"
*
* Example UPLOAD::upload_file("temp","file",true,true,0,"jpg|jpeg|bmp|gif")
*
* return : On success it will return file name else return (boolean)false
*/

function upload_file($uploaddir,$name,$rename=true,$replace=false,$file_max_size=0,$check_type="")
{
$this->set_file_type($_FILES[$name]['type']);
$this->set_file_size($_FILES[$name]['size']);
$this->error=$_FILES[$name]['error'];
$this->set_temp_name($_FILES[$name]['tmp_name']);
$this->set_max_size($file_max_size);

$this->set_directory($uploaddir);
$this->check_for_directory();
$this->set_file_name(str_replace(' ','_',$_FILES[$name]['name']));

if(!is_uploaded_file($this->tmp_name))
$this->error = "File ".$this->tmp_name." is not uploaded correctly.";

if(empty($this->file_name))
$this->error = "File is not uploaded correctly.";
if($this->error!="")
return false;


if(!empty($check_type))
{
if(!eregi("\.($check_type)$",$this->file_name))
{
$this->error="File type error : Not a valid file";
return false;
}
}
if(!is_bool($rename)&&!empty($rename))
{
if(preg_match("/\..*+$/",$this->file_name,$matches))
$this->set_file_name($rename.$matches[0]);
}
elseif($rename && file_exists($this->full_name))
{
if(preg_match("/\..*+$/",$this->file_name,$matches))
$this->set_file_name(substr_replace($this->file_name,"_".rand(0, rand(0,99)),-strlen($matches[0]),0));
}
if(file_exists($this->full_name))
{
if($replace)
@unlink($this->full_name);
else
{
$this->error="File error : File already exists";
return false;
}
}


$this->start_upload();
if($this->error!="")
return false;
else
return $this->file_name;
}

function start_upload()
{
if(!isset($this->file_name))
$this->error = "You must define filename!";

if ($this->file_size <= 0)
$this->error = "File size error (0): $this->file_size Bytes
";

if ($this->file_size > $this->max_filesize && $this->max_filesize!=0)
$this->error = "File size error (1): $this->file_size Bytes
";

if ($this->error=="")
{
$destination=$this->full_name;
if (!@move_uploaded_file ($this->tmp_name,$destination))
$this->error = "Impossible to copy ".$this->file_name." from $userfile to destination directory.";
}
}

}

For getting the files and folders in a directory

This is a useful function for getting all subdirectories and files in an array.

$site_files = directoryToArray("path to directory",TRUE);

function directoryToArray($directory, $recursive) {
        $array_items = array();
        if ($handle = opendir($directory)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    if (is_dir($directory. "/" . $file)) {
                        if($recursive) {
                            $array_items = array_merge($array_items,directoryToArray($directory. "/" . $file, $recursive));
                        }
                        $file = $directory . "/" . $file;
                        $array_items[] = preg_replace("/\/\//si", "/", $file);
                    } else {
                        $file = $directory . "/" . $file;
                        $array_items[] = preg_replace("/\/\//si", "/", $file);
                    }
                }
            }
            closedir($handle);
        }
        return $array_items;
    }

user model
username}'";

$db = $this->_open_connection();

$find_user = mysql_query($select,$db);
$data_user = mysql_num_rows($find_user);

if($data_user == 0)
{

$sql = "INSERT INTO user(username,password) VALUES('{$model_user->username}','{$model_user->password}')";
$result = mysql_query($sql,$db);
return $result;
return true;

}
else
return false;
}

//LOGIN
public function user_select($model_user)
{
$select = "SELECT id FROM user WHERE username = '{$model_user->username}' AND password = '{$model_user->password}'";

$db = $this->_open_connection();

$find_user = mysql_query($select,$db);
$data_user = mysql_num_rows($find_user);
$data = mysql_fetch_array($find_user);

if($data_user == 1)
{

$_SESSION['uid'] = $data['id'];
return true;
}

else
return false;
}

//GET USER_id
public function userID($model_user)
{
$select = "SELECT id FROM user WHERE username = '{$model_user->username}'";

$db = $this->_open_connection();

$find_user = mysql_query($select,$db);
$data = mysql_fetch_array($find_user);

return $data['id'];
}

//UPDATE PROFILE
public function editProfile($model_user)
{

$sql = "UPDATE user SET name='{$model_user->name}',email='{$model_user->email}',password='{$model_user->password}',sex='{$model_user->sex}'
,city='{$model_user->city}',country='{$model_user->country}',contact='{$model_user->contact}',aboutme='{$model_user->aboutme}'
WHERE id = '{$model_user->id}'";
$db=$this->_open_connection();
$result=mysql_query($sql,$db);

$_SESSION['upload_msg'] = '';
$_SESSION['saveprofile_msg'] = "profile succesfully save";
header('Location: user.php?view=edit-profile');
}

//UPLOAD PROFILE PICTURE
public function profilepic($model_user)
{
$target_path = $_SERVER['DOCUMENT_ROOT'].'/mvc2/upload/';

$target_path = $target_path . basename( $_FILES['file']['name']);

$picname = $_FILES["file"]["name"];

if($_FILES["file"]["type"] == "image/jpeg"){
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {

$_SESSION['upload_msg'] = "The file ". basename( $_FILES['file']['name']).
" has been uploaded";


$sql = "UPDATE user SET profilepic='{$picname}' WHERE id = '{$model_user->id}'";
$db=$this->_open_connection();
$result=mysql_query($sql,$db);


header('Location: user.php?view=edit-profile');
}
}
else{
$_SESSION['upload_msg'] = "There was an error uploading the file, please try again!";
header('Location: user.php?view=edit-profile');
}

}


//DISPLAY USER DATA
public function user_data($id)
{
$sql="SELECT * FROM user WHERE id='{$id}'";
$db=$this->_open_connection();
$result=mysql_query($sql,$db);
$row=mysql_fetch_array($result);
$data=array('profilepic'=>$row['profilepic'],
'name'=>$row['name'],
'email'=>$row['email'],
'password'=>$row['password'],
'sex'=>$row['sex'],
'city'=>$row['city'],
'country'=>$row['country'],
'contact'=>$row['contact'],
'aboutme'=>$row['aboutme'],);

return $data;
}

//ALL USER DATA DISPLAY
public function all_user()
{
$sql="SELECT * FROM user";
$db=$this->_open_connection();
$result=mysql_query($sql,$db);
while($row=mysql_fetch_array($result))
{
$data=array('profilepic'=>$row['profilepic'],
'name'=>$row['name'],
'email'=>$row['email'],
'password'=>$row['password'],
'sex'=>$row['sex'],
'city'=>$row['city'],
'country'=>$row['country'],
'contact'=>$row['contact'],
'aboutme'=>$row['aboutme'],);

if( $row['id'] != $_SESSION['uid']){
echo "";
echo $row['username']."

"; }
}
return $data;
}

//ADD COMMENT
public function addComments($model_user)
{
if(!empty($model_user->comment))
{
$sql = "INSERT INTO commnets(comments,my_id,post_id) VALUES('{$model_user->comment}','{$model_user->myid}','{$model_user->postid}' )";
$db=$this->_open_connection();
$result = mysql_query($sql,$db);
return true;;
}
else
return false;
}

//DATABASE CONNECTION
private function _open_connection(){
$con=mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if(!$con)
die('Error Connection:'.mysql_error());
$db_select=mysql_select_db(DB_NAME,$con);
if(!$db_select)
die('Error Selection'.mysql_error());
return $con;
}
}
?>

CONTROLLER
username = $_POST['username'];
$model_user->password = $_POST['password'];

return $model_user->user_registration($model_user);
}

//login
public function user_login()
{
require_once($_SERVER['DOCUMENT_ROOT'].'/mvc2/application/model/user_model.php');

$model_user = new user_model();
$model_user->username = $_POST['username'];
$model_user->password = $_POST['password'];

return $model_user->user_select($model_user);

}

//get userID
public function userID()
{
require_once($_SERVER['DOCUMENT_ROOT'].'/mvc2/application/model/user_model.php');

$model_user = new user_model();
$model_user->username = $_POST['username'];
$model_user->password = $_POST['password'];

return $model_user->userID($model_user);
}

//profile edit
public function profileEdit()
{

require_once($_SERVER['DOCUMENT_ROOT'].'/mvc2/application/model/user_model.php');

$model_user = new user_model();
$model_user->id = $_POST['id'];
$model_user->name = $_POST['name'];
$model_user->email = $_POST['email'];
$model_user->password = $_POST['password'];
$model_user->name = $_POST['name'];
$model_user->sex = $_POST['sex'];
$model_user->city = $_POST['city'];
$model_user->country = $_POST['country'];
$model_user->contact = $_POST['contact'];
$model_user->aboutme = $_POST['aboutme'];

return $model_user->editProfile($model_user);
}

//upload pic
public function uploadProfilePic()
{
require_once($_SERVER['DOCUMENT_ROOT'].'/mvc2/application/model/user_model.php');

$model_user = new user_model();

$model_user->file = $_POST['file'];
$model_user->id = $_POST['id'];

return $model_user->profilepic($model_user);

}

//add comment
public function addComment()
{
require_once($_SERVER['DOCUMENT_ROOT'].'/mvc2/application/model/user_model.php');

$model_user = new user_model();

$model_user->comment = $_POST['comment'];
$model_user->myid = $_POST['myid'];
$model_user->postid = $_SESSION['postid'];


return $model_user->addComments($model_user);
}

//menu
public function menus()
{
echo "My PROFILE ";
echo "REGISTERED USERS ";
echo "LOG OUT ";
}


}



$user = new user();

//view ********************************

if(!empty($_GET['view']))
{
$view = $_GET['view'];
{
switch($view)
{
case 'user-signup':
$page = $user->pageIndex();
break;

case 'user-profile':
$page = $user->profilePage();
break;

case 'edit-profile':
$page = $user->profileViewEdit();
break;

case 'all-user':
$page = $user->AllUserProfile();
break;

case 'visit-profile':
$page = $user->visitProfile();
break;
}
include($_SERVER['DOCUMENT_ROOT'].'/mvc2/application/view/'.$page.'.php');
}
}

//model *******************************************
if(!empty ($_GET[model]))
$model = $_GET['model'];
{
switch($model)
{

//REGISTRATION
case 'user-register':
$result = $user->user_registration();
if($result)
{
$_SESSION['reg_message'] = 'Success register';
}
else
{
$_SESSION['reg_message'] = 'username already exist';
}
$_SESSION['login_message'] = '';
header('Location:user.php?view=user-signup');
break;

//LOG-IN
case 'user-log':
$page = $user->profilePage();
$result = $user->user_login();
if($result)
{
$id = $user->userID();
header('Location:user.php?view=user-profile&id='.$id);
}
else
{
$_SESSION['login_message'] = 'worng username or password, please try again';
header('Location:user.php?view=user-signup');
}
$_SESSION['reg_message'] = '';
break;

//PROFILE EDIT
case 'profile-edit':
$user->profileEdit();

break;

//UPLOAD PICTURE
case 'upload-pic';
$user->uploadProfilePic();
break;
//ADD COMMENT
case 'add-comment';
$user->addComment();
break;
}
}
?>

Register Globals

PHP automatically creates global variables containing data from a variety of external sources EGPCS (Environment, GET, POST, Cookie, Server).register_globals setting in PHP's configuration file (php.ini)(which can be either On or Off) tells whether or not to register the contents of the EGPCS variables as global variables.

Example 1:
To start a session use session_start() and to register a variable in this session use the $_SESSION array.

<?php
session_start();
$_SESSION['my_var'] = 'Hello World';
?>
If register_globals is enabled then your session variables will be available as normal variables on subsequent pages.
<?php
session_start();
echo $my_var;
?>
And If register_globals is enabled, then it will only be in the $_SESSION array.
<?php
session_start();
echo $_SESSION['my_var'];
?>


Example 2:

If register_globals is on, the url http://www.testdomain.com/test.php?id=3 will declare $id as a global variable with no code required.


Note : This feature is a great security risk, and you should ensure that register_globals is Off for all scripts (as of PHP 4.2.0 this is the default).

Assignment #8 Final Project

0) Shopping Cart module is cancelled.
The filenames that are related to the shopping cart are deleted, but their names are recorded in the excel file.

Updated: (To avoid SQL injection attack)
1) adminVal.php --> is updated to avoid "SQL injection attack."

Upload image feature added.
2) item.php (Updated) --> Added a link for "uploading image is added." User must log in as an administrator in order to upload a new image.

3)UploadForm.php --> Accepts ID number of image via get, passes file and ID to uploadImage.php To let user to pick up the image file to upload.

4) UploadImage.php--> To execute the uploading actions. This file is not visible to user. Retrieves image info from uploadForm.php, uploads image over old version of file

Paging Feature is added.
5) Template class: class.recnav.php, class.recnav2.php. are as parent class to extend child classes: RecNav#.php

6)RecNav1.php, RecNav2.php --> extend from class.recnav.php.

7)RecNav3.php --> Extends: class.recnav2.php. RecNav3 uses an updated version of the class, "class.recnav2.php", which allows the developer to pass a category from page to page.

global variable in php

<?php

$num1=10;
$num2=5;

function add()
{
  global $num1,$num2;
  return $num1+$num2;
}

function sub($num1,$num2)
{
  return $num1-$num2;
}

echo 'addition  with out global variables : '. add().'<br>';

echo 'subtraction with global variables : '.sub($num1,$num2);

?>output :

addition with out global variables : 15
subtraction with global variables : 5

Display local country time, instent of displaying server time using SafGetLocalTime

<?
//Display local country time, instent of displaying server time,
//If you country is Sri Lanka and web server in in USA, you can use the following script to solve your problem
//$datetime variable shuld contain the date time like date('Y-m-d H:i:s')
//$diferent variable is the diferent between server and your local country like +5.5 -6
//$mylenth from the final out put you can tell to the function how many character from $myafter sould display
//better to keep $myafter=0 and $mylenth=0 as it is

function SafGetLocalTime($datetime,$myafter=0,$mylenth=0,$diferent){ //get local time pass datetime and diferent
list($year,$month,$day,$hour,$minute,$second) = explode("-",str_replace(array(" ",":"),"-",$datetime));
$hour = ($hour+$diferent);
$datetime = mktime($hour,$minute,$second,$month,$day,$year);

if (
$mylenth==0) {
$datetime = date('Y-m-d H:i:s',$datetime);
}else{
$datetime = date('Y-m-d H:i:s',$datetime);
$datetime = substr($datetime,$myafter,$mylenth);
}
return
$datetime;
}
?>

REST Architecture with PHP

ROA( Resource Oriented Architecture talks about a set of guidelines of implementation of a REST architecture.REST stands for Representational state transfer.REST architectures can be easily implemented in PHP and has wide popularity among the PHP community since it is based on CURD(CREATE, READ, UPDATE, DELETE) model.here are key REST principle mentioned below.

  • Give every “thing” an ID
  • Link things together
  • Use standard methods
  • Resources with multiple representations
  • Communicate statelessly

for more information on REST click here

PHP to MySQL Date Format

Default MySQL DATE Column is in '2012-07-18 10:20:32'  format

We must be using some input box or calender script in Webpages to enter a date .
If the Date inserted is not in Format of MySQL it wont get saved to DB.
So when we insert a Date Value from PHP into a database column we need to format according to MySQL.

For this we can use MySQL STR_TO_DATE().
Syntax: STR_TO_DATE(Str,format);
Str is the DATE string  and Format is the format of Str.
Please remember this function always return a DATE in 'YY-MM-DD' format.

eg:
SELECT STR_TO_DATE('18-7-2012','%d-%m-%Y')
prints : 2012-07-18
we mention is the second argument the format in which we pass the Str which has a date.
if we pass the Str in '2012/07/18' (ie YY/MM?DD)
SELECT STR_TO_DATE(' 2012/07/18 ','%Y / %d / %m')
prints : 2012-07-18

How to enable showing queries in Code Igniter profiling?


Hello Web,

Its been now a while using CodeIgniter (PHP Framework), but i have been keep finding new stuff when face some dramatic problem. I have to enable a profiling in one my work and come accross a problem that profiling not showing any queries even database is selected.
To solve this problem goto system/database/DB_driver.php look for :



var $save_queries= FALSE;

Set save_queries variable from FLASE -> TRUE so your new settings will be:

var $save_queries= TRUE; 



It will now show a queries into profiling.
Enjoy Googling.
:D




:D

Vertrigo server installation

Before installing Vertrigo server we try to know something about Vertrigo web server. Vertrigo is a software system that provides PHP environment with one step installation. This integrated software provides Apache, PHP, MySQL and PhpMyAdmin in integrated way. If you install vertrigo web server in your computer then it will creates PHP environment in your computer as a local server. So let's try to install vertrigo web server with us. 

Vertrigo Server Installation Procedure:

Step 1:
First of all download the latest version of vertrigo web server from this link Download Vertrigo . To download the latest version click on GET THE LATEST VERSION.

Step 2: 
After download, double click on that file and then click next, then click on I agree. Then select the destination folder such that I select D folder like the picture.

Step 3:  
Install the software by clicking next. Your work is done. You will see a Vertrigo server icon in your desktop. Double click on this icon and the server will run in your computer.




Like the above picture you can shutdown or start, stop Vertrigo server. PHP environment creation is done now it is time to write your first PHP code.

Enable Windows Authentication in a PHP website

Hosting your PHP site in IIS server is easy way to enable Windows Authentication.

Let's see How to install PHP 5.3 on IIS 7
I downloaded PHP for windows from http://windows.php.net/download/

Run the exe and start installation.























Then click next and accept the terms and conditions go next.

Then select IIS FastCGI option.






















Select features and extensions you want.

There is an another tool called PHP manager.If u install it you can easily change PHP configuration.
I download that software from http://phpmanager.codeplex.com/

After installing it appears in IIS.You can change configurations such as php.ini configurations enable disable extensions etc.






























Now go to authentication window by clicking authentication icon.












Then you can see authentication types. Right click on Windows Authentication and click Enable.

Now you can use server variables to get logged user name.
$userId=$_SERVER['REMOTE_USER'];
It will return YOUR_DOMAIN\USERNAME


Tipo de datos Booleanos en Php

Este es el tipo más simple. Un boolean expresa un valor de verdad. Puede ser TRUE or FALSE.
nota: El tipo booleano fue introducido en PHP 4.

Sintaxis:
Para especificar un literal booleano, use alguna de las palabras clave TRUE o FALSE. Ambas son insensibles a mayúsculas y minúsculas.

<?php
$foo = True; // asignar el valor TRUE a $foo
?>

Usualmente se usa algún tipo de operador que deuelve un valor boolean, y luego éste es pasado a una estructura de control.

<?php
// == es un operador que prueba por
// igualdad y devuelve un booleano
if ($accion == "mostrar_version") {
echo "La versión es 1.23";
}

// esto no es necesario...
if ($mostrar_separadores == TRUE) {
echo "<hr>\n";
}

// ...porque se puede escribir simplemente
if ($mostrar_separadores) {
echo "<hr>\n";
}
?>

Conversión a booleano

Para convertir explícitamente un valor a boolean, use el moldeamiento (bool) o (boolean). Sin embargo, en la mayoría de casos no es necesario usar el moldeamiento, ya que un valor será convertido automáticamente si un operador, función o estructura de control requiere un argumento tipo boolean.

Cuando se realizan conversiones a boolean, los siguientes valores son considerados FALSE:

• el boolean FALSE mismo
• el integer 0 (cero)
• el float 0.0 (cero)
• el valor string vacío, y el string "0"
• un array con cero elementos
• un object con cero variables miembro (sólo en PHP 4)
• el tipo especial NULL (incluyendo variables no definidas)
• objetos SimpleXML creados desde etiquetas vacías

Cualquier otro valor es considerado TRUE (incluyendo cualquier resource).

aviso : ¡-1 es considerado TRUE, como cualquier otro número diferente a cero (ya sea negativo o positivo)!

<?php
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
?>

What is PHP?

PHP is a popular programming language for extending web pages with dynamic features. It is using small and big company, big project or very small project. It has wide-range usability. Youtube, Facebook and Joomla is written with PHP.

Php is powerfull and free. So, Everyone can use it for commercial. You can run your PHP script most of OS. Mac, Windows or Unix. You must just configure your server for PHP.

Php can be use with MySQL, MSSQL or other database. You can create your own dynamic web site in short time.

Here is simple PHP example;

<?php
/**
*
@author PCoder
*
@copyright 2009
* Php Hello World
*/

echo("Hello World "); /* Result: Hello World */
Print("Hello World "); /* Result: Hello World */

/* Define a var for Hello World */

$var = "Hello World ";
echo $var; /* You can use this : echo($var); */
print $var; /* You can use this : print($var); */
?>

Introduction

This is a step-by-step tutorial to build a multithreaded daemon in PHP. I will point out several problems caused by a greedy implementation and will give some ways to solve them. I will also have a look at which functions are provided by PHP, what are their advantages and their drawbacks, and how to use them. I will finally give a working implementation of a class that would expose every functions needed to run such a daemon. The implementation will be written in PHP5.

Below are the steps of this tutorial :

  1. Introduction (this part)
  2. Why to use a daemon ?
  3. What is provided by PHP to handle multithreading ?
  4. Roots of a conceptual implementation
  5. The basic implementation of the multithreading class
  6. Limitations of the basic implementation and future work.