PHP Couse Referance
PHP Couse Referance
***/
1- data types :
ex :
<?php
class car {
function carWalk(){
$this->wheel= "mechlin";
}
}
echo gettype($var1)."<br/>";
echo gettype($var2) ."<br/>";
echo gettype($var3) ."<br/>";
echo gettype($var4) ."<br/>";
echo gettype($var5) ."<br/>";
echo gettype($var6) ."<br/>";
echo gettype($var7) ."<br/>";
echo gettype($var8) ."<br/>";
echo "<h2>var_dumb</h2>";
var_dump ($var1);
var_dump ($var2) ;
var_dump ($var3) ;
var_dump ($var4) ;
var_dump ($var5) ;
var_dump ($var6) ;
var_dump ($var7) ;
var_dump ($var8) ;
?>
/
**=================================================================================
========================*/
2- constats // Global
__ // magic constats :
===================================================================================
=============================
3- logical opertaor :
[and] : condition 1 and 2 and 3
[&&] : same as and but it preferable .
[xor] : one is true [lazem shart wa7ed yt772 bas msh el etneen ]
[||] : or
[or] : condition1 or condition 2 or all
[!] : not
===================================================================================
================================
// if we want to igonre error and disaper from hackers (file path) : put(@) :
before function.
@fopen('amr.txt', 'r')
//if we want to put custom message when the page is not exists:
@fopen('amr.txt', 'r') or die(' this File is not found please go another page') .
// advanced loop :
1-
for($i= 1 ; ; $i++) {
if($i > 20) break ;
echo $i . "<br>";
}
2-
$i= 1 ;
for(;; $i++) {
if($i > 20) break ;
echo $i . "<br>";
}
3-
$i= 1 ;
for(;;) {
if($i > 20) break ;
echo $i . "<br>";
$i++ ;
}
=================================================
do-while :
$i= 100;
do {
$i++ ;
echo $i ;
}while ($i<20);
===========================================================================
$cot = array(
'egy' =>'egypt',
'leb' =>'lebnaon',
'sy' =>'syria',
'u' =>'usa',
'ca' =>'canada',
'sau' =>'sudia aribia',
'qa' =>'qatar'
);
foreach($cot as $key => $value ){
echo $key . ":" . $value .'<br>';
}
"egy:egypt
leb:lebnaon
sy:syria
u:usa
ca:canada
sau:sudia aribia
qa:qatar"
===================================================================================
===
functions advanced :
<?php
// frame styling
function cerateFrame($element){
$frame = "<div class= 'frame'>";
$frame .= $element ;
$frame .= "</div>";
return $frame ;
}
$myElement = cerateFrame($id)
?>
<!DOCTYPE html>
<html>
<head>
<title>content</title>
<style>
.frame{
background-color: #ccc ;
color: white ;
padding :20px ;
margin: auto ;
text-align : center ;
width : 400px ;
border-radius : 10px ;
}
</style>
</head>
<body>
<?php echo $myElement ?>
</body>
</html>
<head></head>
===================================================================================
====================+
indexed array :
foreach loop on array :
===========================================================
for loop on array :
associative array :
foreach():
syntax :
["key" => 'value ,
"key" => 'value,
"key" => 'value
]
note ! :
key : accpets only integer and string not array or object
ex :
<?php
$langs = [
'html' => "60%",
'css' => "60%",
'js' => "40%",
'java' => "20%",
'bootstrap' => "20%",
'hquery' => "70%",
'ajax' => "20%",
'jason' => "90%"
];
$langs[]= 'amr'; // add value to array
$langs[5] = 'karreem'; // reset index 7
echo "<ul>";
foreach($langs as $key => $value){ // key as value
echo '<li>'. $key. ' '. $value . '</li>' ;
}
echo "</ul>";
echo count($langs); // length of array in php
?>
note : key must be unique : css , html : if we asign many values it takes last one
==============================================================
$diet = array(
"dayOne" => array('meat', 'bread', 'banaana', 'apple', 'kewi') ,
"dayTwo" => array('bread', 'strawibey', 'apple') ,
"dayThree" => array('milk', 'fish', 'banaana', 'meat', 'kewi') ,
"dayFour" => array('meat', 'bread', 'banaana', 'apple', 'kewi',
array(
" dayFive" => array('meat', 'bread', 'banaana', 'apple', 'kewi')
))
);
echo"<pre>";
print_r($diet) ;
echo $diet["dayFour"][6]['meat'] ;
echo "</pre";
$diet = array(
"dayOne" => ['meat', 'bread', 'banaana', 'apple', 'kewi'],
"dayTwo" => array('bread', 'strawibey', 'apple') ,
"dayThree" => array('milk', 'fish', 'banaana', 'meat', 'kewi') ,
"dayFour" => array('meat', 'bread', 'banaana', 'apple', 'kewi',
array(
" dayFive" => array('meat', 'bread', 'banaana', 'apple', 'kewi')
))
);
echo"<pre>";
print_r($diet) ;
output :
array methods :
$array = [
'html',
'css',
'php' ,
'js' ,
'mysql' ,
'ruby',
'python'
] ;
==============================================
if(array_key_exists("html", $array)){
echo 'yes its found ';
}else {
echo 'no' ;
}
'no' : because it's not key but if we add in associative array : yes its found .
$array = [
'html',
'css',
'php' ,
'js' ,
'mysql' ,
'ruby',
'python'
] ;
Array
(
[0] => html
[1] => css
[2] => php
[3] => js
[4] => mysql
[5] => ruby
[6] => python
[7] => amr
[8] => kareem
)
===========================================
Array
(
[0] => amr
[1] => kareem
[2] => html
[3] => css
[4] => php
[5] => js
[6] => mysql
[7] => ruby
[8] => python
)
=======================================================
deleting array :
1 - array_pop(array) //delete the last element in the array .
array_pop($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>
Array
(
[0] => html
[1] => css
[2] => php
[3] => js
[4] => mysql
[5] => ruby
)
======================================
array_shift($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>
Array
(
[0] => css
[1] => php
[2] => js
[3] => mysql
[4] => ruby
[5] => python
)
================================================================================
sort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
============================
methods of sort :
Array
(
[0] => 10
[1] => 20
[2] => ass
[3] => html
[4] => js
[5] => mysql
[6] => php
[7] => python
[8] => ruby
)
============================
rsort() : //reverse sort from Z to A
rsort($array, SORT_STRING);
===================================================================================
=====================
$array = [
"ass" => 80 ,
"php" => 20 ,
"js" => 10 , /// sort the value not the key
"mysql" => 50 ,
"ruby" => 70 ,
"python" => 60
] ;
asort($array, SORT_STRING);
echo '<pre>';
print_r($array);
echo '</pre>';
so the resuly :
Array
(
[js] => 10
[php] => 20
[mysql] => 50
[python] => 60 // sort value for smaller to bigger
[ruby] => 70
[ass] => 80
)
=================================
2- arsort () // sort the value in reverse in associative array from bigger to
smaller alphapitical:
arsort($array, SORT_STRING);
Array
(
[ass] => 80
[ruby] => 70
[python] => 60
[mysql] => 50
[php] => 20
[js] => 10
)
=========================
ksort($array, SORT_STRING);
Array
(
[ass] => 80
[js] => 10
[mysql] => 50
[php] => 20
[python] => 60
[ruby] => 70
)
=================
krsort($array, SORT_STRING);
Array
(
[ruby] => 70
[python] => 60
[php] => 20
[mysql] => 50
[js] => 10
[ass] => 80
)
=========================================
array_reverse( array , peserve ) : // arrange array from last one to first one
preserve : true or fasle
true : preserve the index of the last one as its 5 it goes to the first line with
index
$array = [
"ass" ,
"php" ,
"js" ,
"mysql" ,
"ruby" ,
"python"
] ;
$reversedAray = array_reverse($array);
echo '<pre>';
print_r($reversedAray);
echo '</pre>';
result :
when preserve its fasle : array_reverse($array, fasle ) // default value
Array
(
[0] => python
[1] => ruby
[2] => mysql
[3] => js
[4] => php
[5] => ass
)
but when it is true : array_reverse($array, true ) //preserve the index value
Array
(
[5] => python
[4] => ruby
[3] => mysql
[2] => js
[1] => php
[0] => ass
)
2 - shuffle(array)
Array
(
[0] => php
[1] => mysql
[2] => ass // random
[3] => ruby
[4] => python
[5] => js
)
===================================================================
result :
Array
(
[2] => amr
[3] => amr
[4] => amr
[5] => amr
[6] => amr
[7] => amr
[8] => amr
[9] => amr
[10] => amr
[11] => amr
)
==================
filling by multi dimention array :
$fill = array_fill(1 , 5, [
'amr' ,
'mohamed',
'kareem' ,
'hossam'
]
);
echo '<pre>';
print_r($fill);
echo '</pre>';
result :
Array
(
[1] => Array
(
[0] => amr
[1] => mohamed
[2] => kareem
[3] => hossam
)
========================
=============================================================
echo '<pre>';
print_r($array);
echo '</pre>';
echo $sum ;
result :
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => amr
)
15
==========================
"ass" ,
"php" ,
"js" ,
"mysql" ,
"ruby" ,
"python"
] ;
$rand = array_rand($array, 3) ;
echo '<pre>';
print_r($array);
echo '</pre>';
echo $array[$rand[0]] . "<br>";
echo $array[$rand[1]] ."<br>";
echo $array[$rand[1]] ."<br>";
result :
Array
(
[0] => ass
[1] => php
[2] => js
[3] => mysql
[4] => ruby
[5] => python
)
ass
mysql
mysql
===============================================
$array = [
"ass" ,
"php" ,
"js" ,
"js" ,
"mysql" ,
"ruby" ,
"python" ,
"python" ,
"ruby" ,
"mysql"
] ;
$unique = array_unique($array) ;
echo '<pre>';
print_r($array);
echo '</pre>';
echo '<pre>';
print_r($unique);
echo '</pre>';
result :
Array
(
[0] => ass
[1] => php
[2] => js
[3] => js
[4] => mysql
[5] => ruby
[6] => python
[7] => python
[8] => ruby
[9] => mysql
)
Array
(
[0] => ass
[1] => php
[2] => js // it removes the
repated elements in the top array
[4] => mysql
[5] => ruby
[6] => python
)
===================================================================================
=============================================================
2- String :
=============
result :
Array
(
[0] => l
[1] => love
[2] => php
)
============
$myString = 'l-love php' ;
$myExplodedeString = explode( "-", $myString ) ;
result :
Array
(
[0] => l
[1] => love php
)
ex : 2 .
result :
Array
(
[0] => l
[1] => love, php too much
)
ex : 2 with negative value remove the last elements according to the last
negative index number
Array
(
[0] => l
[1] => love
[2] => php
[3] => too
) // removed the last elements which is 'much'
=========================================================================
real life example [i want to add link by writing css files ]
===================================================================================
====
ex :
$array = array('amr', 'mamoud' , 'mohamed' , 'saker') ;
$str = implode(" & ", $array ) ;
echo ' hello our clients are :' . $str ;
result :" hello our clients are :amr & mamoud & mohamed & saker" //stringed .
===========================================================
echo "<pre>" ;
$arr = str_split($str) ;
print_r($arr) ;
echo "</pre>" ;
result :
=============
$arr = str_split($str, 2) ;
Array
(
[0] => he
[1] => ll
[2] => o // space
[3] => o //space
[4] => li
[5] => ve
[6] => p
[7] => hp
)
==============================================
================================================
result :
hello
hello hello hello hello hello hello hello hello hello hello hello hello hello hello
hello hello hello hello hello hello // 20 times
================================]
loehl , lhloe , e hlol ,l lhoe ///mainly used toi genrate keys or tokkens
==========================================
"6"
======================================+
$skipped = addslashes($str) ;
echo $skipped ;
result :
"
i will go at six o'clcok
i will go at six o\'clcok // added esacape charchter : used to clean a string
and display infront of the user
"
=====================
$skipped = addslashes($str) ;
echo $skipped . "</br>";
$cleanedAfterDatabase = stripslashes($skipped);
echo $cleanedAfterDatabase ;
result :
$skipped = addslashes($str) ;
echo $skipped . "</br>";
$cleanedAfterDatabase = stripslashes($skipped);
echo $cleanedAfterDatabase ;
============================================
striptags(string , allow ) : // remove all html tags from string like links
$str = " i love <span> php </span> go to link <a href = 'my.html '>goggle</a> to
learn php ";
echo $str . "</br>";
$strippedTages = strip_tags($str) ;
echo $strippedTages ;
result :
===============
strip_tags with allow : strip_tags(string , allow) : // alow the tags that i want :
$capitalized = strtolower($str);
echo $capitalized ;
result :
"HELLO
hello"
=======================
==========================================
$capitalized = lcfirst($str);
echo $capitalized ;
=============
$capitalized = ucfirst($str);
==================================
\0 null ,
\n newline
\t tab
\r carriege return ,
\x0B vertical tab
" " space
ex :
$str = "hello i Hove php";
echo $str . "</br>";
echo $trimmed ;
result :
hello i Hove php
llo i Hove php
===================================================
str_word_count(string , 0[default] or 1[return indexed array] , 2[returns
associative array] , charchter is counted in stringlike[&] ) ;
result :
hello i Hove php
4 // number of words of the wstring
Array ( [0] => hello [1] => i [2] => Hove [3] => php )
===========================================================
echo "<pre>";
print_r($count) ;
echo "</pre>";
=============================================
analayiz rhe link as variables
$str = "name='amr'&age'23'address='elshek ";
$count = parse_str($str);
echo $name ;
echo $age ;
echo $address ;
result :
'amr'
'23'
'elshek'
=========================================
parse_str(string ,array) :
ex :
$str = "name='amr'&age='23'&address='elshek'";
echo "<pre>" ;
print_r($array);
echo "</pre>" ;
result :
Array
(
[name] => 'amr'
[age] => '23'
[address] => 'elshek'
)
========================================================
result :
=========================================================
1- strpos(string, the word i want to search , the starting index i want to search
from)
result :
18 : the index of "very"
=======================================
ex :
result :
@gmail.com // default with no third parameter
@gmail.com // all words after @
amrmohsen72 // // all words before @
===================================================================================
====
results :
[0] : means string1 = string2 ,
ex 1: [string1 = string2]
$str1 = "helloooo" ;
$str2= "hello";
echo strcmp($str1, $str2);
result: 0
ex: 2
$str1 = "helloooo0000000000" ;
$str2= "hello";
echo strcmp($str1, $str2);
ex : 3
$str1 ="hello" ;
$str2= "helloooo0000000000" ;
strcmp(string1 ,string2, number) string compare the four of first three numbers
$str1 ="PHPPPPPPPP" ;
$str2= "PHP" ;
====================================================
stringrev(string) : /// reverse the string words
$str1 ="amr" ;
echo strrev($str1);
result :
"rma"
=========================================
substr(string[req], start[req], length [optional]) : // subract string
ex :
$str1 ="i love php so much" ;
$pice = substr($str1,7) ;
echo $pice ;
result :
"php so much"
ex:
$str1 ="i love php so much" ;
$pice = substr($str1,-6,3) ; 3 : number of piece
echo $pice ;
"o m"
==================
ex : 3
$str1 ="i love php so much i love php so much php php " ;
$pice = substr_count($str1, " php", 1 ) ;
result : " 4 " // start search from count for "php" words in string
ex : 4
$pice = substr_count($str1, " php", 1 , 30) ;
result: "2"
======================================================
ex: 1
$str1 ="zmr" ;
$str2 = "osama";
$copmare = substr_compare($str1 , $str2 ,0 );
echo $copmare ;
result : 0 // str1 = str2 where it starts form 6 index and compare (osama with
osama)
---------------------
=============================================
include "inc.php" ;
include_once "inc.php" ;
================================
require , require_once : //same as include but if theres no files it stop the
script
==========================================================
FILE system :
--------------
dirname() : //get the path of the file
echo dirname(__FILE__);
$file = 'amr.txt';
result : C:\xampp\htdocs\php_course
------------------
ex : 1
echo dirname(__FILE__);
$file = 'amr.txt';
if(file_exists($file)) {
echo "good ['. $file.'] is fonund" ;
file_put_contents($file, "add with php"); // it will write the following
inside the file
}
}
else {
echo " sorry ['. $file.'] is Not fonund" ;
}
echo " sorry ['. $file.'] is Not fonund but o cerated it with php" ;
file_put_contents($file, "add with php"); /// create flie if not exists
=========================================
is_writable() : // able to write inside it not read Only
if(is_writable($file)) {
echo " good ['. $file.'] is writable" ;
}
========================================
ex : 1
$name = 'amr';
if(is_dir($name)) { // if folder already exists
rmdir($name) ;
echo 'the directory' . $name . 'is derated ' ;
}
else{
echo " no files here";
}
"no files here"
----------------------
$name = 'mohsen';
if(is_dir($name)) {
echo " file already existes";
}
else{
echo __FILE__ ;
result " C:\xampp\htdocs\php_course\index.php "
-------------
echo dirname(__FILE__);
result : "C:\xampp\htdocs\php_course "
-================
ex ;
==================================
basename(path , suffex) :
----
echo basename(__FILE__ , '.php') // the second parameter is the word that i
want to remove like profiles
result : "index' .
============
include $myfile ; // include the file that i have been created to my page
========================================================
ex :
file_put_contents("amr.text" , "this created by php" , FILE_APPEND) ; //
add over old and dont delete it .
file_put_contents("amr.text" , "this created by php" , LOCK_EX) ; //
lcok file not other users
file_put_contents("amr.text" , "this created by php" , LOCK_EX | FILE_APPEND) ;
// use two together
===================================================================================
==========================================
copy(oldefile , newfile ) ;
copy("amr.txt" , "amr_new.txt") ;
function copyMe($extionsion) {
$orginal = __FILE__ ;
return copy($orginal, $orginal . '.' . $extionsion );
}
copyMe("cool");
======================================
rename(oldname, newname) :
// used to rename file to other name also it can move it to other directory
mkdir("profile");
rename("amr.txt", __DIR__ . "/profile/file.txt");
============================================================================
pathinfo(path , options) ;
echo "<pre>";
print_r( pathinfo(__FILE__));
echo "</pre>";
result : array
Array
(
[dirname] => C:\xampp\htdocs\php_course
[basename] => index.php
[extension] => php
[filename] => index
)
--------
$links = pathinfo(__FILE__ );
echo $links["extension"];
result : "php"
====================================
unlink(__DIR__ ."/profile/file.txt");
ex : // very easy
========================================================
ex :
$myFolder = __DIR__ . '/amr' ;
$file = scandir($myFolder);
echo "<pre>";
print_r($file) ;
echo "</pre>";
Array
(
[0] => .
[1] => ..
[2] => acsses.accdb
[3] => amr.txt
[4] => exel.xlsx
[5] => publis.pub
[6] => rar.zip
)
--------------
// use sort methods :
1- SCANDIR_SORT_DESCENDING // descinding
$myFolder = __DIR__ . '/amr' ;
$file = scandir($myFolder , SCANDIR_SORT_DESCENDING);
echo "<pre>";
print_r($file) ;
echo "</pre>";
result :
Array
(
[0] => rar.zip
[1] => publis.pub
[2] => exel.xlsx
[3] => amr.txt
[4] => acsses.accdb
[5] => ..
[6] => .
)
----------------
3- use sort none
Array
(
[0] => .
[1] => ..
[2] => acsses.accdb
[3] => amr.txt
[4] => exel.xlsx
[5] => publis.pub
[6] => rar.zip
)
---------------
rmdir($myFolder); // cant delete it because its not empty
Warning: rmdir(C:\xampp\htdocs\php_course/amr): Directory not empty in C:\xampp\
htdocs\php_course\index.php on line 10
foreach($files as $file) {
if(is_file($myFolder . "/" . $file)) {
unlink($myFolder . "/" . $file) ;
}
} /// it will delete the all files inside the folder
===========================================================
mode : // important !
r: read only starting from beginning of the file (file must be exist)
r+: read and write starting from beginning of the file (file must be exist)
w: write only (open and clear the content) (creat the file if not exist)
w+: write and read (open and clear the content) ( creat the file if not exist)
a: write only (open and write to the end of file) (creat the file if not exist)
a+ : write and read ( open and write to the end of file) (creat the file if not
exist)
x: write only (creat a new file) (file must not be exist or give error)
x+: write and read (creat a new file) (file must not be exist or give error)
Unix : \n
Windows : \r\n
Mac :\R
===============================================================================
fread(handle ,length ) :
ex:
$handel = fopen("amrs.txt", "r");
$content = fread($handel , 34);
echo $content ;
result : hello iam amr mohsen from the file // from browser
result : orginal
startthis is the new text
=======================================================
whence :
1- SEEK_SET : // defalut start from beginning
2- SEEK_CUR : // seek cuurent : +number of index
3- SEEK_END : start from end negative value
ex :
1-SEEK_SET
result :
old: "elzero "
new : elzebo
-----------
ex: 2
$handle = fopen("amrs.txt", "r+");
fseek($handle , 4, SEEK_SET );
$write = fwrite($handle , "b");
fseek($handle , 1, SEEK_SET );
$write = fwrite($handle , "a"); // keyboaed cursor or pointer
result :
old: "elzero "
new : elzebo
new : eazebo
--------------------------
2- SEEK_CUR : // CURRENT pointer start search
ex :
$handle = fopen("amrs.txt", "r+");
fseek($handle , 2);
$write = fwrite($handle , "r");
fseek($handle , 2 ,SEEK_CUR);
$write = fwrite($handle , "h");
old : am*mo-sen
new: amrmo-sen
newest : amrmohsen
----------
$handle = fopen("amrs.txt", "r+");
fseek($handle , -4 ,SEEK_END); //searched from the end 4 steps[old
value(amrmo-sen) and repllace]
$write = fwrite($handle , "h");
result :
old : amrmo-sen
new : amrmohsen
==============================================================================
super Globals :
function amr() {
$name = "koko";
}
amr();
echo $name ;
use Global :
$name = "koko";
function amr() {
echo $GLOBALS['name'] ;
}
amr();
result : koko
-------------------------
function amr() {
$GLOBALS['name'] = "koko";
}
amr();
echo $name;
result : "koko";
==================================================
prefined variables :
echo $_SERVER["PHP_SELF"];
/php_course/index.php
-------------------------------
echo $_SERVER["SERVER_ADDR"]; //server ip address
::1
------------------------------------
echo $_SERVER["SERVER_NAME"];
localhost
------
if($_SERVER["SERVER_NAME"] == "localhost") {
echo 'you are from local host';
}
--------------------
echo $_SERVER["QUERY_STRING"]; // string after question mark in the link at
the top
name=amr&age=24
-----------------------
$_SERVER["HTTP_REFERER"] : // says what page i gat from used in traffic
$_GET[] ;
index.php page :
if(in_array($userName , $admins)){
echo "welecome " . $userName . " to control panel";
}else {
echo "sorry this username isnot available";
}
=======================================
$_POST[] :
index.php page :
<form action="test.php" method= "post"> <!-- cant get the values in the link -->
<input type="text" name="username">
<input type="password" name= "password">
<input type="submit" name= "login">
</form>
-------------
test.php page :
if(in_array($userName , $admins)){
echo "welecome " . $userName . " to control panel";
}else {
echo "sorry this username isnot available";
}
-------------
using server method to get the method :
echo "ypu send the data with " . $_SERVER['REQUEST_METHOD'] . ' request ' ;
result : "ypu send the data with POST request sorry this username isnot available "
------------
use server method to check :
if($_SERVER['REQUEST_METHOD']== 'POST') {
if(in_array($userName , $admins)){
echo "welecome " . $userName . " to control panel";
}else {
echo "sorry this username isnot available";
}
}else {
echo "you cant brwose this page directlys";
}
"laxem el user yegy 3n tarek el form mynf3sh nkon fel saf7a w n3ml q n5osh 3la el
data"
=====================================
cookies[]
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
==========================================
simple example to make cookies color :
<?php
?>
<!DOCTYPE html>
<html>
<head>
<title>content</title>
<style>
</style>
</head>
<body style = "background-color :<?php echo $body; ?>" >
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="color" name ="color">
<input type="submit" name ="choose" value="choose">
</form>
</body>
</html>
<head></head>
==================================
To delete a cookie, use the setcookie() function with an expiration date in the
past:
setcookie("user", "", time() - 3600);
=====================================
session :
room1 :
session_start() ;
echo "hellow ". $_SESSION['username'] . "how aare you" . "<br>";
echo "your favorite food is : " . $_SESSION['favfood'] ;
echo '<a href="page3.php">Room number 3 </a>';
session_start() ;
echo "hellow ". $_SESSION['username'] . " u are in page 3 " . "<br>";
echo "your favorite food is : " . $_SESSION['favfood'] ;
-----------------------
modify session :
room4 :
session_start() ;
$_SESSION['favfood']= 'chicken'; //session moodiefied in page four
echo "hellow ". $_SESSION['username'] . " u are in page 4 " . "<br>";
echo "your favorite food is : " . $_SESSION['favfood'] ;
-------------------------
print_r($_SESSION);
===========================
page1 :
<?php
-----------
<?php
page1 :
<?php
session_start() ;
$admins = array("amr" , "kareem" , "mohamed" , "yousef" , "adham");
if($_SERVER['REQUEST_METHOD']== "POST") {
$user = $_POST['username'];
if(in_array($user ,$admins )) {
//if is admin
$_SESSION['user'] = $user ; // if is in array sagelo fel session
echo "welcome ". $_SESSION['user']. ' you will be directed to control
panel area';
header("REFRESH:2, URL = control.php"); // redirection
}else {
// if not admin
echo "adimin not fount";
}
}else{
echo "you cant acsses this page directly";
}
?>
----------------------------
page3 :
<?php
session_start();
if(isset($_SESSION['user'])) {
echo "welecome" . $_SESSION['user']. "you are adimn";
}else {
echo "you are not primted to enter this page";
}
?>
===========================================
$name = 'amr';
echo $name ;
sleep(2);
echo "sorry!" ;
-------
usleelp(5000000) ;
--------------
simple function on sleep() :
<?php
function checkFiles() {
if(file_exists('amr.txt')){
echo "file is found" ;
}else {
sleep(1);
checkFiles(); //repat the function untill it found the file
}
}
echo checkFiles();
?>
-------------
time_sleep_until(time()+ 5) :
=============================
exit() or die() :
ex :
<?php
$name = 'amr' ;
echo $name ;
exit(); // bw2af el ode l8aeyt el 7ta de
@fopen('osma.text' , 'r')
or exit("file is not exist") ; //w2af el code l8a' hena mohmea!
echo "ho0";
echo "ho0";
echo "ho0";
resul : "file is not exist"
==================================
uniqid(prefix , more_entropy) : //uniq identidir
<?php
$random = uniqid() ;
echo $random ;
?>
$random = uniqid("script1_") ;
script1_5de954822feae
-------------------
using more_entropy : // increase randomize
$random = uniqid("script1_" ,TRUE) ;
result : "script1_5de956756825e6.52416164" ; // 23 charchter
============================================
filters :
/*
user input ,
bad cookies
web service
server variables
database query result
*/
<?php
foreach(filter_list() as $filter) { //show filter_list
echo $filter ."<br>";
}
?>
int
boolean
float
validate_regexp
validate_domain
validate_url
validate_email
validate_ip
validate_mac
string
stripped
encoded
special_chars
full_special_chars
unsafe_raw
email
url
number_int
number_float
magic_quotes
callback
--------------------
filter_var() :
ex :
<?php
$string = $_POST['test'];
echo filter_var($string , FILTER_SANITIZE_STRING ) // snatiize : ta3keem
?>
----------------------------
filter_var(variable ,filter type , options);
<?php
$input = $_POST['test'];
$filter = filter_var($input , FILTER_VALIDATE_INT ); / validate the integer
input
if($filter == TRUE) {
echo "you enterd integer";
}else {
echo 'you dont';
}
?>
using filter(options) to max max and min number in the input : // options
must be array
<?php
$input = $_POST['test'];
$opt = [
'options' => array(
"min_range" => 1 ,
"max_range" =>999
)
// 'flags' =>
];
$filter = filter_var($input , FILTER_VALIDATE_INT , $opt);
if($filter == TRUE) {
echo "GOOD ! the ". $input ." is between 1 and 999";
}else {
echo 'sorry the ' . $input . 'is not between';
}
?>
--------------
FILTER_VALIDATE_IP example :
<?php
$input = $_POST['test'];
$opt = ['options' => array(),'flags' => FILTER_FLAG_IPV4 ];
$filter = filter_var($input , FILTER_VALIDATE_IP , $opt);
if($filter == TRUE) {
echo "GOOD ! the ". $input ." is version 4";
}else {
echo 'sorry the ' . $input . 'is version 6';
}
?>
result :GOOD ! the 192.168.1.1 is version 4
===============================
validate VS snatiize : // important for security :
<?php
$input = $_POST['test'];
date(format , timestamp) ;
//today :2019-12-07 07:33:18 :
--------------
advanced example 2 :
$month = 30*24*60*60;
$afterSixMonth = time() +(6*$month);
echo date("l jS \of F Y d:h:s a" ,$afterSixMonth) ;
===================================================================================
=============================================================
===================================================================================
===========================================================
MYSQL : database
methods :
1- command line
2-PHP myadmin
3- php software
<?php
try {
$db = new PDO($dsn , $user, $password ,$options ); //start a new
connection with PDO class
$db ->setAttribute(PDO::ATTR_ERRMODE ,PDO::ERRMODE_EXCEPTION); //PDO
OPTIONS IN MANUAL PHP
$query= "INSERT INTO items (name) VALUES ('koko')"; //query
$db->exec($query) ; //excute query
echo "the connection established";
}catch(PDOException $e) {
echo "the connection failed" .$e->getMessage() ;
}
?>
result : if no error : "the connection established"
if an error occuerd : $password = '123'; //password " then
the connection failedSQLSTATE[HY000] [1045] Access denied for user
'root'@'localhost' (using password: YES)
============================================================
data types :
tables :
// create table
create table students(
id int(11) ,
name varchar(255) ,
email varchar(2550)
);
-------------------
MariaDB [students]> CREATE TABLE AMR (
-> name varchar(255),
-> id int(11) ,
-> email varchar(255) /// create table
in command line
-> )
-> ;
Query OK, 0 rows affected (0.249 sec)
--------------------------------------------------
========================================================
=====================================
Alter : add
edit : datatype of column ,
edit the column name ,
edit the arrangment of the column,
add new column
-------
ALTER TABLE kareem ADD password varchar(255); // it will add a a new record to
table but at the end
ALTER TABLE kareem ADD address varchar(255) AFTER name;
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| password | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
===========
alter : drop
ALTER TABLE kareem DROP password; /// delete passowrd from coloumn karrem
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
========================
change postion of column :
MariaDB [students]> describe kareem;
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
====================================================
change the data type of the column :
MariaDB [students]> ALTER TABLE kareem CHANGE id id int(11);
ALTER TABLE newitems RENAME osama; //use Alter to change name of the table
newitems to osama ;
======================================
constraints :
NULL , NOT NULL , UNIQUE , primary key , foregin key
ALTER TABLE kareem MODIFY osama varchar(255) NOT NULL; // add NOT NULL
constraint
ALTER TABLE kareem ADD UNIQUE(osama); // add UNIQUE constraint
ALTER TABLE kareem DROP INDEX userid ; // remove UNIQUE from the table
constraint
ALTER TABLE kareem MODIFY userid int(21) NOT NULL UNIQUE ; //add not null and
UNIQUE at the same line
--------------------------------------------
primary key :
second method :
CREATE TABLE teachers (
tid int NOT NULL ,
tname VARCHAR(255) , // alone at the end
PRIMARY KEY(tid)
);
----------------
create[ add ] primary key at the existing table :
ALTER TABLE kareem ADD PRIMARY KEY(userid); // add primary key to adress in
table kareem
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| name | varchar(255) | YES | | NULL | |
| regligon | varchar(255) | YES | | NULL | |
| email | char(50) | YES | | NULL | |
| userid | int(21) | NO | PRI | NULL | | //primary key
| address | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
-----------------------
drop primary key :
=================================================
foregin key :
-----------------
// create table orders //child table
CONSTRAINT cons_client
FOREIGN KEY (client) REFERENCES clients(id)
on DELETE CASCADE on UPDATE CASCADE ,
cONSTRAINT cons_shop
FOREIGN KEY (shop) REFERENCES shops(id)
on DELETE CASCADE on UPDATE CASCADE
==================================
SELECT * FROM clients JOIN shopmembership ON clients.id = shopmembership.client
WHERE shopmembership.shop = 1;
// -get the members which has shop id 1 .
-----------------------------
SELECT * FROM shops JOIN shopmembership ON shops.shop_id = shopmembership.shop
WHERE shopmembership.client = 20166233;
sting functions :
--------------------
1- LEFT (sting , length);
orginal string :
-----------------
myText |
-----------------
egypt |
saduia araiba |
canada |
--------++-------
SELECT LEFT (myText , 2) FROM try ; // cut the first 2 charchters column
myText
-----------------
myText |
-----------------
eg |
sa |
ca |
--------++-------
==========================================
3 - RIGHT(string , length) ;
SELECT RIGHT(myText , 2) FROM try;
-----------------
myText |
-----------------
pt |
ba | //cuts 2 charchters from right
da |
--------++-------
======================================
-----------------
myText |
-----------------
gyp |
adu |
ana |
--------++-------
==============================================
LENGTH(string) : OR
CHAR_LENGTH () // mesure the acutal length in charchter as (euro sign)
==================================
UCASE(string) // uper case :
SELECT UCASE(myText) as COUNT FROM try ;
LCASE(string) //lower case
=====================================
REPEAT(string , number of repeats);
SELECT myText, REPEAT(myText ,3 ) AS repeted FROM try ;
----------------------------------------------------------------
myText | repeted
------------------|---------------------------------------------
egypt | egypt egypt egypt |
saduia araiba | saduia araiba saduia araiba saduia araiba |
canada | canada canada canada | //repat
the entire string
--------++-------++--------------------------------------------
-------------------------------------------
REPLACE(string , from ,to) ;
SELECT myText, REPLACE(myText ,'a' , '@' ) AS replaced FROM try ;
-------------------------------------+
myText | repeted |
------------------|------------------|
egypt | egypt |
saduia araiba | s@dui@ @r@ib@ |
canada | c@n@d@ | //change the charchter "a" to "@"
inall column
--------++-------++------------------+
result :
"egypt , added "
"saduia araiba , added"
"canda , added "
=======================================
string :
INSERT(string , postion , length , new string)
SELECT myText , INSERT(myText,3,2 , 'amr')AS INSERTED FROM `try`;
-------------------------------------+
myText | INSERTED |
------------------|------------------ |
egypt | egamrt |
saduia araiba | saamria araiba |
canada | caamrda | //replace from postion 3 two
charchters by new string
--------++-------++------------------+
another ex :
UPDATE `try` SET myText = INSERT(myText, 3,2,'serial');
=======================================================
TRIM(methods[leading | trailing | both] [remove string]FROM String) :
- methods optional if NOT writtten both will be used
- removeed string if NOT used space will be removed
ex 1 :
SELECT `name` , trim(name) FROM `try` or SELECT `name` , trim(BOTH,name) FROM
`try
old : osama
new :osama
---------
with leading: // cut from left only and leave right space
SELECT `name` , trim(LEADING FROM name) FROM `try`
old :osama // here space
new : osama
------------
with option trailing: // cut from right
SELECT `name` , trim(TRAILING FROM name) FROM `try`
-------------------------------------+
myText | paddedString |
------------------|------------------ |
os | @@@os |
mah | @@mah |
osama elzero | osama | // i want 5 charchters only and it add the
sting[@] to the string if its exseesd it will not add anything
--------++-------++------------------+
CEIL(number) ;
SELECT numbers as old , CEIL(numbers) as new FROM `try` ;
FLOOR(number);
ROUND(number, decimal(2 or 3 ... ));
=================================
TRUNCATE(number , decimal) ;
SELECT numbers as old , round(numbers) as rounded ,
TRUNCATE(numbers , 2) as truncated FROM `try`
---------------+----------------------+--------------+
old | rounded | truncated |
---------------+-------------------------------------|
4.5 | 4 | 4.50 |
4.5995879 | 5 | 4.59 |
1.6587699 | 2 | 1.65 | //diffrence between
truncate and round is truncate takes the two number but dosent aproxmiate
--------++-------++------------------+---------------+
---------------------
POW(numebr, powerd) ; //power //so easy
POW(2,2) : result : 4
-----------------------
MOD(number,mod); MOD(21,5) : result: 1
=======================================================================
DAYNAME(date);
SELECT CURRENT_DATE() , DAYNAME(CURRENT_DATE()) AS todayName
------------+-----------+--|
CURRENT_DATE() | todayName|
------------+-----------+ |
2019-12-14 | Saturday |
------------+-----------+--+
set date :
SELECT CURRENT_DATE() , DAYNAME('2016-07-30') AS nextWeek
==============================
DAYOFMONTH(date);
SELECT CURRENT_DATE() , DAYOFMONTH(CURRENT_DATE()) AS monthdate
------------+-----------+--|
CURRENT_DATE() | monthdate|
------------+-----------+ |
2019-12-14 | 14 |
------------+-----------+--+
==============================
DAYOFWEEK(date);
==============================
------------+-----------+--|
CURRENT_DATE() | yearDate |
------------+-----------+ |
2019-12-14 | 348 |
------------+-----------+--+
========================
MONTH(date);
SELECT MONTH(CURRENT_DATE());
result : 12
==============================
MONTHNAME(date);
SELECT MONTHNAME(CURRENT_DATE());
result : December
==============================
HOUR(date);
SELECT HOUR(CURRENT_DATE());
result : 8
==============================
MINUTE(date);
SELECT MINUTE(CURRENT_DATE());
result : 17
==============================
DATEDIFF(date1 , date2) //date diffrence // very important
ex:
SELECT id, personDate , name ,
CONCAT( 'regesterd',DATEDIFF(CURRENT_DATE() ,personDate) , 'days ago') as
numberOfDays FROM `try` //diffrence between CURRENT date and the puted date
---------------+----------------------+--------------+----------+------+
id | personDate | name | numberOfDays |
---------------+-----------------------------------------------+----++++
1 | 2019-12-18 02:12:05 | KOKO | 4 days ago |
2 | 2019-12-11 08:02:01 | MOHSEN | 3 days ago |
2 | 2019-12-10 02:02:0 | aamr | 3 days ago |
--------++-------++------------------+---------------+----------+------+
==========================================================================
example :
---------------+----------------------+--------------+----------+-------
+------------------------------------- |------------------+
id | personDate | name | added 10 days |
subracted_5_month |lastdayInTheMonth |
---------------+-----------------------------------------------+--------
+------------------------------------- |-------------------
1 | 2019-12-10 02:12:05 | KOKO | 2019-12-20 02:02:01 |
2019-07-10 02:02:01 | 2019-12-31 |
2 | 2019-12-11 08:02:01 | MOHSEN | 2019-12-21 02:02:01 |
2019-07-10 02:02:01 | 2019-12-31 |
2 | 2019-12-10 02:02:0 | aamr | 3 days ago |
2019-07-10 02:02:01 | 2019-12-31 |
--------++-------++------------------+---------------+----------
+----------------------------------------------+------------------|
===================================================================================
=========================================
comparision functions :
ex:3
SELECT * FROM `try` WHERE
`personDate` BETWEEN DATE_SUB(CURRENT_DATE() ,INTERVAL 2 MONTH) AND
CURRENT_DATE() ; last tow months - current date
----------------------------
NOT BETWEEN AND :
SELECT * FROM `try` WHERE `id` NOT BETWEEN 2 AND 6
1
7
==========================================================
IN
SELECT * FROM `try` WHERE `id` IN (2,5 , 6, "osama") //get the idS of these
numbers [if its no exists dont worry ]
--------------------------------
NOT IT /// all exept numbers in the brackets
SELECT * FROM `try` WHERE `id` NOT IN (2,5 , 6, "osama")
==========================================================
LIKE
% : (empty or collecttion of charchters) : means unknowen [.....]
SELECT * FROM `try` WHERE `name` LIKE '%amr'
sELECT * FROM `try` WHERE `name` LIKE '%sen%';
sELECT * FROM `try` WHERE `name` LIKE '%a%' :osama ,aamr
sELECT * FROM `try` WHERE `name` LIKE 'm%n'
NOT LIKE
-------
_(one charchter).
ex : SELECT * FROM `try` WHERE `name` LIKE '_sama' result : osama , asama
ex: SELECT * FROM `try` WHERE `name` LIKE 'sam_h': result : sameh , samah
-------------------
NOT LIKE : .ex : SELECT * FROM `try` WHERE `name` NOT LIKE '%sama' // all
expec this
===================================================================================
=========
comparision opertaors :
logical operators :
AND : SELECT * FROM `try` WHERE `name` LIKE '%sama' AND id > 100
NOT: SELECT * FROM `try` WHERE `name` NOT LIKE '%sama'
OR : SELECT * FROM `try` WHERE `name` LIKE '%sama' OR id > 100
XOR [A condition and not B condition]: SELECT * FROM `try` WHERE `name` LIKE
'%sama' XOR id > 100
[B condition and not A condition]:
===========================================
-------------------++++
id | resluts |
1 | bad luck |
1 | bad luck |
2 | bad luck |
3 | good luck|
5 | good luck|
0 | bad luck |
0 | bad luck |
10 | good luck|
------------------- --|
================================
Case :
SELECT name ,id ,
CASE
WHEN `id` = 1 THEN 'good luck '
WHEN `id` = 2 THEN 'ex luck '
WHEN `id` = 5 THEN 'amazing luck '
WHEN `id` = 0 THEN 'bad luck '
END as result
FROM `try`;
result :
-------------------------+
id | resluts |
1 | bad luck |
1 | bad luck |
2 | ex luck |
3 | good luck |
5 | amazing luck|
0 | bad luck |
0 | bad luck |
------------------- -----
=========================================