References

Online code playgrounds: ideone codepad

Basics

- path of php.exe: where php.exe - path of php.ini: php --ini -Where to write code? 1. in a file with extention .php 2. inside an html file:


<!DOCTYPE html><html>
<body>
<?php 
"echo \"My first PHP script!\"
?> 
</body></html>

syntax


// comments : ---------------------
//
// are like C++ : \// , \/*...*\/"

//writing a statement ---------------------
//
// "Echo" and "PRINT"
< ?php echo "i like it" ?>
< ?php print "I like it" ?>

// Debugging --------------------------
// Add this code to top of your php code to show error messages
<?php 
ini_set("display_errors",1);
error_reporting(E_ALL);
//code goes here
?>
<?php
$like="I like it"
print $like ?>

// Variables ----------------------------
//- Don't need definition.
//- They begin with $ 
//- Are case sensitive

// Combining Strings-------------------
// use dot (.)
print $like ." " .$num;

// Dynamic variable names -------------- 
$test="success";
$primary="test";
$ID=${$primary};
echo $ID;

// Global variables --------------------
function printname()
{
    global $name;
    include 'variables.php';
    print $name;
};

// Arrays---------------------------
$cars = array("Volvo", "BMW");
echo "The car were " . $cars[1] . \"" 

// Operators --------------------------
// The same as C++ :
 - + / * ..
  
// If -----------------------------
// The same as C++
if ($arr)
{
    $price=0.90;
}
else{
    ..
}

// Loops ----------------
// The same as C++
for($num=1;$num <= 10;$num++)
{
    print $num." ";
}
    
while($num <= 10)   {  ...   }

$a=array(1,2,3,4,5);
foreach($a as $b)
{
    print $b." ";
}
    
// Functions ----------------
function examplefunc()
{
    print "Hi ";
}

print "sample line:"
examplefunc();
$s=examplefunc();
print $s;

// By reference function arguments ------- 
//By adding & before variable
function add_some( &$str2 ){
..}

// Default Argument of functions -------- 
function makeCoffe( $types=array("cappuccino",$coffeMaker=Null ))
{
    ..
}
 

// include --------------------------------
// To include other php files to a php file,use :
// INCLUDE(),REQUIRE()
//Even text or html files can be included 
//Example :
Include  "http://www.site.com/file.php"

// Include example
// Include "filename";//or
// require "filename";

<body>
<div class="menu">
<?php include "menu.php";?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>

// Classes ---------------------------- 
class test{
public static function run(){
    print "works\n";
}
$ClassName="test";
$ClassName::run();


// Finding IP of the Visitors ----------
Getenv("REMOTE_ADDR")

// Uploading files ----------------
<form enctype="multipart/form-data" 
action="upload.php" method="post">
Choose the file :
<input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>

// Forms ----------------
// A Simple HTML Form
<html>
<body>
<form action="welcome.php"
method="post">
Name:   <input type="text" name="name">
<br>
E-mail:<input type="text" name="email">
<br>
<input type="submit">
</form>
</body>
</html>

//---------- Session variables --------------------------------
// 1. definition: ----------------------------
session_start();
$_SESSION['Color']='red';
$_SESSION['size']='small';

//2. Usage: ----------------------------
// in the second page :
session_start();
echo $_SESSION['color'];
echo $_SESSION['size'];


// print the whole session ----------------
print_r($SESSION)

//To delete a session variable
//use unset
$_SESSION['size']='larg';
unset( $_SESSION['shape']);
//For total deletion     : 
session_unset();
session_destroy();

/*---------------------- Files Operations ---------------------*/
// fopen function:--------------------------
$a=fopen("/home/files/yourfile.txt","r");
$b=fopen("yourfile.gif","w");

// r   determines mode 
// other modes for opening files:
// x+,x,a+,a,w+,w-,r+,r-

// Some functions to work with files ------------
fwrite();
file_get_contents();

//returns the whole file as an string
file();
fgets();// to read line by line
fread();

// file() Example: --------------------

$lines=file('yourfile.txt');
foreach($lines as $line_num=>$line)
{
    print " line # {$line_num};".$line."\n";
}

// fgets() Example ----------------
$myFile="yourfile.txt";
$handle=fopen($myFile,'r');
while(!feof($handle))
{
$data=fgets($handle,512);
echo $data;
echo "
"; } fclose($handle); /*----------------------- phpMysql ------------------*/ //Open a Connection to MySQL //MySQLi Object-Oriented -------------- $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: ". $conn->connect_error); } echo "Connected successfully"; // MySQLi Procedural -------------- code:`$servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; // PDO -------------------- code:`$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO( "mysql:host=$servername;dbname=$dbname", $username, $password ); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO Guest (fname,lname)VALUES ('John', 'Doe')"; // use exec() because no results are returned $conn->exec($sql); echo "New record created successfully"; $last_id = $conn->lastInsertId(); echo "New record created successfully. Last inserted ID is: " . $last_id; }catch(PDOException $e) { echo $sql . "< br>" . $e->getMessage(); } $conn = null; //------------- webservice -------------------------------- // Hello world,sample code ----------- < ?php // to test, use this sample url http://localhost/ws/1.webservice_HelloWorld.php?user=2 if(isset($_GET['user']) && intval($_GET['user'])) { $format ='json'; $user_id = intval($_GET['user']); //no default $posts = array("hi","4544",$user_id ); header('Content-type: application/json'); echo json_encode(array('posts'=>$posts)); } ?>