Archive for February 2013

For removing content of a directory - subdirectory - files in php

For removing content of a directory - subdirectory - files in php
$site_files = $this->directoryToArray($site_path, TRUE);

foreach($site_files as $val){

          unlink($val);

}

$site_files = $this->directoryToArray($site_path, TRUE);

krsort($site_files);

foreach($site_files as $val){

                 rmdir("$val");

}

 rmdir("$site_path");

----------------------------------------------------------------------------------




function directoryToArray($directory, $recursive) {

                $array_items = array();

                if ($handle = opendir($directory)) {

                              while (false !== ($file = readdir($handle))) {

                                       if ($file != "." && $file != "..") {

                                              if (is_dir($directory . "/" . $file)) {

                                                      $file1 = $directory . "/" . $file;

                                                      $array_items[] = preg_replace("/\/\//", "/", $file1);

                                                      if ($recursive) {

                                                                     $array_items = array_merge($array_items, $this->directoryToArray($directory . "/" . $file, $recursive));

                                                    }

                                            } else {

                                                $file = $directory . "/" . $file;

                                                $array_items[] = preg_replace("/\/\//", "/", $file);

                                      }

                             }

                 }

         closedir($handle);

     }

     return $array_items;

}

File Upload if File Exists Append Number to File Name with Increment

<?php
error_reporting(0);
$fileName=$_FILES['fileImage']['name'];
$file=$_FILES['fileImage']['tmp_name'];
$path='image/'.$_FILES['fileImage']['name'];
$extension=fileGetEXT($fileName);

function fileGetEXT($fName)
{
$fileName=$fName;
$start=strpos($fileName,".");
$getEXT=substr($fileName,$start+1,4);
return($getEXT);
}
function createUniqueFile($fName)
{
$fileName=$fName;
$start=strpos($fileName,".");
$name=substr($fileName,0,$start);
$getEXT=fileGetEXT($fileName);
$counter = 1;
while(file_exists($newFileName=strip_tags('image/'.$name.'~'.$counter.'.'.$getEXT)))
{
$counter++;
}
return $newFileName;
}

$validEXT=array("jpg","jpeg","gif","bmp","png");

