25
PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and for. Some useful PHP functions How to work with HTML forms, cookies, files, time and date. How to create a basic checker for user-entered data

PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Embed Size (px)

Citation preview

Page 1: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

PHP Basics

Introduction to PHP• a PHP file, PHP workings, running PHP.• Basic PHP syntax• variables, operators, if...else...and switch, while, do while, and for.

Some useful PHP functions

How to work with • HTML forms, cookies, files, time and date.

How to create a basic checker for user-entered data

Page 2: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

PHP

توسط راسموس ِل�ردورت ابداع شد.1995در سال .در اصل برای ردیابی مشاهده کنندگان وب سایت ِل�ردورت درست شد بعد از دو سال به همراه آپاچی یکی از بهترین ابزارهای توِلید صفحات

دینامیک شد..یک زبان اسکریپتی رایگان و با کد باز است کامال باmySQL.سازگار است

PHP مثل جاوا اسکریپت است منتهی در سمت سرور کار می کند.

یعنی با برچسپهای مخصوص و داخل کدHTML .جاسازی می شود ( از روی نوع فایل.php یا .phtml سرور متوجه می شود با متن )PHP

سروکار دارد. سرور کدPHP را اجرا و نتیجه را داخل صفحه HTML.قرار می دهد ِلذا کاربر هیچوقت کدPHP .را نمی بیند و فقط نتیجه اجرا را می بیند

Page 3: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

What do You Need?

شما به نرم افزارهای زیر برای اجرای وب سایتهایی که با PHP:می نویسید دارید

PHP- زبان اسکریپت نویسی 1MySQL –پایگاه داده 2iis- وب سرور آپاچی یا 3

Download PHP for free here: http://www.php.net/downloads.php

Download MySQL for free here: http://www.mysql.com/downloads/index.html

Download Apache for free here: http://httpd.apache.org/download.cgi

Page 4: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Basic PHP syntax

PHPهر قطعه کد بین برچسپهای

?<php قرار ?< ومی گیرد .

دستوراتprint و echo برای نمایش

خروجی هر دستور باید با;

خاتمه یابد غیر از آخرین •

دستور که اختیاری ;وجود است.

برای توضیحات //تک خطی

*/ برای */ و توضیحات چند خطی

<html><!-- hello.php COMP519 --><head><title>Hello World</title></head><body> <p>This is going to be ignored by the PHP interpreter.</p>

<?php echo ‘<p>While this is going to be parsed.</p>‘; ?>

<p>This will also be ignored by PHP.</p>

