<html>
<head> </head>
<body>
test... <br/>
<?php echo "first example.";?>
</body>
</html>
1. <?php ... code ... ?>
2. <script language="php">
... code ...
</script>
3. <? ... code ... ?>
<?= expression ?>
4. ASP-style tags:
<% ... code... %>
$text="example";
$no=4;
$no1=5.6l;
$vect=array(1,2,3,4,5);
$b=TRUE;
$x = "test"; $x1=$x;
$x1 = &$x;
//$x1 is an alias for $x;
$n=4;
include "vars.php"; //$n is visible in "vars.php"
$n=4;
function foo() { echo $n; } // $n is undefined here
function test() {
static $n = 0; $n++; echo $n;
}
$a=2; $b=2;
function test() {
global $a, $b;
$c = $a + $b; //$c is here 4
}
$c = $GLOBALS['a'] + $GLOBALS['b'];
function test_global()
{
// Most predefined variables aren't "super" and require
// 'global' to be available to the functions local scope.
global $HTTP_POST_VARS;
echo $HTTP_POST_VARS['name'];
// Superglobals are available in any scope and do
// not require 'global'. Superglobals are available
// as of PHP 4.1.0, and HTTP_POST_VARS is now
// deemed deprecated.
echo $_POST['name'];
}
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";
test();
will print:
$foo in global scope: Example content
$foo in current scope: local variable
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
Welcome <?php echo $_GET["fname"]; ?>.
You are <?php echo $_GET["age"]; ?> years old!
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
Welcome <?php echo $_POST["fname"]; ?>.
You are <?php echo $_POST["age"]; ?> years old!
function functionName($param1, $param2, ..., $paramn) {
... statements ...
return ...;
}
<?php
function add($x,$y) {
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
class SimpleClass {
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
$instance = new SimpleClass();
class ExtendClass extends SimpleClass {
// Redefine the parent method
function displayVar() {
echo "Extending class\n";
parent::displayVar();
}
}
$extended = new ExtendClass();
$extended->displayVar();
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$str = <<<FOO
this is
a string
FOO;
$str = <<<'FOO'
this is
a string
FOO;
$a = array("a"=>45, 2=>7, 36=>"zzz")
$b = array(4=>40, 67, 87, "b"=>3) is the same as:
$b = array(4=>40, 5=>67, 6=>87, "b"=>3)
$c = array(2=>"zz", 45=>array("a"=>11, 23=>34)) – a multidimensional array
$v = array(1=>2, 2=>"zz", vect=>array(2, 3, 4));
$v[2] = 45;
$v['vect'][1]=4;
$v[2]=3;
unset($v[2]);
unset($v);
$output = `ls –l `
define("const1", "something");
echo const1;
while($n < 4):
$i++;
echo $i;
endwhile;
label:
$i++;
...
goto label;
include "settings.php";
require "global.php";
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
<?php session_start(); ?>
<html>
<body> </body>
</html>
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
<?php
unset($_SESSION['views']);
?>
<?php
session_destroy();
?>
<?php
$con = mysqli_connect("localhost", "user", "pass", "DB");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
// some code
mysqli_close($con);
?>
<?php
$con = mysqli_connect("localhost", "user", "pass", "DB");
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
$result = mysqli_query($con, "SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
{ "Name": "Adrian Sterca",
"Age": 39,
"Profession": "teacher",
"Courses": [ "Web Programming", "Audio-Video Data Processing" ]
}
var obj = JSON.parse(' { "name": "forest", "age" : 39, "sex": "M"} ');
document.write(obj.name);
obj.age=20;
var obj = new Object();
obj.name="forest";
obj.age=25;
obj.sex="M";
var jsonString = JSON.stringify(obj);
$arr = array("name" => "forest", "age" =>39, "sex" => "M");
$jsonString = json_encode($arr);
echo $jsonString;
$arr = json_decode($jsonString, true);
$obj = json_decode($jsonString, false);
var xmlhttp
function showHint(str) {
if (str.length==0) {
document.getElementById("txtHint").innerHTML="";
return;
}
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="submit.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged() {
if (xmlhttp.readyState==4) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) { // code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
$.get("showStudentsFromGroup-GET.php",
{groupid : "2" , name : "forest"},
function(data,status) {
$("#maindiv").html(data);
});
$.ajax({
type : "GET",
url : "showStudentsFromGroup-GET.php",
data: {groupid : "2" , name : "forest"},
success: function(data,status) {
$("#maindiv").html(data);
}
});
$.post("showStudentsFromGroup-POST.php",
{groupid : "2" , name : "forest"},
function(data,status) {
$("#maindiv").html(data);
});
// Function to fetch data from a remote URL
async function getRandomUser() {
try {
// 1. Start the request
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
// 2. Check if the response was successful (status 200-299)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 3. Parse the JSON data from the response body
const data = await response.json();
// 4. Use the data
console.log("User Name:", data.name);
console.log("User Email:", data.email);
} catch (error) {
// Handle any network or parsing errors
console.error("Could not fetch user:", error);
}
}
// Call the function
getRandomUser();
async function createUser() {
const url = 'https://jsonplaceholder.typicode.com/posts';
// The data we want to send
const userData = {
title: 'New Post',
body: 'This is the content of my post.',
userId: 1
};
try {
const response = await fetch(url, {
method: 'POST', // Specify the HTTP method
headers: {
'Content-Type': 'application/json' // Tell the server we are sending JSON
},
body: JSON.stringify(userData) // Convert the JS object into a JSON string
});
if (!response.ok) {
throw new Error(`Status error: ${response.status}`);
}
const result = await response.json();
console.log('Success! Created item:', result);
} catch (error) {
console.error('Error posting data:', error);
}
}
createUser();
async function getPrivateData() {
const token = 'YOUR_SECRET_ACCESS_TOKEN'; // Usually retrieved from login
try {
const response = await fetch('https://api.example.com/v1/dashboard', {
method: 'GET',
headers: {
// Standard headers
'Content-Type': 'application/json',
// The Authorization header
'Authorization': `Bearer ${token}`
}
});
if (response.status === 401) {
console.error("Unauthorized: Your token might be expired.");
return;
}
const data = await response.json();
console.log("Protected Data:", data);
} catch (error) {
console.error("Network error:", error);
}
}