if(isset($_POST['submit']) && ($_POST['submit']=="Submit"))
{
if(in_array($extension,$validEXT))
{
if(file_exists($path))
{
$newFile=createUniqueFile($fileName);
$path1=strip_tags($newFile);
move_uploaded_file($file,$path1);
echo ucfirst($extension)." Valid Extension";
}
else
{
move_uploaded_file($file,$path);
echo ucfirst($extension)." Valid Extension";
}
}
else
{
echo ucfirst($extension)." Invalid Extension";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File Uploading</title>
</head>
<body>
<form name="uploadFrm" method="post" action="" target="" id="" enctype="multipart/form-data">
<table align="center" style="border:#666666 solid 1px; margin-top:20px;">
<tr>
<td>First Name:</td>
<td><input type="text" name="txtfirstName" value="" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="txtLastNAme" value="" /></td>
</tr>
<tr>
<td>Image:</td>
<td><input type="file" name="fileImage" value="" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>

PHP Operator Types


What is Operator?Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
  • Arithmetic Operators
  • Comparision Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators:
There are following arithmetic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/
Divide numerator by denumerator
B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++
Increment operator, increases integer value by one
A++ will give 11
--
Decrement operator, decreases integer value by one
A-- will give 9
Comparison Operators:
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
and
Called Logical AND operator. If both the operands are true then then condition becomes true.
(A and B) is true.
or
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
(A or B) is true.
&&
Called Logical AND operator. If both the operands are non zero then then condition becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false.
Assignment Operators:
There are following assignment operators supported by PHP language:
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assigne value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax:
Operator
Description
Example
? :
Conditional Expression
If Condition is true ? Then value X : Otherwise value Y
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
  • Unary prefix operators, which precede a single operand.
  • Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
  • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
  • Assignment operators, which assign a value to a variable.
Precedence of PHP Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category 
Operator 
Associativity 
Unary 
! ++ -- 
Right to left 
Multiplicative  
* / % 
Left to right 
Additive  
+ - 
Left to right 
Relational  
< <= > >= 
Left to right 
Equality  
== != 
Left to right 
Logical AND 
&& 
Left to right 
Logical OR 
|| 
Left to right 
Conditional 
?: 
Right to left 
Assignment 
= += -= *= /= %=
Right to left 

VBA writing in a text file

This code reads from a sheet until a blank cell is found and writes in a text file the results.

Sub writetextfile()

Set fs = CreateObject("Scripting.FileSystemObject")

Set a = fs.CreateTextFile("file.txt", True)

j = 2

While Sheets("sheets 1").Cells(j, 1) <> ""

You can use Range("A1") instead of Cells(1,1) pointing to cell A1 for example.
       a.WriteLine ("" & Sheets("sheets 1").Range("A" & j) & "")
       j = j + 1
Wend

a.Close

End Sub

PHP installation

We know PHP run on server, that's why at first we need to create PHP environment in our local computer. To do this we need to install PHP and a web server. So we say that to create PHP environment we need two things 
  1. PHP (Apache)
  2. Web Server  
At first we install PHP (Apache) and then we install web server. This installation process is very complex. Now a days there are various types of software provides integrated capability, that means we need to install only one software to create PHP environment. Some software are XAMPP, WAMPP, Vertrigo etc.  

In our tutorial we will show you how to install XAMPP and Vertrigo in your local computer. I like vertrigo web server and though in our whole tutorial I will use Vertrigo web sever but you can use XAMPP server. XAMPP server is very useful and popular web server for the PHP developers. So guys install one software among them ( ZAMPP or Vertrigo). If you already installed PHP environment just skip this installation process.

XAMPP INSTALLATION

Installing CPAN modules in perl in linux.

Perl support lots of in built module available under CPAN [Comprehensive Perl Archive Network] which can be install by the following command.

uttam@uttam:/ sudo perl -MCPAN -e shell

after this command you'ill be under cpan shell and you'll see the following text on screen..

cpan shell -- CPAN exploration and modules installation (v1.9205)
ReadLine support available (maybe install Bundle::CPAN or Bundle::CPANxxl?)

cpan[1]>

Now you can install module you want with perl.for example you can type "install DBI" to install DBI modules.

After successful installation you can view the DBI directory under following folder.
/usr/local/lib/perl/5.10.0/.

PHP File Inclusion



You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.
  • The include() Function
  • The require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.
The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
Assume you want to create a common menu for your website. Then create a file menu.php with the following content.
<a href="http://www.tutorialspoint.com/index.htm">Home</a> -
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> -
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />
Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
This will produce following result
This is an example to show how to include PHP file. You can include mean.php file in as many as files you like!
The require() Function
The require () function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.
<html>
<body>
<? Php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This will produce following result
This is an example to show how to include wrong PHP file!
Now lets try same example with require() function.
<html>
<body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This time file execution halts and nothing is displayed.
NOTE: You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.

Subhajit Das | PHP Developer | PHP Programmer

SUBHAJIT DAS
Vill. & P.O. – Debagram, Distt. - Nadia, West Bengal, Pin - 741137
Contact: +91-9434185745, 3474266095 (Res.); Email: 2005.subhajit@gmail.com


PHP PROGRAMMER
Offering 1.5 years extensive experience in web development and project development

 Technically and professionally competent; with 1.5 years of extensive experience in Web Development & Maintenance of sites, with an indomitable urge to learn and apply.
 Abreast with the latest trends and developments of the field with thorough knowledge of various computer applications and programming language. Knowledge of functional areas with expertise in Project Management Life Cycle for various platforms including Project Scoping, Requirement Analysis & Technical Specifications, Effort Estimates, Risk Management, Planning, Monitoring & Tracking, Reporting & Communication Management, Process Compliance & Management, Change Management and Resource Optimization.
 Working as PHP Programmer and Web Developer, on a wide array of PHP, JavaScript and MySql.
 Keen sense of the Online Media, matured outlook on coverage, analysis and robustness of writing with an intuitive talent for connecting with the target audience.

Core Competencies

Planning ~ Requirement Analysis & Technical Specifications ~ Cross-functional Coordination ~ Resource Optimization ~ Process & Performance Management


TECHNICAL SKILLS

Operating System Windows 98/XP, Linux
Database Technologies My SQL
Programming Languages C, PHP, Javascript, MySql
Documentation/Design Tools PHP Documentation
PHP Open source Wordpress
Other Tools Web Testing, Adobe Photoshop, Adobe Dreamweaver


PROFESSIONAL EXPERIENCE

LEE & NEE SOFTWARE EXPORTS LTD., KOLKATA June 2010 till date
PHP Programmer

 Presently working on PHP & Mysql and coordinating with different teams working on the project.
 Responsible to analyze root cause of failures and evolved breakdown solutions within minimum turnaround time.
 Accountable to identify & analyze client’s requirement by maintaining active & comprehensive conversation.
 Manage guidance on the projects and its requirements to the clients over the technology, processes and applications while updating them on the regular project related developments.
 Ensure clients issues were promptly addressed documented and resolved in a timely and professional manner and passed them to correct channels.

INFO SOFT SOLUTIONS, KOLKATA Nov. 2009 – June 2010
PHP Programmer


 Provide technical leadership for analyzing and resolving service requests viz. developing application and unit, integration and system testing.
 Primarily working on PHP & Mysql.
 Coordinating with different teams working on the project.
 Analyze root cause of failures and evolved breakdown solutions within minimum turnaround time.
 Identify & analyze client’s requirements by maintaining active & comprehensive conversation.
 Manage guidance on the projects and its requirements to the clients over the technology, processes and applications while updating them on the regular project related developments.
 Ensure clients issues were promptly addressed documented and resolved in a timely and professional manner and passed them to correct channels.
 Efficiently manage entire day-to-day activities covering wide functional areas include designing & developing the workflow program, debugging and troubleshooting of the application.
 Drive the efforts across managing project life cycle from user requirements to system analysis & planning, design, development, implementation and deployment.

Projects Accomplished attached as Annexure A.

Esolz Incorporation Oct. 2008 to July 2008
PHP programmer


ACADEMIA

B. Tech., 2008 ● Bankura Unnayani Institute of Engg. (C.S.E.) (West Bengal University of Technology); 7.11 DGPA

Higher Secondary (XII), 2004 ● Debagram.S.A. Vidyapith (W.B.C.H.S.E.); 58.6%

Secondary (X), 2002 ● Debagram.S.A. Vidyapith (W.B.B.S.E.); 68.25%

PROFESSIONAL CERTIFICATION

 Certification in Network Management (Networking) from NETTECH, I.I.T., Kharagpur.

Date of Birth: 4th Nov. 1986
Languages: English, Bengali, Hindi
Hobbies: Listening to music, singing
Permanent Address: Vill. & P.O. – Debagram, Distt. - Nadia, West Bengal, Pin - 741137
References: Available on request














ANNEXURE – A : PROJECTS HANDLED:

Position: Programmer Environment: PHP, MySql

Title/URL: www.jollyconsulting.net
Duration: 1 month
Description: This site is Information site where people will know about Medical information.

Title/URL: www.enjoyjars.com
Duration: 2 months
Description: This is a shopping cart project.

Title/URL: www.annexcollege.co.in
Duration: 6 months
Description: This site is ERP site of annex college. Where management can view, add, delete all information about all students, faculty, library and all employee.

Title/URL: www.ezcruizer.com
Duration: 2 months
Description: This is a shopping cart project.

Title/URL: www.alexanderin2010.com Duration: 15 days
Description: This is a political site of state representative of USA.

Title/URL: www.alexanderin2010.com Duration: 15 days
Description: This is a political site of state representative of USA.

Title/URL: http://www.completefitness.org.uk/index.php Duration: 1.5 months
Description: This is information site of Complete Fitness, the First Company to provide this unique concept, combining personal training sessions and physiotherapy under one roof.

Title/URL: http://www.cashnowsite.biz/ Duration: 15 days
Description: This is an affiliate site with CMS.

Title/URL: http://www.irchemicals.com/ Duration: 15 days
Description: This is information site of I.R. Chemicals.

Title/URL: http://theorigin.in/ Duration: 15 days
Description: This is a job consultancy site.

Assignment #2 Modified.

Base on instructor Bill's email, I modified the web with the following changes.

1) Use Dreamweaver and Fireworks to create a better background for the website.

2) Web-site logo is added on the left-top corner the template pages(chekGalleryTemplate.dwt).