<?php print(‘<p>Hello and welcome to <i>my</i> page!</p>'); ?>

<?php

//This is a comment

/* This is a comment block */ ?>

</body></html>

view the output page

Page 5: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

متغییر های اسکاِلر

انواع متغییرها:boolean integerfloatstring برای

نگهداری رشته ها

<html><head></head><!-- scalars.php COMP519 --><body> <p><?php$foo = True; if ($foo) echo "It is TRUE! <br /> \n";$txt='1234'; echo "$txt <br /> \n";$a = 1234; echo "$a <br /> \n";$a = -123; echo "$a <br /> \n";$a = 1.234; echo "$a <br /> \n";$a = 1.2e3; echo "$a <br /> \n";$a = 7E-10; echo "$a <br /> \n";echo 'Arnold once said: "I\'ll be back"', "<br /> \n";$beer = 'Heineken'; echo "$beer's taste is great <br /> \n";$str = <<<EODExample of stringspanning multiple linesusing “heredoc” syntax.EOD;echo $str;?> </p></body></html>

view the output page

شروع می شوند و می توانند از رشته ها و اعداد نگهداری $متغییر با عالمت •کنند.

نوع یک متغییر وابسته به داده ای است که نگهداری میکند و در حین اجرا قابل •تغییر است.

Page 6: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

آرایه بصورت نقشه وجود دارند. یعنی هر آیتم دارای کلید است.PHPآرایه ها در آرایه را ایجاد )(arrayدستور

می کنذ.<?php$arr = array("foo" => "bar", 12 => true);echo $arr["foo"]; // barecho $arr[12]; // 1?>

•key .یک عدد یا یک رشته است •value هر نوع دادهای معتبر در

PHP

<?phparray(5 => 43, 32, 56, "b" => 12);array(5 => 43, 6 => 32, 7 => 56, "b" => 12);?>

اگر ایتمی دارای کلید نباشد، به عنوان 1بزرگترین کلید +

کلید آن قرار داده می شود.

<?php$arr = array(5 => 1, 12 => 2);$arr[] = 56; // the same as $arr[13] = 56;$arr["x"] = 42; // adds a new elementunset($arr[5]); // removes the elementunset($arr); // deletes the whole array$a = array(1 => 'one', 2 => 'two', 3 => 'three');unset($a[2]);$b = array_values($a);?>

unset)( یک زوجکلید/مقدار را حذف

می کند.array_values)( آرایه را بصورت

شمارشی ایندکس گذاری می کند.

view the output page

Page 7: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

یک ثابت اسمی است که به یک مقدار نسبت داده می شود. برای اسم گذاری ثابتها معموال از حروف بزرگ استفاده می شود.

ثابتها را می شود در هر جای برنامه استفاده کرد.

<?php

// Valid constant namesdefine("FOO", "something");define("FOO2", "something else");define("FOO_BAR", "something more");

// Invalid constant namesdefine("2FOO", "something");

// This is valid, but should be avoided:// PHP may one day provide a “magical” constant// that will break your scriptdefine("__FOO__", "something");

?>

ثابتها

Page 8: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

عملگرها

+, -, *,/ , %, ++, -- عملگرهای ریاضی: =, +=, -=, *=, /=, %= :عملگرهای انتساب:

==, !=, <, >, <=, >=عملگرهای مقایسه ای: &&, ||, !عملگرهای منطقی: . , .=عملگرهای رشته ها:

Example Is the same asx+=y x=x+yx-=y x=x-yx*=y x=x*yx/=y x=x/yx%=y x=x%y

$a = "Hello ";$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";$a .= "World!";

Page 9: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

if else شرط:

<html><head></head><!-- if-cond.php COMP519 --><body>

<?php$d=date("D");if ($d=="Fri") echo "Have a nice weekend! <br/>"; else echo "Have a nice day! <br/>";

$x=10;if ($x==10){ echo "Hello<br />"; echo "Good morning<br />";}

?>

</body></html>

if (condition)code to be executed if condition is true;elsecode to be executed if condition is false;

view the output page

date)( یک تابع آماده است کهمی توان آنرا با پارامترهای

مختلف صدا زد تا تاریخ و زمان را با فرمتهای متفاوت

برگرداند.

در این حاِلت ما امروز را بصورت یک رشته سه حرفی

گرفته ایم.

Page 10: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

switchشرط:

<html><head></head><body><!–- switch-cond.php COMP519 --><?php$x = rand(1,5); // random integerecho “x = $x <br/><br/>”;switch ($x){case 1: echo "Number 1"; break;case 2: echo "Number 2"; break;case 3: echo "Number 3"; break;default: echo "No number between 1 and 3";}?>

</body></html>

switch (expression){case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break;default: code to be executed if expression is different from both label1 and label2;}

view the output page

Page 11: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

do-while و while حلقه:

<html><head></head><body>

<?php $i=1;while($i <= 5){ echo "The number is $i <br />"; $i++;}?>

</body></html>

whileحلقه

view the output page

<html><head></head><body>

<?php $i=0;do{ $i++; echo "The number is $i <br />";}while($i <= 10);?>

</body></html>

do-whileحلقه

view the output page

Page 12: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

foreach و forحلقه:

<?phpfor ($i=1; $i<=5; $i++){echo "Hello World!<br />";}?>

یک حلقه با تعداد تکرار مشخص

<?php$a_array = array(1, 2, 3, 4);foreach ($a_array as $value) { $value = $value * 2; echo “$value <br/> \n”;}?>

به اندازه عناصر آرایه تکرار می شود.

<?php $a_array=array("a","b","c");foreach ($a_array as $key=>$value){ echo $key." = ".$value."\n";}?>view the output page

Page 13: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

User Defined Functions

<?phpfunction foo($arg_1, $arg_2, /* ..., */ $arg_n){ echo "Example function.\n"; return $retval;}?>

<?phpfunction square($num){ return $num * $num;}echo square(4);?>

<?phpfunction small_numbers(){ return array (0, 1, 2);}list ($zero, $one, $two) = small_numbers();echo $zero, $one, $two;echo "<br/>“?>

<?phpfunction takes_array($input){ echo "$input[0] + $input[1] = ", $input[0]+$input[1];} takes_array(array(1,2)); echo "<br/>“?>

view the output page

Page 14: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Variable Scope

<?php$a = 1; /* global scope */ function Test(){ echo $a; /* reference to local scope variable */ } Test();echo "<br/>“?>

داخل توابع متغییر ها ارزش .محلی دارند

<?php$a = 1;$b = 2;function Sum(){ global $a, $b; $b = $a + $b;} Sum();echo $b;echo "<br/>"?>

global

برای متغییرهای عمومی

<?phpfunction Test1(){ static $a = 0; echo $a; $a++;}Test1(); Test1();Test1();echo "<br/>"?>

static

برای متغییرهایی که مقدار خود را از دست نمی .دهند

view the output page

Page 15: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Including Filesیک فایل را اِلحاق و ارزیابی می کند. )(include عبارت

vars.php<?php

$color = 'green';$fruit = 'apple';

?>

test.php<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

محدوده متغییرهای که در فایل اِلحاق شده تعریف شده اند به محل اِلحاق •فایل بستگی دارد.

نیز استفاده نمود. require_once و include_once می توان از عبارتهای •

view the output page

<?php

function foo(){ global $color;

include ('vars.php‘);

echo "A $color $fruit";}

/* vars.php is in the scope of foo() so * * $fruit is NOT available outside of this * * scope. $color is because we declared it * * as global. */

foo(); // A green appleecho "A $color $fruit"; // A green

?>

view the output page

Page 16: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

PHP Information نصب شده استفاده می گردد.PHPبرای نمایش اطالعات کلی نسخه )(phpinfo تابع

<html><head></head><!– info.php COMP519<body><?php// Show all PHP informationphpinfo();?><?php// Show only the general informationphpinfo(INFO_GENERAL);?></body></html>

INFO_GENERAL The configuration line, php.ini location, build date, Web Server, System and more

INFO_CREDITS PHP 4 creditsINFO_CONFIGURATION Local and master values

for php directives

INFO_MODULES Loaded modules

INFO_ENVIRONMENT Environment variable information

INFO_VARIABLES All predefined variables from EGPCS

INFO_LICENSE PHP license information

INFO_ALL Shows all of the above (default)

view the output page

Page 17: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Server Variables

_$SERVER.یک متغییر رزرو شده است که تمام اطالعات سرور از طریق آن قابل دسترسی است این متغییر یک متغییر عمومی است.

<html><head></head><body>

<?phpecho "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];?>

</body></html>

view the output page

Page 18: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

File Openبرای باز کردن فایل استفاده می شود. fopen("file_name","mode") تابع

<?php$fh=fopen("welcome.txt","r");?>

r Read only. r+ Read/Write.w Write only. w+ Read/Write. a Append. a+ Read/Append.x Create and open for write only. x+ Create and open for read/write.

<?phpif (!($fh=fopen("welcome.txt","r")))exit("Unable to open file!"); ?>

اگر فایل وجود , a و, w در حاِلتهای • سعی می کند fopenنداشته باشد،

فایل را ایجاد کند.، اگر فایل وجود داشته xدر حاِلت •

باشد، منجر به توِلید خطا میگردد.اگر فایل مورد نظر باز نشود عدد •

صفر بر می گردد.

Page 19: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

کار با فایلهاfclose)( فایل را می بندد.

fgetc)( یک کاراکتر از فایل میخواند.

fwrite)(و fputs یک رشته را با و در فایل می نویسد.n\بدون

<?php$myFile = "welcome.txt";if (!($fh=fopen($myFile,'r'))) exit("Unable to open file.");while (!feof($fh)) { $x=fgetc($fh); echo $x;}fclose($fh);?>

<?php$myFile = "welcome.txt";$fh = fopen($myFile, 'r');$theData = fgets($fh);fclose($fh);echo $theData;?>

<?php$myFile = "testFile.txt";$fh = fopen($myFile, 'a') or die("can't open file");$stringData = "New Stuff 1\n";fwrite($fh, $stringData);$stringData = "New Stuff 2\n";fwrite($fh, $stringData);fclose($fh);?>

<?php$lines = file('welcome.txt');foreach ($lines as $l_num => $line) { echo "Line #{$l_num}:" .$line. "<br/>";}?>

view the output page

view the output page

view the output pageview the output page

•feof)( اگر در آخر فایل باشیم true .است

•fgets)( یک خط از فایل را میخواند.

•file)( کل فایل را داخل یک آرایهمی ریزد.

Page 20: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

کار کردن با فرمها

<html><-- form.html COMP519 --><body><form action="welcome.php" method="POST">Enter your name: <input type="text" name="name" /> <br/>Enter your age: <input type="text" name="age" /> <br/><input type="submit" /> <input type="reset" /></form></body></html>

<html><!–- welcome.php COMP 519 --><body>

Welcome <?php echo $_POST["name"].”.”; ?><br />You are <?php echo $_POST["age"]; ?> years old!

</body></html>

$_POST contains all POST data.

$_GET contains all GET data.

view the output page

Page 21: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

کار با کوکیهابرای ایجاد کوکی استفاده setcookie(name,value,expire,path,domain) تابع

می گردد. <?php

setcookie("uname", $_POST["name"], time()+36000);

?>

<html>

<body>

<p>

Dear <?php echo $_POST["name"] ?>, a cookie was set on this

page! The cookie will be active when the client has sent the

cookie back to the server.

</p>

</body>

</html>

نکته: باید )(setcookieتابع

قبل از برچسپ <html> .قرار بگیرد

view the output page

<html><body><?phpif (isset($_COOKIE["uname"]))echo "Welcome " . $_COOKIE["uname"] . "!<br />";elseecho "You are not logged in!<br />";?></body></html>

تمام COOKIE$_متغییر •اطالعات کوکی را دارد.

یک کوکی را )(issetتابع •چک می کند تا ببیند تعریف

شده است یا نه؟اسم متغییر به عنوان •

پارامتر به تابع فرستاده می شود.

view the output page

Page 22: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

نمایش زمان و تاریخdate)( و time)( .برای نمایش زمان و تاریخ استفاده میگردد

<?php//Prints something like: Mondayecho date("l");echo "<br/>“;//Like: Monday 15th of January 2003 05:51:38 AMecho date("l dS \of F Y h:i:s A");echo "<br/>“;//Like: Monday the 15thecho date("l \\t\h\e jS");?>

یک رشته )(date تابعبا فرمتی که از

طریق پارامتر اول فرستاده می گردد

را بر می کرداند.

<?phpecho "<br/>“;$nextWeek = time() + (7 * 24 * 60 * 60);

// 7 days; 24 hours; 60 mins; 60secsecho 'Now: '. date('Y-m-d') ."\n";echo "<br/>“;echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";?>

time)( زمانسیستم را به

GMTفرمت برمی گرداند.

view the output page

Page 23: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Required Fields in User-Entered Dataدر این مثال از کاربر اطالعاتی اطالعاتی گرفته می شود. سپس برنامه

چک می کند که کاربر قسمتهای الزم را پر کرده است یا نه؟<html>

<!-- form_checker.php COMP519 -->

<head>

<title></title>

</head>

<body>

<?php

/*declare some functions*/

function print_form($f_name, $l_name, $email, $os){?>

<form action="form_checker.php" method=“POST"> First Name: <input type="text" name="f_name" value="<?php echo $f_name?>“ /> <br/> Last Name <b>*</b>:<input type="text" name="l_name" value="<?php echo $l_name?>“ /> <br/> Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>“ /> <br/> Operating System: <input type="text" name="os" value="<?php echo $os?>“ /> <br/><br/> <input type="submit" name="submit" value="Submit“ /> <input type=“reset“ /> </form>

<?php}

Print Function

Page 24: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Check and Confirm Functionsfunction check_form($f_name, $l_name, $email, $os)

{

if (!$l_name||!$email){

echo "<h3>You are missing some required fields!</h3>";

print_form($f_name, $l_name, $email, $os);

}

else{

confirm_form($f_name, $l_name, $email, $os);

}

}

function confirm_form($f_name, $l_name, $email, $os)

{

?>

<h2>Thanks! Below is the information you have sent to us.</h2>

<h3>Contact Info</h3>

<?php

echo "Name: $f_name $l_name <br/>";

echo "Email: $email <br/>";

echo "OS: $os";

}

Page 25: PHP Basics Introduction to PHP a PHP file, PHP workings, running PHP. Basic PHP syntax variables, operators, if...else...and switch, while, do while, and

Main Program/*Main Program*/

if (!$_POST["submit"]){?>

<h3>Please enter your information</h3> <p>Fields with a "<b>*</b>" are required.</p>

<?php print_form("","","","");}else{ check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]);}?>

</body></html>

view the output page