3) contactMe.php 's email links also point Bill's email account.


Edit Assignment #2: Basically meets the requirements.
File edited:
1) headerINC.php, Time spent: 20 mins
Learnt: How the include a file to construct a header.


2) hNavINC.php, Time spent: 15 mins
Learnt: How to include a file to construct a header.


3) navINC.php, Time spent: 20 mins
Learnt: How to include a file to construct a navigation column.


4) footerINC.php, Time spent: 20 mins
Learnt: How to include a file to construct a footer.


5) chekGalleryTemplate.dwt , Time spent: 2 hrs 25 mins
Learnt: To use dreamweaver to handle the static part, include a cuscading style sheet to make simple changes affecting al files that include it.


6) chekgallery.css, Time spent: 1 hr 30 mins
Learnt: To use template, include PHP files, array, and CSS. It is a new version of the CSS which give a better look.

7) const.php, Time spent: 20 mins
Learnt: Modified with a new template. To create a form to send e-mail back to the author, or any other targeted receiver. Also to use template, include PHP files, array, and CSS.

8a) myProfiles.php is update with new links and templates.

8b) artEvents.php, shoppingCart.php, gallery.php, checkOut.php, are created from template.

8c) contactMe.php is modified to include more email addresses.
9) pagedesc.xls is updated with new files created.
10) theSitePlan.doc is edited for newer color frame.

Writing oracle procedure.

You can write a stored procedure in oracle using any editor. I use sql developer by oracle. I am very new to write procedures in oracle. I found it's syntax way different than the syntax of MySql. I am fond fo opensource projects because of the support and simplicity of the solutions it has. Mysql has very simple ways to extacts rows, have lost's of in built funtions to use which makes it simple to use. After writting few oracle procedures I found how easy and simple mysql is compared to oracle in syntax. Anyway, Oracle has it's own advantage, and I like learning new stuff and the way to write oracle procedure. Here are 2 common requirement which I faced while writting a procedure in oracle.

1) situations where you want to limit number of resultset in range (10-20) in oracle. In mysql you have limit caluse where you simply say

limit start, count
in your query and it's done, but in oracle you don't have this clause.

here is how you go about the same.

suppose you have table emp with coulumn id,name,sal.

CREATE OR REPLACE
PROCEDURE GETEMPLISTING(
var_name VARCHAR2,
var_limit_start IN INTEGER,
var_limit_end IN INTEGER,
page_cur out SYS_REFCURSOR)

AS
var_data_query varchar2(4000) default '';
BEGIN
var_data_query := 'select *
from
( select rownum rnum, a.*
from (SELECT id,name,sal FROM emp WHERE name LIKE ''%'||var_name||'%'') a
where rownum <= '|| var_limit_end ||')
where rnum >= '|| var_limit_start ||'';

OPEN page_cur FOR
var_data_query


2) you want same data but based on ids using IN caluse, In Oracle this is how I've acheived the same.

Declare a new data type

create or replace TYPE "MYNUMTABLE" as table of number;


Declare a function num_list

create or replace FUNCTION "NUM_LIST"
( p_str in varchar2,
p_delim in varchar2 default ',')
return myNumTable
as
l_data myNumTable := myNumTable();
l_str long default p_str || p_delim;
l_n number;
begin
loop
exit when l_str is null;
l_data.extend;
l_n := instr( l_str, p_delim );
l_data( l_data.count ) := substr( l_str, 1, l_n-1 );
l_str := substr( l_str, l_n+1 );
end loop;
return l_data;
end;



now write a procedure

CREATE OR REPLACE
PROCEDURE GETEMPLISTING(
var_ids VARCHAR2,
page_cur out SYS_REFCURSOR)

AS
BEIGIN
OPEN page_cur FOR
SELECT id,name,sal FROM emp WHERE id IN(SELECT * FROM THE
( SELECT CAST( num_list(p_users_id) AS myNumTable
)
FROM dual) a
);




now you can call procedure to get the result expected. page_ids parameter has to be id seperated by comma (,) in this case for example parameter could be 1,2,5,7. which in reutrn shuld give records of the respected emplyee 1,2,5,7.


Well that all for the day. Will cover next learning soon.

insert data into 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 ');
  }
?>



insert_table.php :
<?php

require 'connection.inc.php';

if (mysql_select_db('test'))
echo '<br>database selected<br>';
if(mysql_query("insert into test(sno,name)values (2,'human')",$con))
  {
  echo "<br>data inserted<br>";
  }
else
  {
  echo '<br>data not inserted :'.mysql_error().'<br>';
  }

mysql_close($con);
?>

run " insert_table.php "

output :


host coonected

database selected

data inserted

rand() in php

<?php

$random=rand();
$maximum_ramdom_number=getrandmax();
echo 'rendom number :'.$random.'<br>';
echo 'maximum rendom number :'.$maximum_ramdom_number.'<br>';

//   or

echo 'rendom number :'. rand().'<br>';
echo 'maximum rendom number :'.getrandmax();

?>

output :
rendom number :30224
maximum rendom number :32767
rendom number :21769
maximum rendom number :32767

note:

1) for every refresh of the browser the random number is changing . but , the maximum random number is not change

Send Email Using SafSendMailV2

<?
function SafSendMailV2($MYRECIPIENTE_EMAIL,$MYRECIPIENTE_NAME,$MYFROM_NAME,$MYFROM_EMAIL,$MYSUBJECT,$MYBODY,$MYHTML,$REMOTE_ADDR,$PHP_SELF
){
$MYRECIPIENTE_EMAIL = "$MYRECIPIENTE_EMAIL"
;
if (
$MYHTML==true
) {
$MYHEADERS = "From: $MYFROM_NAME <$MYFROM_EMAIL>\r\n"
;
$MYHEADERS .= "MIME-Version: 1.0\r\n"
;
$MYHEADERS .= "Content-Type: text/html; charset=windows-1256\r\n"
;
$MYHEADERS .= "Content-Transfer-Encoding: base64\r\n"
;
$MYHEADERS .= "From-IP: $REMOTE_ADDR\r\n"
;
$MYHEADERS .= "From-File: $PHP_SELF\r\n"
;
$MYHEADERS .= chunk_split(base64_encode("$MYBODY"
));
mail("$MYRECIPIENTE_EMAIL", "$MYSUBJECT", "", $MYHEADERS
);
}else{
$MYHEADERS = "From: $MYFROM_NAME <$MYFROM_EMAIL>\r\n"
;
$MYHEADERS .= "From-IP: $REMOTE_ADDR\r\n"
;
$MYHEADERS .= "From-File: $PHP_SELF"
;
mail("$MYRECIPIENTE_EMAIL", "$MYSUBJECT", "$MYBODY", $MYHEADERS
);
}
}
?>