PHP stands for Hypertext Preprocessor. It is a widely-used open-source scripting language especially suited for web development and can be embedded into HTML.
PHP was originally created by Rasmus Lerdorf in 1994. It started as a set of CGI scripts written in C. Over the years, PHP evolved into a robust server-side scripting language with support for object-oriented programming, databases, and more.
On Windows: Download from https://windows.php.net/, extract, and set environment variables.
On Linux: Use package managers like apt: sudo apt install php
On Mac: Use Homebrew: brew install php
PHP scripts are run by a web server with PHP installed (like Apache). For CLI, you can execute PHP using the terminal:
<!-- Run a PHP file from terminal --> php filename.php
PHP code is written between <?php
and ?>
tags.
<!-- PHP syntax always starts with <?php and ends with ?> --> <?php // This is a single-line comment /* This is a multi-line comment */ // Use echo to print text echo "This is a basic PHP script"; ?>
This script demonstrates the use of the echo
statement to output text.
<!-- Start of PHP script --> <?php // Print "Hello World" to the output echo "Hello World"; ?>
PHP can be embedded directly into HTML documents to generate dynamic content.
<!-- A simple HTML page with embedded PHP --> <!DOCTYPE html> <html> <head> <title>PHP in HTML</title> </head> <body> <h1>Welcome</h1> <p> <?php // Insert dynamic content inside HTML echo "Today is " . date("l"); ?> </p> </body> </html>
Every PHP script starts with <?php
and ends with ?>
. This tells the server to interpret the code between these tags as PHP.
<?php // This is valid PHP code echo "PHP is running!"; ?>
PHP is case-sensitive in variables, but not in keywords like echo
.
<?php $name = "Alice"; // Variable names are case-sensitive echo $name; // Correct // echo $Name; // Incorrect, would cause an undefined variable error ?>
Each statement in PHP ends with a semicolon (;
). Missing semicolons will cause syntax errors.
<?php echo "Line one"; // Each line ends with a semicolon echo "Line two"; // Another statement ?>
PHP supports two types of single-line comments: //
and #
.
<?php // This is a single-line comment using // # This is a single-line comment using # echo "Single-line comments work!"; ?>
Multi-line comments span multiple lines using /* */
.
<?php /* This is a multi-line comment that can span several lines to explain more complex logic */ echo "Multi-line comments are useful."; ?>
PHP can be embedded within HTML to add dynamic content. The server interprets the PHP parts before sending the HTML to the browser.
<!DOCTYPE html> <html> <head><title>Embedded PHP</title></head> <body> <h1>Welcome</h1> <p> <?php // Display today's date using embedded PHP echo "Today is " . date("Y-m-d"); ?> </p> </body> </html>
Writing clean PHP code means using indentation, consistent naming, commenting where necessary, and avoiding unnecessary complexity.
<?php // Good practice: use consistent formatting and spacing $firstName = "John"; $lastName = "Doe"; // Combine names with a space $fullName = $firstName . " " . $lastName; // Output the result echo "Full name: " . $fullName; ?>
Variables in PHP are declared by using the $
symbol followed by the variable name. The variable does not have a specific type when it is declared, PHP will determine the type automatically based on the value assigned.
<!-- Declare a variable named $name --> <?php $name = "John"; // Variable holding a string value echo $name; // Output the value of $name ?>
When naming variables, the following rules apply:
$name
is different from $Name
).<!-- Valid variable names --> <?php $firstName = "Alice"; // Starts with a letter $_age = 25; // Starts with an underscore $user123 = "Bob"; // Can contain numbers echo $firstName . " " . $_age; // Output: Alice 25 ?>
Values can be assigned to variables directly using the assignment operator (=
).
<!-- Assigning different types of values --> <?php $number = 10; // Assigning an integer value $price = 20.99; // Assigning a float value $isAvailable = true; // Assigning a boolean value echo $number . " " . $price . " " . $isAvailable; // Output the values ?>
PHP provides several predefined variables such as $_GET
, $_POST
, $_SERVER
, and others that are commonly used in web development.
<!-- Example of using $_SERVER predefined variable --> <?php echo "Server Software: " . $_SERVER['SERVER_SOFTWARE']; // Output the server software info ?>
Constants are similar to variables but once set, their values cannot be changed. They can be defined using either define()
or const
.
<!-- Using define to create a constant --> <?php define("SITE_NAME", "MyWebsite"); // Define constant echo SITE_NAME; // Output the constant value ?>
PHP provides functions such as gettype()
and various is_*
functions to check the type of a variable.
<!-- Check variable type using gettype() --> <?php $var = 10; echo gettype($var); // Output: integer ?>
<!-- Use is_* functions to check types --> <?php $var = "Hello"; if (is_string($var)) { echo "It is a string"; // Check if variable is a string } ?>
In PHP, a variable can have its name determined dynamically using a variable variable.
<!-- Example of Variable Variables --> <?php $varName = "name"; // Define a variable $$varName = "John"; // Create variable $name dynamically echo $name; // Output the dynamically created variable ?>
PHP supports four scalar data types:
true
or false
.<?php // Integer type $age = 30; // Float type $price = 19.99; // String type $name = "John Doe"; // Boolean type $isActive = true; echo $age . " " . $price . " " . $name . " " . $isActive; ?>
Compound types can hold multiple values:
<?php // Array type $fruits = ["apple", "banana", "cherry"]; // Object type (using a simple class) class Car { public $brand; public $model; function __construct($brand, $model) { $this->brand = $brand; $this->model = $model; } } $myCar = new Car("Toyota", "Corolla"); echo $fruits[0]; // Accessing array element echo $myCar->brand; // Accessing object property ?>
PHP has two special types:
<?php // Null type $data = null; // Resource type (simulating database connection) $connection = fopen("file.txt", "r"); var_dump($data); var_dump($connection); ?>
Type casting is converting one data type to another. PHP provides explicit and implicit type casting.
<?php // Explicit casting (int) $str = "123.45"; $int = (int)$str; // Cast string to integer echo $int; // Output: 123 ?>
PHP automatically converts between data types in certain situations. This is called "type juggling".
<?php // Adding a string and a number $result = "10" + 5; // PHP automatically converts string to integer echo $result; // Output: 15 ?>
var_dump()
and print_r()
are used to display information about variables. var_dump()
provides more detailed information, including data type and value.
<?php $data = ["apple", "banana", "cherry"]; // var_dump: displays type and value var_dump($data); // print_r: displays only value in a readable format print_r($data); ?>
In PHP, strings can be declared using either single or double quotes. Single quotes do not parse variables or escape sequences, while double quotes do.
<!-- Single quotes --> <?php $singleQuoteString = 'Hello, $name'; // Variables won't be parsed echo $singleQuoteString; // Outputs: Hello, $name ?> <!-- Double quotes --> <?php $name = "John"; $doubleQuoteString = "Hello, $name"; // Variables will be parsed echo $doubleQuoteString; // Outputs: Hello, John ?>
The dot (.) operator is used to concatenate two or more strings together in PHP.
<?php $firstName = "John"; $lastName = "Doe"; $fullName = $firstName . " " . $lastName; // Concatenates strings echo $fullName; // Outputs: John Doe ?>
String interpolation allows you to directly include variables inside a string, but it works only with double-quoted strings.
<?php $greeting = "Hello"; $name = "Alice"; echo "$greeting, $name!"; // Outputs: Hello, Alice! ?>
HeredocNowdoc is similar, but does not parse variables.
<?php // Heredoc syntax $name = "Bob"; $heredocString = <<<EOD Hello, $name! Welcome to Heredoc. EOD; echo $heredocString; // Outputs: Hello, Bob! Welcome to Heredoc. ?> <!-- Nowdoc syntax --> $nowdocString = <<<'EOD' Hello, $name! Welcome to Nowdoc. EOD; echo $nowdocString; // Outputs: Hello, $name! Welcome to Nowdoc.
To include special characters (like quotes) inside a string, use escape sequences (backslashes).
<?php $escapedString = "He said, \"Hello, World!\""; // Escaping double quotes echo $escapedString; // Outputs: He said, "Hello, World!" ?>
PHP provides several built-in string functions. strlen() returns the length of a string, and strpos() finds the position of a substring.
<?php $string = "Hello, World!"; echo strlen($string); // Outputs: 13 (length of the string) $position = strpos($string, "World"); // Finds the position of "World" echo $position; // Outputs: 7 ?>
PHP provides the mb_* functions to handle multibyte encodings like UTF-8. Functions like mb_strlen() are used to calculate the length of multibyte strings.
<?php $mbString = "こんにちは"; // Japanese for "Hello" echo mb_strlen($mbString); // Outputs: 5 (number of characters in the string) ?>
Arithmetic operators are used to perform common mathematical operations.
<!-- Example of Arithmetic Operators --> <?php $a = 10; $b = 5; echo "Addition: " . ($a + $b); // Addition echo "<br>"; echo "Subtraction: " . ($a - $b); // Subtraction echo "<br>"; echo "Multiplication: " . ($a * $b); // Multiplication echo "<br>"; echo "Division: " . ($a / $b); // Division echo "<br>"; echo "Modulus: " . ($a % $b); // Modulus (remainder) ?>
Assignment operators are used to assign values to variables.
<!-- Example of Assignment Operators --> <?php $a = 10; // Simple assignment $a += 5; // Adds 5 to $a (equivalent to $a = $a + 5) echo "Value of a after +=: " . $a; // 15 echo "<br>"; $a -= 3; // Subtracts 3 from $a (equivalent to $a = $a - 3) echo "Value of a after -=: " . $a; // 12 echo "<br>"; ?>
Comparison operators are used to compare two values and return a boolean result.
<!-- Example of Comparison Operators --> <?php $a = 10; $b = 5; echo "Equal: " . ($a == $b); // Check if equal echo "<br>"; echo "Identical: " . ($a === $b); // Check if identical (value and type) echo "<br>"; echo "Not equal: " . ($a != $b); // Check if not equal echo "<br>"; echo "Greater than: " . ($a > $b); // Check if greater than echo "<br>"; echo "Less than: " . ($a < $b); // Check if less than ?>
Logical operators are used to perform logical operations on expressions.
<!-- Example of Logical Operators --> <?php $a = true; $b = false; echo "AND: " . ($a && $b); // AND operation (true if both are true) echo "<br>"; echo "OR: " . ($a || $b); // OR operation (true if either is true) echo "<br>"; echo "NOT: " . (!$a); // NOT operation (true if $a is false) ?>
Increment and decrement operators are used to increase or decrease a variable by one.
<!-- Example of Increment and Decrement --> <?php $a = 10; echo "Pre-increment: " . ++$a; // Increment before use echo "<br>"; echo "Post-increment: " . $a++; // Increment after use echo "<br>"; echo "Value after post-increment: " . $a; // Value after increment echo "<br>"; $b = 5; echo "Pre-decrement: " . --$b; // Decrement before use echo "<br>"; echo "Post-decrement: " . $b--; // Decrement after use echo "<br>"; echo "Value after post-decrement: " . $b; // Value after decrement ?>
The ternary operator is a shorthand for if-else
statements. The null coalescing operator is used to return the value if it is not null.
<!-- Example of Ternary and Null Coalescing --> <?php $a = 10; $result = ($a > 5) ? "Greater" : "Smaller"; // Ternary operator echo "Ternary result: " . $result; // "Greater" echo "<br>"; $b = null; $value = $b ?? "Default value"; // Null Coalescing Operator echo "Null Coalescing result: " . $value; // "Default value" ?>
Bitwise operators are used to perform operations on the binary representations of numbers.
<!-- Example of Bitwise Operators --> <?php $a = 6; // Binary: 110 $b = 3; // Binary: 011 echo "AND: " . ($a & $b); // Bitwise AND echo "<br>"; echo "OR: " . ($a | $b); // Bitwise OR echo "<br>"; echo "XOR: " . ($a ^ $b); // Bitwise XOR echo "<br>"; echo "NOT: " . ~$a; // Bitwise NOT ?>
The if
statement evaluates a condition and runs a block of code if the condition is true.
<?php $age = 18; if ($age >= 18) { echo "You are an adult."; } ?>
The else
statement runs if the if
condition is false, and the elseif
statement allows for additional conditions.
<?php $age = 16; if ($age >= 18) { echo "You are an adult."; } elseif ($age >= 13) { echo "You are a teenager."; } else { echo "You are a child."; } ?>
Conditions can be nested within other conditions for more complex decision-making.
<?php $age = 25; $isStudent = true; if ($age >= 18) { if ($isStudent) { echo "You are an adult student."; } else { echo "You are an adult."; } } else { echo "You are a minor."; } ?>
The switch
statement is an alternative to multiple if
conditions. It compares a variable against multiple values.
<?php $day = "Monday"; switch ($day) { case "Monday": echo "Start of the week!"; break; case "Friday": echo "Almost weekend!"; break; default: echo "Midweek days."; } ?>
The match
expression, introduced in PHP 8, provides a more powerful alternative to switch
.
<?php $day = "Monday"; match ($day) { "Monday" => echo "Start of the week!", "Friday" => echo "Almost weekend!", default => echo "Midweek days." }; ?>
It's important to keep conditional statements clear, use else if
for multiple conditions, and ensure that the conditions are logically ordered.
<?php $age = 30; $income = 45000; // Best practice: Keep conditions readable if ($age >= 18) { if ($income > 30000) { echo "You qualify for the premium service."; } else { echo "You qualify for the standard service."; } } else { echo "You do not qualify for any service."; } ?>
The while
loop is used to execute a block of code as long as the specified condition evaluates to true.
<!-- Example of while loop --> <?php $i = 1; // Initializing the variable while ($i <= 5) { // Condition to check echo $i . "<br>"; // Output the value of $i $i++; // Increment the value of $i } ?>
The do...while
loop will execute the block of code at least once before checking the condition.
<!-- Example of do...while loop --> <?php $i = 1; do { echo $i . "<br>"; // Output the value of $i $i++; // Increment the value of $i } while ($i <= 5); // Condition to check ?>
The for
loop is used when you know beforehand how many times you want to execute a statement or a block of code.
<!-- Example of for loop --> <?php for ($i = 1; $i <= 5; $i++) { // Initialize $i, check condition, increment echo $i . "<br>"; // Output the value of $i } ?>
The foreach
loop is used to iterate over arrays. It is specifically designed for working with arrays in PHP.
<!-- Example of foreach loop --> <?php $arr = array(1, 2, 3, 4, 5); // Declare an array foreach ($arr as $value) { // Iterate over each value in the array echo $value . "<br>"; // Output each value } ?>
Both break
and continue
are used to control the flow of a loop:
break
: Exits the loop immediately.continue
: Skips the current iteration and moves to the next iteration of the loop.<!-- Example of break and continue --> <?php for ($i = 1; $i <= 10; $i++) { if ($i == 5) { break; // Break the loop when $i is 5 } if ($i == 3) { continue; // Skip the iteration when $i is 3 } echo $i . "<br>"; // Output $i } ?>
A nested loop is a loop inside another loop. The inner loop will be executed one time for each iteration of the outer loop.
<!-- Example of nested loops --> <?php for ($i = 1; $i <= 3; $i++) { // Outer loop for ($j = 1; $j <= 3; $j++) { // Inner loop echo "($i, $j) "; // Output the values of $i and $j } echo "<br>"; // New line after each iteration of outer loop } ?>
You can use loops to iterate over array elements. The foreach
loop is the most common for array iteration, but other loops like for
and while
can also be used.
<!-- Loop through an associative array using foreach --> <?php $person = array("name" => "Alice", "age" => 25, "city" => "New York"); // Associative array foreach ($person as $key => $value) { // Iterate through key-value pairs echo $key . ": " . $value . "<br>"; // Output each key-value pair } ?>
Indexed arrays are arrays that use numerical indexes starting from 0.
<?php // Declare an indexed array $fruits = ["apple", "banana", "cherry"]; // Accessing array elements using indexes echo $fruits[0]; // Output: apple ?>
Associative arrays are arrays where each element is assigned a key, which can be a string or an integer.
<?php // Declare an associative array $person = [ "name" => "John", "age" => 25, "city" => "New York" ]; // Accessing array elements using keys echo $person["name"]; // Output: John ?>
Multidimensional arrays are arrays that contain other arrays as elements. These can be two-dimensional (like matrices) or more.
<?php // Declare a multidimensional array $students = [ ["name" => "Alice", "age" => 22, "grade" => "A"], ["name" => "Bob", "age" => 23, "grade" => "B"], ["name" => "Charlie", "age" => 24, "grade" => "C"] ]; // Accessing elements of the multidimensional array echo $students[0]["name"]; // Output: Alice ?>
Arrays can be declared using the array()
function or shorthand syntax. Array elements can be accessed using their indexes or keys.
<?php // Array declaration using the array() function $colors = array("red", "green", "blue"); // Accessing array elements echo $colors[1]; // Output: green ?>
Arrays can be modified by adding, updating, or removing elements.
<?php // Declare an indexed array $fruits = ["apple", "banana", "cherry"]; // Adding an element to the array $fruits[] = "orange"; // Updating an element in the array $fruits[1] = "grape"; // Removing an element from the array unset($fruits[0]); // Display the modified array print_r($fruits); // Output: Array ( [0] => grape [1] => cherry [2] => orange ) ?>
Arrays can be iterated using loops like foreach
, for
, or while
.
<?php // Declare an indexed array $fruits = ["apple", "banana", "cherry"]; // Iterating with foreach loop foreach ($fruits as $fruit) { echo $fruit . " "; // Output: apple banana cherry } ?>
PHP 7.1 introduced array destructuring, allowing you to extract elements from arrays directly into variables.
<?php // Declare an indexed array $person = ["John", 25, "New York"]; // Destructuring the array into variables list($name, $age, $city) = $person; echo $name . " is " . $age . " years old and lives in " . $city . "."; // Output: John is 25 years old and lives in New York. ?>
count() returns the number of elements in an array. array_push() adds one or more elements to the end of an array. array_pop() removes the last element of an array.
<?php // count() function $fruits = ["apple", "banana", "cherry"]; echo count($fruits); // Outputs: 3 // array_push() function array_push($fruits, "orange"); // Adds "orange" to the array print_r($fruits); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry [3] => orange ) // array_pop() function array_pop($fruits); // Removes "orange" from the array print_r($fruits); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry ) ?>
array_merge() merges one or more arrays into a single array. array_combine() creates an array by using one array for keys and another for values.
<?php // array_merge() function $array1 = ["apple", "banana"]; $array2 = ["cherry", "date"]; $mergedArray = array_merge($array1, $array2); // Merges both arrays print_r($mergedArray); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry [3] => date ) // array_combine() function $keys = ["name", "age"]; $values = ["John", 30]; $combinedArray = array_combine($keys, $values); // Combines keys and values into an associative array print_r($combinedArray); // Outputs: Array ( [name] => John [age] => 30 ) ?>
array_slice() extracts a portion of an array without affecting the original array. array_splice() removes and optionally replaces elements of an array.
<?php // array_slice() function $array = [1, 2, 3, 4, 5]; $slice = array_slice($array, 1, 3); // Extracts elements starting from index 1, length 3 print_r($slice); // Outputs: Array ( [0] => 2 [1] => 3 [2] => 4 ) // array_splice() function array_splice($array, 1, 2, ["a", "b"]); // Replaces 2 elements starting from index 1 with "a" and "b" print_r($array); // Outputs: Array ( [0] => 1 [1] => a [2] => b [3] => 4 [4] => 5 ) ?>
in_array() checks if a value exists in an array, and array_search() returns the key of the first occurrence of a value in an array.
<?php // in_array() function $numbers = [1, 2, 3, 4, 5]; echo in_array(3, $numbers) ? "Found" : "Not Found"; // Outputs: Found // array_search() function $key = array_search(4, $numbers); // Finds the index of value 4 echo $key; // Outputs: 3 ?>
PHP provides a variety of sorting functions. For example, sort() sorts an array in ascending order, and rsort() sorts it in descending order.
<?php $numbers = [5, 3, 8, 1, 2]; sort($numbers); // Sorts the array in ascending order print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 [4] => 8 ) rsort($numbers); // Sorts the array in descending order print_r($numbers); // Outputs: Array ( [0] => 8 [1] => 5 [2] => 3 [3] => 2 [4] => 1 ) ?>
array_filter() filters an array using a callback function, and array_map() applies a callback function to the elements of an array.
<?php // array_filter() function $numbers = [1, 2, 3, 4, 5]; $evenNumbers = array_filter($numbers, function($num) { return $num % 2 == 0; }); print_r($evenNumbers); // Outputs: Array ( [1] => 2 [3] => 4 ) // array_map() function $squaredNumbers = array_map(function($num) { return $num * $num; }, $numbers); print_r($squaredNumbers); // Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 ) ?>
array_keys() returns all the keys of an array, and array_values() returns all the values.
<?php $array = ["a" => "apple", "b" => "banana", "c" => "cherry"]; // array_keys() function print_r(array_keys($array)); // Outputs: Array ( [0] => a [1] => b [2] => c ) // array_values() function print_r(array_values($array)); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry ) ?>
Functions are declared using the function
keyword, followed by the function name and a pair of parentheses for parameters.
<!-- Example of Declaring a Function --> <?php function greet() { echo "Hello, World!"; } greet(); // Call the function ?>
Functions can accept parameters, which are variables that hold values passed to the function. These values are known as arguments.
<!-- Example of Parameters and Arguments --> <?php function greet($name) { echo "Hello, " . $name . "!"; } greet("Alice"); // Pass the argument "Alice" ?>
Functions can return values using the return
keyword. The returned value can be used in other parts of the code.
<!-- Example of Return Values --> <?php function add($a, $b) { return $a + $b; } $result = add(3, 4); // Store the returned value in a variable echo "The sum is: " . $result; ?>
Functions can have default parameter values. If the caller does not pass an argument for that parameter, the default value is used.
<!-- Example of Default Parameters --> <?php function greet($name = "Guest") { echo "Hello, " . $name . "!"; } greet(); // No argument, so the default is used echo "<br>"; greet("Bob"); // Argument passed, default is ignored ?>
PHP allows functions to accept an arbitrary number of arguments using the ...
syntax. These arguments are passed as an array.
<!-- Example of Variable-length Arguments --> <?php function sum(...$numbers) { return array_sum($numbers); } echo "The sum is: " . sum(1, 2, 3, 4, 5); // Pass a variable number of arguments ?>
Anonymous functions (also called closures) are functions that do not have a name. They are often used as arguments to other functions.
<!-- Example of Anonymous Functions --> <?php $greet = function($name) { echo "Hello, " . $name . "!"; }; $greet("Charlie"); // Call the anonymous function ?>
Arrow functions, introduced in PHP 7.4, provide a shorter syntax for anonymous functions. They automatically capture variables from the surrounding scope.
<!-- Example of Arrow Functions --> <?php $multiply = fn($a, $b) => $a * $b; // Short syntax for anonymous function echo "The product is: " . $multiply(3, 4); ?>
The $_GET
superglobal is used to collect form data after submitting an HTML form with method="get". It is also used to pass variables through URL parameters.
<!-- Example using $_GET --> <?php // Retrieve the value passed via the URL $name = $_GET['name']; // The 'name' parameter from the URL echo "Hello, " . $name; // Output the value of the 'name' parameter ?>
example.com?name=John
, the output will be:The $_POST
superglobal is used to collect form data after submitting a form with method="post". It is more secure than $_GET
as the data is not visible in the URL.
<!-- Example using $_POST --> <form method="post"> Name: <input type="text" name="name"><br> <input type="submit" value="Submit"> </form> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name']; // Collect form data from the 'name' input echo "Hello, " . $name; // Output the value of 'name' } ?>
The $_REQUEST
superglobal collects data from both $_GET
and $_POST
. It is a general-purpose variable for fetching user input.
<!-- Example using $_REQUEST --> <form method="post"> Name: <input type="text" name="name"><br> <input type="submit" value="Submit"> </form> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_REQUEST['name']; // Collect data from POST request echo "Hello, " . $name; // Output the value of 'name' } ?>
The $_SERVER
superglobal contains information about the server environment and the current request, such as the current script name, headers, and more.
<!-- Example using $_SERVER --> <?php echo $_SERVER['SERVER_NAME']; // Displays the server's host name echo $_SERVER['REQUEST_METHOD']; // Displays the request method (GET or POST) ?>
The $_SESSION
superglobal is used to store session variables. $_COOKIE
is used to store small pieces of data in the client's browser.
<!-- Example using $_SESSION --> <?php session_start(); // Start a session $_SESSION['username'] = 'JohnDoe'; // Store session data echo $_SESSION['username']; // Retrieve session data ?>
<!-- Example using $_COOKIE --> <?php // Set a cookie (expires in 1 hour) setcookie('user', 'Alice', time() + 3600); // Retrieve the cookie if(isset($_COOKIE['user'])) { echo "Hello, " . $_COOKIE['user']; } ?>
The $_FILES
superglobal is used to upload files via a form. It contains information about the file uploaded.
<!-- Example using $_FILES --> <form method="post" enctype="multipart/form-data"> Choose a file to upload: <input type="file" name="file"><br> <input type="submit" value="Upload"> </form> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_FILES['file'])) { echo "File name: " . $_FILES['file']['name']; // Get file name } } ?>
$_ENV
contains environment variables, and $_GLOBALS
contains all global variables, including those from the current script.
<!-- Example using $_ENV --> <?php // Retrieve an environment variable (if set) echo getenv('PATH'); // Output system PATH variable ?>
<!-- Example using $_GLOBALS --> <?php $x = 10; // Global variable echo $GLOBALS['x']; // Access global variable using $_GLOBALS ?>
HTML forms allow users to input data that can be sent to the server for processing. Here’s an example of a basic form:
<!-- HTML form to submit user data --> <form action="process.php" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" required><br> <label for="email">Email:</label> <input type="email" id="email" name="email" required><br> <input type="submit" value="Submit"> </form>
Once the form is submitted, the data can be accessed using the $_POST
superglobal array in PHP:
<!-- PHP script to receive data via $_POST --> <?php // Access form data sent via POST $name = $_POST['name']; $email = $_POST['email']; echo "Name: " . $name . "<br>"; echo "Email: " . $email; ?>
To prevent security risks such as XSS (Cross-Site Scripting), it’s important to sanitize user input using htmlspecialchars()
:
<!-- PHP script to sanitize user input --> <?php // Sanitize user input to prevent XSS attacks $name = htmlspecialchars($_POST['name']); $email = htmlspecialchars($_POST['email']); echo "Name: " . $name . "<br>"; echo "Email: " . $email; ?>
Form validation ensures that the data submitted is correct. Basic validation checks can be done before sending data to the server:
<!-- PHP script for form validation --> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if name and email are empty if (empty($_POST["name"]) || empty($_POST["email"])) { echo "Both fields are required!"; } else { echo "Form is valid"; } } ?>
The filter_input()
function can be used to filter and validate user input, improving security:
<!-- PHP script using filter_input() to validate email --> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Validate email using filter_input() $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); if ($email) { echo "Valid email: " . $email; } else { echo "Invalid email format!"; } } ?>
Required fields can be easily enforced in both HTML and PHP. Here’s an example:
<!-- HTML form with required attribute --> <form action="process.php" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" required><br> <label for="email">Email:</label> <input type="email" id="email" name="email" required><br> <input type="submit" value="Submit"> </form>
It’s important to display errors when validation fails. Here’s an example of error display:
<!-- PHP script to display validation errors --> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"]) || empty($_POST["email"])) { echo "Both fields are required!<br>"; } else { echo "Form is valid!<br>"; } } ?>
The fopen() function is used to open a file. It takes two parameters: the file name and the mode (e.g., read, write).
<!-- Open a file in read mode --> <?php // Open the file for reading $file = fopen("example.txt", "r"); // 'r' is for read mode if ($file) { echo "File opened successfully!"; } else { echo "Unable to open file."; } fclose($file); // Always close the file ?>
You can read files using the fread() or fgets() functions. fread() reads the entire file, while fgets() reads one line at a time.
<!-- Reading a file with fread() --> <?php $file = fopen("example.txt", "r"); if ($file) { // Read the entire file $content = fread($file, filesize("example.txt")); echo $content; fclose($file); } ?>
<!-- Reading a file line by line with fgets() --> <?php $file = fopen("example.txt", "r"); if ($file) { while (($line = fgets($file)) !== false) { echo $line . "<br>"; } fclose($file); } ?>
The fwrite() function is used to write data to a file. If the file does not exist, it will be created (if the mode allows it).
<!-- Writing to a file --> <?php $file = fopen("example.txt", "w"); // 'w' mode for writing if ($file) { fwrite($file, "This is some text written to the file."); fclose($file); echo "Data written successfully!"; } else { echo "Unable to open file for writing."; } ?>
To handle file uploads in PHP, you need to use the $_FILES
superglobal array. Below is an example of uploading a file via an HTML form.
<!-- HTML Form for file upload --> <form action="upload.php" method="post" enctype="multipart/form-data"> Select file to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload File" name="submit"> </form>
PHP Script to handle file upload:
<!-- PHP file upload script --> <?php if (isset($_FILES['fileToUpload'])) { $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>
The unlink() function is used to delete a file.
<!-- Delete a file --> <?php if (unlink("example.txt")) { echo "File deleted successfully!"; } else { echo "Error deleting file."; } ?>
The file_exists() function checks if a file or directory exists. The is_file() function checks if the path is a file.
<!-- Check if a file exists --> <?php if (file_exists("example.txt")) { echo "File exists!"; } else { echo "File does not exist."; } ?>
<!-- Check if path is a file --> <?php if (is_file("example.txt")) { echo "It is a file!"; } else { echo "It is not a file."; } ?>
PHP allows you to check and change file permissions using functions like chmod() and fileperms().
<!-- Changing file permissions --> <?php chmod("example.txt", 0755); // Set file permissions to rwxr-xr-x echo "Permissions changed successfully!"; ?>
In PHP, sessions are started using the session_start()
function. This function must be called at the very beginning of your script, before any HTML output.
<!-- Start a session at the beginning of the PHP script --> <?php // Start the session session_start(); ?>
After starting a session, you can store data in the $_SESSION
superglobal array. To retrieve the data, you simply access the array by the key.
<!-- Store and retrieve session variables --> <?php session_start(); // Start the session // Store a value in the session $_SESSION["username"] = "JohnDoe"; // Retrieve and display the session value echo "Hello, " . $_SESSION["username"]; ?>
To destroy a session, use session_destroy()
. However, to fully remove all session variables, you should also unset them using unset()
.
<!-- Destroy a session and remove session variables --> <?php session_start(); // Start the session // Unset all session variables session_unset(); // Destroy the session session_destroy(); echo "Session destroyed."; ?>
Cookies are small pieces of data stored in the user's browser. You can set cookies using the setcookie()
function, and you can access their values using the $_COOKIE
superglobal.
<!-- Create and read cookies in PHP --> <?php // Set a cookie that expires in 1 hour setcookie("user", "JaneDoe", time() + 3600, "/"); // Check if the cookie exists and display it if(isset($_COOKIE["user"])) { echo "Welcome back, " . $_COOKIE["user"]; } else { echo "Cookie not set."; } ?>
When setting cookies, you can specify an expiration time. The time is set in Unix timestamp format (seconds since January 1, 1970). To make a cookie expire after a certain period, you adjust this time.
<!-- Set a cookie that expires in 30 days --> <?php // Set cookie to expire in 30 days setcookie("userPreference", "darkMode", time() + (30 * 24 * 60 * 60), "/"); // 30 days echo "Cookie set for 30 days."; ?>
To delete a cookie, you must set its expiration date to a time in the past.
<!-- Delete a cookie by setting its expiration time to the past --> <?php // Delete the "user" cookie by setting its expiration time in the past setcookie("user", "", time() - 3600, "/"); echo "Cookie deleted."; ?>
To enhance security, use secure and HttpOnly flags when working with cookies. Also, always use session_regenerate_id()
to avoid session fixation attacks.
<!-- Secure session practice example --> <?php session_start(); // Start the session // Regenerate session ID to prevent session fixation session_regenerate_id(true); // Set secure cookie with HttpOnly and Secure flags setcookie("secureCookie", "secureValue", time() + 3600, "/", "", true, true); // Secure and HttpOnly echo "Secure session practices applied."; ?>
A class in PHP is a blueprint for creating objects. It defines the properties and methods that the objects created from the class will have.
<!-- Define a simple class --> <?php class Car { // Property of the class public $make; public $model; // Constructor to initialize properties public function __construct($make, $model) { $this->make = $make; $this->model = $model; } // Method of the class public function displayInfo() { return "Make: " . $this->make . ", Model: " . $this->model; } } ?>
Objects are instances of a class. You can create an object using the new keyword, which calls the constructor method of the class.
<!-- Create an object from the Car class --> <?php // Create an object of the Car class $car1 = new Car("Toyota", "Corolla"); // Accessing method to display info echo $car1->displayInfo(); ?>
Constructors are special methods that run automatically when an object is created. They are used to initialize the object's properties. Destructors are called when an object is destroyed, typically when the script ends or the object goes out of scope.
<!-- Class with constructor and destructor --> <?php class Book { public $title; // Constructor to initialize title public function __construct($title) { $this->title = $title; echo "Book '$title' created.
"; } // Destructor to indicate object destruction public function __destruct() { echo "Book '$this->title' is being destroyed.
"; } } // Create Book object $book1 = new Book("PHP for Beginners"); ?>
Properties are variables that belong to a class, and methods are functions that belong to a class. These define the characteristics and behaviors of objects created from the class.
<!-- Class with properties and methods --> <?php class Animal { // Property public $name; // Constructor public function __construct($name) { $this->name = $name; } // Method public function speak() { echo $this->name . " makes a sound.
"; } } // Create an object $dog = new Animal("Dog"); $dog->speak(); // Calling the method ?>
The $this keyword refers to the current object in a class. It is used to access the object's properties and methods.
<!-- Using $this keyword --> <?php class Person { public $name; public function __construct($name) { $this->name = $name; } // Method using $this to access the property public function greet() { echo "Hello, " . $this->name . "!"; } } // Create object and call method $person1 = new Person("John"); $person1->greet(); ?>
In PHP, properties and methods can have different visibility levels:
<!-- Example with visibility levels --> <?php class Employee { // Public property public $name; // Private property private $salary; // Protected property protected $position; // Constructor public function __construct($name, $salary, $position) { $this->name = $name; $this->salary = $salary; $this->position = $position; } // Method to display public property public function displayInfo() { echo "Employee: " . $this->name . "
"; } // Method to access private property public function getSalary() { return $this->salary; } } // Create object $emp = new Employee("Alice", 50000, "Developer"); $emp->displayInfo(); // Accessing public method echo "Salary: " . $emp->getSalary(); ?>
Inheritance allows a class to inherit methods and properties from another class.
<?php class Animal { public $name; public function __construct($name) { $this->name = $name; } public function speak() { return $this->name . " makes a sound"; } } class Dog extends Animal { public function speak() { return $this->name . " barks"; } } $dog = new Dog("Buddy"); echo $dog->speak(); // Output: Buddy barks ?>
Method overriding allows a subclass to provide its own implementation of a method defined in its parent class.
<?php class Vehicle { public function start() { return "Vehicle started"; } } class Car extends Vehicle { // Overriding the start method public function start() { return "Car started"; } } $car = new Car(); echo $car->start(); // Output: Car started ?>
Abstract classes cannot be instantiated directly and are used to define methods that must be implemented by subclasses.
<?php abstract class Shape { abstract public function area(); // Abstract method } class Circle extends Shape { public $radius; public function __construct($radius) { $this->radius = $radius; } public function area() { return pi() * pow($this->radius, 2); } } $circle = new Circle(5); echo $circle->area(); // Output: 78.539816339744 ?>
Interfaces define methods that a class must implement but cannot provide the implementation.
<?php interface Payable { public function pay($amount); } class Employee implements Payable { public function pay($amount) { return "Paid $" . $amount; } } $employee = new Employee(); echo $employee->pay(100); // Output: Paid $100 ?>
Traits are a way to reuse code in multiple classes without inheritance. They help avoid issues with multiple inheritance.
<?php trait Logger { public function log($message) { return "Log: " . $message; } } class Application { use Logger; // Using the trait } $app = new Application(); echo $app->log("System started"); // Output: Log: System started ?>
Namespaces are used to organize code into logical groups and avoid name collisions in larger applications.
<?php namespace Vehicles; class Car { public function drive() { return "Car is driving"; } } namespace Animals; class Dog { public function bark() { return "Dog barks"; } } $car = new \Vehicles\Car(); echo $car->drive(); // Output: Car is driving ?>
Autoloading allows PHP to automatically include classes when they are needed, avoiding the need for explicit include or require statements.
<?php spl_autoload_register(function ($class_name) { include $class_name . '.class.php'; }); // Assuming the class "Car" is defined in "Car.class.php" $car = new Car(); $car->drive(); // Output: Car is driving ?>
In PHP, errors can be categorized into four types:
PHP provides a try-catch-finally
block to handle exceptions:
<!-- Example using try, catch, and finally --> <?php try { // Code that might throw an exception $num = 5; if ($num > 0) { throw new Exception("This is an exception"); } } catch (Exception $e) { // Exception handling code echo "Caught exception: " . $e->getMessage(); } finally { // Code that runs regardless of an exception echo "<br>Finally block executed."; } ?>
In PHP, exceptions can be thrown using the throw
keyword. An exception is an object that inherits from the Exception
class.
<!-- Example of throwing an exception --> <?php function checkNumber($num) { if ($num > 0) { throw new Exception("Number must be negative."); } return $num; } try { checkNumber(1); } catch (Exception $e) { echo "Caught exception: " . $e->getMessage(); } ?>
You can create custom exception classes by extending the built-in Exception
class. This allows for specialized exception handling.
<!-- Example of custom exception class --> <?php class CustomException extends Exception { public function errorMessage() { return "Custom error: " . $this->getMessage(); } } try { throw new CustomException("This is a custom exception."); } catch (CustomException $e) { echo $e->errorMessage(); } ?>
The error_reporting()
function sets the level of error reporting in PHP. You can choose which types of errors to report by using predefined constants.
<!-- Example of using error_reporting() --> <?php // Report all errors except notices error_reporting(E_ALL & ~E_NOTICE); // Example of notice that won't be shown $var; ?>
PHP provides error logging functionality, which can be enabled using ini_set()
and error_log()
. Logs can be written to a file or sent via email.
<!-- Example of error logging --> <?php ini_set("log_errors", 1); // Enable error logging ini_set("error_log", "/path/to/php-error.log"); // Set log file // Generate an error trigger_error("This is a custom error message.", E_USER_NOTICE); ?>
The first step in working with a MySQL database in PHP is to establish a connection using the MySQLi extension.
<!-- PHP code to connect to the database --> <?php // Create connection $conn = new mysqli("localhost", "username", "password", "database_name"); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
Once connected to the database, you can create tables using SQL commands.
<!-- PHP code to create a table --> <?php // SQL query to create a table $sql = "CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table Users created successfully"; } else { echo "Error creating table: " . $conn->error; } ?>
You can insert data into a table using SQL INSERT INTO
queries.
<!-- PHP code to insert data into the table --> <?php $sql = "INSERT INTO Users (firstname, lastname, email) VALUES ('John', 'Doe', 'john.doe@example.com')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "
" . $conn->error; } ?>
Data can be retrieved from the database using SELECT
queries.
<!-- PHP code to select data from the table --> <?php $sql = "SELECT id, firstname, lastname FROM Users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // Output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; } ?>
You can update or delete data from the table using UPDATE
and DELETE
SQL commands.
<!-- PHP code to update a record --> <?php $sql = "UPDATE Users SET email='newemail@example.com' WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } ?>
<!-- PHP code to delete a record --> <?php $sql = "DELETE FROM Users WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } ?>
The mysqli_fetch_assoc()
function fetches a result row as an associative array.
<!-- PHP code using mysqli_fetch_assoc() --> <?php $sql = "SELECT id, firstname, lastname FROM Users"; $result = $conn->query($sql); while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } ?>
After performing all database operations, it's essential to close the database connection.
<!-- PHP code to close the connection --> <?php $conn->close(); ?>
PDO (PHP Data Objects) is a database access layer providing a uniform method of access to multiple databases. It does not provide database abstraction but allows for a uniform and secure way of interacting with databases.
To connect to a database using PDO, use the new PDO()
constructor. The connection string format is "mysql:host=localhost;dbname=test"
for MySQL.
<?php try { // Connect to MySQL database $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'password'); // Set PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully!"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
Prepared statements are used to execute SQL queries securely and efficiently. They help prevent SQL injection by separating SQL logic from data.
<?php // Prepare a query to insert data $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)"); // Bind parameters $stmt->bindParam(':name', $name); $stmt->bindParam(':email', $email); // Assign values to the parameters $name = 'John Doe'; $email = 'johndoe@example.com'; // Execute the statement $stmt->execute(); echo "Record inserted successfully!"; ?>
In PDO, parameters can be bound to placeholders in the SQL query. You can bind parameters by name or position.
<?php // Prepare a query to select data $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email"); // Bind the parameter $stmt->bindParam(':email', $email); // Assign value to parameter $email = 'johndoe@example.com'; // Execute the query $stmt->execute(); // Fetch the results $result = $stmt->fetch(PDO::FETCH_ASSOC); print_r($result); ?>
PDO supports various fetch methods to retrieve results from a query. Common methods include fetch()
and fetchAll()
.
<?php // Fetch all records from the users table $stmt = $pdo->query("SELECT * FROM users"); // Fetch all results as an associative array $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Display the results foreach ($results as $row) { echo $row['name'] . " - " . $row['email'] . "<br>"; } ?>
Error handling in PDO is typically done using exceptions. The setAttribute()
method is used to set the error mode to throw exceptions on error.
<?php try { // Intentional error: incorrect table name $stmt = $pdo->query("SELECT * FROM non_existent_table"); } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } ?>
PDO supports database transactions, allowing you to execute multiple queries as a single unit. This ensures data consistency. Use beginTransaction()
, commit()
, and rollBack()
.
<?php try { // Begin transaction $pdo->beginTransaction(); // Insert a record $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)"); $stmt->execute([':name' => 'Mark', ':email' => 'mark@example.com']); // Simulate a second insert $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)"); $stmt->execute([':name' => 'Anna', ':email' => 'anna@example.com']); // Commit the transaction $pdo->commit(); echo "Transaction successful!"; } catch (PDOException $e) { // Rollback if error occurs $pdo->rollBack(); echo "Error: " . $e->getMessage(); } ?>
An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other. It defines methods and data structures for requesting and exchanging information between systems.
In PHP, we use json_encode()
to convert PHP data into JSON format and json_decode()
to convert JSON back to PHP data.
<?php // PHP array $data = array("name" => "John", "age" => 30); // Convert array to JSON format $jsonData = json_encode($data); echo $jsonData; // {"name":"John","age":30} // Convert JSON back to PHP array $decodedData = json_decode($jsonData, true); print_r($decodedData); // Array ( [name] => John [age] => 30 ) ?>
The file_get_contents()
function in PHP allows you to read the contents of a file or URL into a string. It's often used to fetch data from APIs.
<?php // Fetch data from an API $jsonData = file_get_contents("https://api.example.com/data"); // Decode the JSON response $data = json_decode($jsonData, true); // Output the data print_r($data); ?>
cURL
is a library in PHP that allows you to make HTTP requests. It's more powerful and flexible than file_get_contents()
and is commonly used for interacting with APIs.
<?php // Initialize cURL session $ch = curl_init(); // Set cURL options curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL request and get the response $response = curl_exec($ch); // Close the cURL session curl_close($ch); // Decode JSON response $data = json_decode($response, true); // Output the data print_r($data); ?>
You can send data (such as JSON) to an API using cURL
by setting appropriate cURL options, such as CURLOPT_POST
for POST requests.
<?php // Initialize cURL session $ch = curl_init(); // Set cURL options for sending data curl_setopt($ch, CURLOPT_URL, "https://api.example.com/submit"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["name" => "John", "age" => 30])); // Set the Content-Type header to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); // Execute cURL request and get the response $response = curl_exec($ch); // Close the cURL session curl_close($ch); // Output the response echo $response; ?>
REST APIs allow you to interact with web services using standard HTTP methods like GET, POST, PUT, and DELETE. You can consume REST APIs by sending HTTP requests to the server and processing the responses.
<?php // Initialize cURL session $ch = curl_init(); // Set cURL options for a GET request curl_setopt($ch, CURLOPT_URL, "https://api.example.com/records"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL request and get the response $response = curl_exec($ch); // Close the cURL session curl_close($ch); // Decode the JSON response $data = json_decode($response, true); // Output the data print_r($data); ?>
You can create your own API endpoint by writing a PHP script that handles HTTP requests and returns a response in JSON format.
<?php header('Content-Type: application/json'); // Sample data $data = array("status" => "success", "message" => "API is working!"); // Encode data as JSON and send response echo json_encode($data); ?>
This is the form used to upload files. It uses the enctype="multipart/form-data"
attribute to specify that the form can send files.
<!-- HTML Form to upload a file --> <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Choose file to upload:Handling $_FILES
The
$_FILES
array is used to access the uploaded files in PHP. Each element of the array holds information about the uploaded file, such as its name, type, temporary location, and size.<!-- PHP script to handle file upload --> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_FILES["file"])) { $fileName = $_FILES["file"]["name"]; // Get file name $fileTmpName = $_FILES["file"]["tmp_name"]; // Get temp name echo "File Name: " . $fileName . "<br>"; // Display file name } } ?>File Name: example.jpg
Moving Uploaded Files
Once a file is uploaded, it is stored in a temporary location. You can move it to a permanent location using
move_uploaded_file()
.<!-- PHP script to move uploaded file --> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_FILES["file"])) { $fileTmpName = $_FILES["file"]["tmp_name"]; $fileName = $_FILES["file"]["name"]; $uploadDirectory = "uploads/"; // Directory to move file if (move_uploaded_file($fileTmpName, $uploadDirectory . $fileName)) { echo "File has been uploaded successfully!<br>"; } else { echo "Error uploading file.<br>"; } } } ?>File has been uploaded successfully!
File Size Validation
File size can be validated using the
$_FILES
array'ssize
property. It's a good idea to limit the maximum allowed file size to avoid uploading very large files.<!-- PHP script to validate file size --> <?php $maxSize = 2000000; // Maximum file size (2MB) if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_FILES["file"])) { $fileSize = $_FILES["file"]["size"]; if ($fileSize > $maxSize) { echo "File is too large. Maximum allowed size is 2MB.<br>"; } else { echo "File size is acceptable.<br>"; } } } ?>File size is acceptable.
Allowed File Types
You can restrict the types of files that can be uploaded by checking the
$_FILES
array'stype
property. For example, you may only allow image files.<!-- PHP script to check allowed file types --> <?php $allowedTypes = ["image/jpeg", "image/png", "image/gif"]; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_FILES["file"])) { $fileType = $_FILES["file"]["type"]; if (in_array($fileType, $allowedTypes)) { echo "File type is allowed.<br>"; } else { echo "Invalid file type. Only JPG, PNG, and GIF are allowed.<br>"; } } } ?>File type is allowed.
Display Uploaded Files
Once files are uploaded, you can display them on the page using HTML and PHP.
<!-- PHP script to display uploaded image --> <?php $uploadDirectory = "uploads/"; $fileName = "example.jpg"; // Assume file was uploaded if (file_exists($uploadDirectory . $fileName)) { echo "<img src='" . $uploadDirectory . $fileName . "' alt='Uploaded File' /><br>"; } ?><img src="uploads/example.jpg" alt="Uploaded File" />
Securing File Uploads
It's important to secure file uploads to avoid security risks. Always validate the file type, size, and use proper file names to prevent overwriting files or executing malicious code.
<!-- PHP script to secure file upload --> <?php $allowedTypes = ["image/jpeg", "image/png", "image/gif"]; $maxSize = 2000000; // Max size 2MB $uploadDirectory = "uploads/"; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_FILES["file"])) { $fileTmpName = $_FILES["file"]["tmp_name"]; $fileName = $_FILES["file"]["name"]; $fileType = $_FILES["file"]["type"]; $fileSize = $_FILES["file"]["size"]; // Check if the file type is allowed if (!in_array($fileType, $allowedTypes)) { echo "Invalid file type.<br>"; } // Check file size elseif ($fileSize > $maxSize) { echo "File is too large.<br>"; } // Generate a safe unique file name else { $safeFileName = uniqid("upload_", true) . "." . pathinfo($fileName, PATHINFO_EXTENSION); if (move_uploaded_file($fileTmpName, $uploadDirectory . $safeFileName)) { echo "File uploaded successfully!<br>"; } else { echo "Error uploading file.<br>"; } } } } ?>File uploaded successfully!
The mail()
function in PHP is used to send simple emails.
<?php // Define recipient, subject, and message $to = "recipient@example.com"; $subject = "Test Email"; $message = "Hello, this is a test email!"; // Send email if(mail($to, $subject, $message)) { echo "Email sent successfully!"; } else { echo "Email sending failed!"; } ?>
Headers are used to specify the sender, content type, and other details for an email.
<?php // Define recipient, subject, and message $to = "recipient@example.com"; $subject = "Test Email with Headers"; $message = "This is a test email with headers!"; // Define headers $headers = "From: sender@example.com" . "\r\n"; $headers .= "Reply-To: sender@example.com" . "\r\n"; $headers .= "Content-Type: text/plain; charset=UTF-8" . "\r\n"; // Send email with headers if(mail($to, $subject, $message, $headers)) { echo "Email with headers sent successfully!"; } else { echo "Email with headers sending failed!"; } ?>
To send an HTML email, you need to set the content type to text/html
in the headers.
<?php // Define recipient, subject, and HTML message $to = "recipient@example.com"; $subject = "Test HTML Email"; $message = "Hello!
This is a test HTML email.
"; // Define headers for HTML email $headers = "From: sender@example.com" . "\r\n"; $headers .= "Reply-To: sender@example.com" . "\r\n"; $headers .= "Content-Type: text/html; charset=UTF-8" . "\r\n"; // Send HTML email if(mail($to, $subject, $message, $headers)) { echo "HTML Email sent successfully!"; } else { echo "HTML Email sending failed!"; } ?>
Sending attachments requires encoding the file content and including it in the email body with the appropriate headers.
<?php // Define recipient, subject, and message $to = "recipient@example.com"; $subject = "Test Email with Attachment"; $message = "This email contains an attachment."; // Define attachment $file = "path/to/file.txt"; $file_content = chunk_split(base64_encode(file_get_contents($file))); $file_name = basename($file); // Define boundary $boundary = md5(time()); // Define headers for attachment $headers = "From: sender@example.com" . "\r\n"; $headers .= "Reply-To: sender@example.com" . "\r\n"; $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"" . "\r\n"; // Define email body with attachment $body = "--$boundary\r\n"; $body .= "Content-Type: text/plain; charset=UTF-8\r\n"; $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n"; $body .= $message . "\r\n\r\n"; $body .= "--$boundary\r\n"; $body .= "Content-Type: application/octet-stream; name=\"$file_name\"\r\n"; $body .= "Content-Transfer-Encoding: base64\r\n"; $body .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n\r\n"; $body .= $file_content . "\r\n"; $body .= "--$boundary--"; // Send email with attachment if(mail($to, $subject, $body, $headers)) { echo "Email with attachment sent successfully!"; } else { echo "Email with attachment sending failed!"; } ?>
Some common issues when sending emails include incorrect SMTP configuration, email being marked as spam, or missing headers.
<?php // Ensure SMTP configuration is correct in php.ini // Uncomment and configure the following lines in php.ini // SMTP = smtp.example.com // smtp_port = 25 ?>
PHPMailer is a popular library for sending emails using SMTP and supports many features such as attachments, HTML emails, and more.
<?php // Include PHPMailer files require 'PHPMailerAutoload.php'; // Create instance of PHPMailer $mail = new PHPMailer; // Set mail parameters $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'user@example.com'; $mail->Password = 'password'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; // Set sender and recipient $mail->setFrom('sender@example.com', 'Sender Name'); $mail->addAddress('recipient@example.com'); // Set subject and body $mail->Subject = 'Test PHPMailer Email'; $mail->Body = 'This is a test email using PHPMailer!'; // Send email if($mail->send()) { echo 'Email sent successfully!'; } else { echo 'Email sending failed: ' . $mail->ErrorInfo; } ?>
When using SMTP for sending emails, make sure to configure the SMTP server correctly and authenticate using proper credentials.
<?php // Configure SMTP in PHP settings or use PHPMailer for better flexibility. // Ensure correct SMTP server and authentication details are set. ?>
Scalar type declarations allow you to define the types of function arguments and return values for scalar types like int, float, string, and bool.
<?php // Scalar type declarations in PHP 7 and above function add(int $a, int $b): int { return $a + $b; // Function expects two integers and returns an integer } echo add(2, 3); // Outputs: 5 ?>
Return type declarations specify the type of the value that a function will return. This helps ensure that the return value matches the expected type.
<?php // Return type declarations in PHP 7 and above function multiply(float $a, float $b): float { return $a * $b; // Function expects two floats and returns a float } echo multiply(2.5, 4); // Outputs: 10 ?>
The null coalescing operator (??
) is used to check if a value is null, and if it is, it returns a default value instead.
<?php // Null Coalescing Operator (PHP 7 and above) $username = $_GET['username'] ?? 'guest'; // If 'username' is not set or null, use 'guest' echo $username; // Outputs: guest if 'username' is not set ?>
The match expression (match
) is a more flexible and safer version of the switch statement, introduced in PHP 8. It supports strict comparison and does not require a break statement.
<?php // Match Expression (PHP 8 and above) $status = 200; $message = match ($status) { 200 => 'OK', 404 => 'Not Found', 500 => 'Server Error', default => 'Unknown Status', }; echo $message; // Outputs: OK ?>
Constructor property promotion simplifies the syntax for declaring and initializing properties directly in the constructor, introduced in PHP 8.
<?php // Constructor Property Promotion (PHP 8 and above) class User { public function __construct( public string $name, public int $age ) {} } $user = new User('John', 30); echo $user->name . ' is ' . $user->age . ' years old.'; // Outputs: John is 30 years old. ?>
Named arguments allow you to pass arguments to a function based on the parameter name, rather than their position. This was introduced in PHP 8.
<?php // Named Arguments (PHP 8 and above) function createUser(string $name, int $age, string $role = 'guest') { return "$name, $age years old, role: $role"; } echo createUser(age: 25, name: 'Alice'); // Outputs: Alice, 25 years old, role: guest ?>
Fibers and enumerations were introduced in PHP 8.1. Fibers allow you to suspend and resume functions, while enumerations provide a way to define a set of named constants in a more robust way than simple class constants.
<?php // Fibers (PHP 8.1 and above) $fiber = new Fiber(function (): void { echo "Fiber started\n"; Fiber::suspend(); echo "Fiber resumed\n"; }); $fiber->start(); // Outputs: Fiber started $fiber->resume(); // Outputs: Fiber resumed // Enumerations (PHP 8.1 and above) enum Status { case Pending; case Completed; case Failed; } $status = Status::Pending; echo $status->name; // Outputs: Pending ?>
SQL Injection is a security vulnerability that allows an attacker to interfere with the queries your application makes to its database. The best way to prevent SQL injection is by using prepared statements with bound parameters.
<!-- Example of SQL Injection Prevention --> <?php $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password"); $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username"); $stmt->bindParam(':username', $_POST['username']); $stmt->execute(); $user = $stmt->fetch(); echo "User: " . $user['username']; ?>
Cross-site scripting (XSS) attacks occur when an attacker injects malicious scripts into content that other users view. To prevent XSS, always sanitize and escape user input before displaying it on the page.
<!-- Example of XSS Prevention --> <?php // Sanitizing user input $user_input = htmlspecialchars($_POST['user_input'], ENT_QUOTES, 'UTF-8'); echo "User input: " . $user_input; ?>
Cross-Site Request Forgery (CSRF) attacks trick the user into executing unwanted actions on a web application where they are authenticated. To prevent CSRF, include a token in every form, and validate the token server-side.
<!-- Example of CSRF Protection --> <?php session_start(); // Generate CSRF token if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } ?> <!-- HTML Form with CSRF Token --> <form method="POST" action="submit.php"> <!-- Other form fields here --> <button type="submit">Submit</button> </form>
Input sanitization ensures that user input is safe to use in your application, preventing attacks such as SQL injection or XSS. Functions like filter_var()
and htmlspecialchars()
are used to sanitize input.
<!-- Example of Input Sanitization --> <?php $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $url = filter_var($_POST['url'], FILTER_SANITIZE_URL); echo "Sanitized Email: " . $email; ?>
The Model-View-Controller (MVC) pattern is a design pattern that separates an application into three interconnected components:
/app /controllers /models /views /public /index.php
Composer is a dependency manager for PHP, and autoloading allows classes to be automatically loaded when needed. To enable autoloading in Composer, define an autoload section in your composer.json
file.
<!-- Example of Composer Autoloading --> <?php // Run composer dump-autoload to generate the autoloader require 'vendor/autoload.php'; use App\Models\User; $user = new User(); ?>
Unit testing is a critical part of the development process. PHPUnit is a framework for writing unit tests in PHP. Here's how you can write a simple test case:
<!-- Example of PHPUnit Test --> <?php use PHPUnit\Framework\TestCase; class MathTest extends TestCase { public function testAdd() { $this->assertEquals(4, 2 + 2); } } ?>
Dependency Injection (DI) is a design pattern where an object receives other objects it depends on (its dependencies) from an external source rather than creating them internally.
<?php // Example class with dependency injection class Logger { public function log($message) { echo "Log: $message"; } } class UserService { private $logger; // Inject Logger dependency via constructor public function __construct(Logger $logger) { $this->logger = $logger; } public function register($user) { $this->logger->log("User $user registered"); } } $logger = new Logger(); // Create Logger instance $service = new UserService($logger); // Inject logger into UserService $service->register('Alice'); // Use service ?>
Manual DI means creating and injecting dependencies manually, while containers automate this process using mappings and bindings.
<?php // Manual DI example (shown above) // Containers automatically resolve dependencies based on configuration ?>
A service container manages object creation and dependency resolution.
<?php class Container { protected $bindings = []; // Bind a service to a resolver (closure) public function bind($name, $resolver) { $this->bindings[$name] = $resolver; } // Resolve a service public function make($name) { if (isset($this->bindings[$name])) { return $this->bindings[$name]($this); // Call resolver } throw new Exception("Service not found"); } } // Bind services $container = new Container(); $container->bind('logger', function () { return new Logger(); }); $container->bind('userService', function ($c) { return new UserService($c->make('logger')); // Inject logger }); $service = $container->make('userService'); // Resolve UserService $service->register('Bob'); // Use service ?>
Services are bound to the container and later resolved when needed. This supports loose coupling and better testability.
<?php // See binding above with bind() and make() ?>
- **Factory**: Each call to `make()` creates a new instance.
- **Singleton**: Same instance is reused for every call.
<?php class SingletonContainer { protected $bindings = []; protected $instances = []; public function singleton($name, $resolver) { $this->bindings[$name] = $resolver; } public function make($name) { if (!isset($this->instances[$name])) { $this->instances[$name] = $this->bindings[$name]($this); } return $this->instances[$name]; } } // Singleton usage $container = new SingletonContainer(); $container->singleton('logger', function () { return new Logger(); }); $logger1 = $container->make('logger'); $logger2 = $container->make('logger'); echo ($logger1 === $logger2) ? "Same instance" : "Different instances"; ?>
Laravel's service container automatically resolves dependencies via type hinting.
// Laravel Controller Example class UserController extends Controller { protected $service; // Laravel injects UserService automatically public function __construct(UserService $service) { $this->service = $service; } public function register(Request $request) { $this->service->register($request->name); } } // Laravel handles container binding automatically app()->make(UserController::class);
In traditional synchronous (sync) PHP, tasks are executed one after the other. In asynchronous (async) PHP, tasks can be initiated and allowed to complete while continuing with other logic.
<?php // Simulating synchronous behavior echo "Start processing\n"; // Output start sleep(3); // Wait for 3 seconds echo "Finished processing\n"; // Output end ?>
pcntl_fork()
allows you to fork processes (Linux only). exec()
can run shell commands asynchronously.
<?php // Check if pcntl is available if (function_exists('pcntl_fork')) { $pid = pcntl_fork(); // Fork the current process if ($pid == -1) { die("Could not fork process"); // Handle failure } elseif ($pid) { echo "Parent process continues\n"; // Parent continues } else { sleep(2); // Simulate child doing something echo "Child process done\n"; // Output from child exit(); // End child } } else { echo "pcntl is not available on this system.\n"; } ?>
ReactPHP is an event-driven, non-blocking I/O library for PHP. It allows building async applications like Node.js.
// Example: Basic ReactPHP HTTP server // Run with: php server.php require 'vendor/autoload.php'; // Load Composer packages $loop = React\EventLoop\Factory::create(); // Create an event loop $server = new React\Http\Server(function ($request) { return React\Http\Message\Response::plaintext(200, [], "Hello from ReactPHP!"); }); $socket = new React\Socket\SocketServer('127.0.0.1:8080', [], $loop); // Bind to port $server->listen($socket); // Start listening echo "Server running at http://127.0.0.1:8080\n"; $loop->run(); // Run the loop
ReactPHP uses Promises (like JavaScript) to handle future results. This enables you to run tasks asynchronously without blocking the script.
use React\Promise\Promise; function asyncOperation() { return new Promise(function ($resolve) { // Simulate async delay echo "Working...\n"; sleep(1); $resolve("Done!"); }); } asyncOperation()->then(function ($value) { echo $value . "\n"; });
Guzzle is a PHP HTTP client that supports async requests using Promises. You must install it via Composer.
// Run: composer require guzzlehttp/guzzle require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); $promise = $client->getAsync('https://jsonplaceholder.typicode.com/todos/1'); $promise->then( function ($response) { echo $response->getBody(); }, function ($error) { echo "Error: " . $error->getMessage(); } ); // Prevent script from exiting before the response $promise->wait();
You can handle background tasks in PHP using queues such as RabbitMQ
, Beanstalkd
, or Redis
queues. Laravel uses queues to process jobs asynchronously.
// Laravel Example: Dispatching a job MyJob::dispatch($data); // Will be handled by a queue worker in background // Worker command: php artisan queue:work
<?php // This simple RESTful API returns a JSON response based on a query string. if ($_SERVER['REQUEST_METHOD'] === 'GET') { $data = ["message" => "Hello API"]; header('Content-Type: application/json'); echo json_encode($data); } ?>
<?php // Basic routing simulation using query string (?route=about) $route = $_GET['route'] ?? 'home'; switch ($route) { case 'about': echo "About Page"; break; case 'contact': echo "Contact Page"; break; default: echo "Home Page"; } ?>
<?php // Encoding PHP array to JSON $array = ["name" => "Alice", "age" => 30]; echo json_encode($array); // Decoding JSON string to PHP array $json = '{"name":"Bob","age":25}'; $phpArray = json_decode($json, true); print_r($phpArray); ?>
<?php $ch = curl_init("https://jsonplaceholder.typicode.com/posts/1"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response; ?>
// composer require guzzlehttp/guzzle <?php require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); $response = $client->get('https://jsonplaceholder.typicode.com/posts/1'); echo $response->getBody(); ?>
// Outline using Google OAuth2 // Steps: 1. Redirect to Google, 2. Receive code, 3. Exchange for token // Redirect user header('Location: https://accounts.google.com/o/oauth2/auth?client_id=YOUR_ID&redirect_uri=YOUR_URI&response_type=code&scope=email'); exit(); // Exchange code for token with POST request // Use Guzzle or cURL to send to https://oauth2.googleapis.com/token
// Use firebase/php-jwt // composer require firebase/php-jwt <?php use Firebase\JWT\JWT; use Firebase\JWT\Key; $key = 'secretkey'; $payload = ["user" => "admin"]; $jwt = JWT::encode($payload, $key, 'HS256'); echo $jwt; // Decode example: $decoded = JWT::decode($jwt, new Key($key, 'HS256')); print_r($decoded); ?>
SOLID stands for five key design principles:
<?php class Invoice { public function calculateTotal() { return 100; } } class InvoicePrinter { public function print(Invoice $invoice) { echo "Total: " . $invoice->calculateTotal(); } } $invoice = new Invoice(); $printer = new InvoicePrinter(); $printer->print($invoice); ?>
<?php interface PaymentStrategy { public function pay($amount); } class Paypal implements PaymentStrategy { public function pay($amount) { echo "Paying $amount using PayPal."; } } class CreditCard implements PaymentStrategy { public function pay($amount) { echo "Paying $amount using Credit Card."; } } class PaymentProcessor { private $method; public function __construct(PaymentStrategy $method) { $this->method = $method; } public function process($amount) { $this->method->pay($amount); } } $processor = new PaymentProcessor(new Paypal()); $processor->process(50); ?>
<?php interface Animal { public function speak(); } class Dog implements Animal { public function speak() { return "Woof!"; } } class Cat implements Animal { public function speak() { return "Meow!"; } } class AnimalFactory { public static function create($type) { if ($type == 'dog') return new Dog(); if ($type == 'cat') return new Cat(); throw new Exception("Animal not found."); } } $animal = AnimalFactory::create('dog'); echo $animal->speak(); ?>
<?php interface Observer { public function update($message); } class EmailNotifier implements Observer { public function update($message) { echo "Email: $message"; } } class Logger implements Observer { public function update($message) { echo "Log: $message"; } } class Subject { private $observers = []; public function attach(Observer $observer) { $this->observers[] = $observer; } public function notify($message) { foreach ($this->observers as $observer) { $observer->update($message); } } } $subject = new Subject(); $subject->attach(new EmailNotifier()); $subject->attach(new Logger()); $subject->notify("Order placed!"); ?>
<?php trait LoggerTrait { public function log($msg) { echo "Logging: $msg"; } } class Product { use LoggerTrait; public function create() { $this->log("Product created"); } } $product = new Product(); $product->create(); ?>
<?php class StaticLogger { public static function log($msg) { echo "Static log: $msg"; } } StaticLogger::log("Hello"); ?>
<?php class ServiceLogger { public function log($msg) { echo "Injected log: $msg"; } } class Service { private $logger; public function __construct(ServiceLogger $logger) { $this->logger = $logger; } public function run() { $this->logger->log("Running service"); } } $service = new Service(new ServiceLogger()); $service->run(); ?>
<?php interface Shape { public function area(); } class Square implements Shape { private $side = 5; public function area() { return $this->side * $this->side; } } $square = new Square(); echo $square->area(); ?>
<?php abstract class Vehicle { abstract public function move(); } class Car extends Vehicle { public function move() { return "Car moves"; } } $car = new Car(); echo $car->move(); ?>
WebSockets provide a persistent, full-duplex communication channel between the client and server, enabling real-time data exchange without the overhead of traditional HTTP requests.
:contentReference[oaicite:6]{index=6}Ratchet is a PHP library for implementing WebSocket servers. Below is an example of setting up a basic WebSocket server using Ratchet.
:contentReference[oaicite:9]{index=9}<?php // Include Ratchet library classes use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; // Define Chat class implementing MessageComponentInterface class Chat implements MessageComponentInterface { protected $clients; public function __construct() { // Create a storage for connected clients $this->clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { // Store the new connection $this->clients->attach($conn); echo "New connection! ({$conn->resourceId})\n"; } public function onMessage(ConnectionInterface $from, $msg) { // Broadcast the received message to all connected clients foreach ($this->clients as $client) { if ($from !== $client) { $client->send($msg); } } } public function onClose(ConnectionInterface $conn) { // Remove the connection from the storage $this->clients->detach($conn); echo "Connection {$conn->resourceId} has disconnected\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e->getMessage()}\n"; $conn->close(); } } // Run the server use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; require __DIR__ . '/vendor/autoload.php'; $server = IoServer::factory( new HttpServer( new WsServer( new Chat() ) ), 8080 ); $server->run(); ?>
With the WebSocket server running, clients can connect and exchange messages in real-time. Below is an example of a simple HTML client that connects to the server and sends messages.
:contentReference[oaicite:12]{index=12}<!DOCTYPE html> <html> <head> <title>WebSocket Chat Client</title> </head> <body> <h2>WebSocket Chat</h2> <input type="text" id="message" placeholder="Enter message" /> <button onclick="sendMessage()">Send</button> <ul id="chat"></ul> <script> // Create a new WebSocket connection const socket = new WebSocket('ws://localhost:8080'); // Event handler for receiving messages socket.onmessage = function(event) { const chat = document.getElementById('chat'); const message = document.createElement('li'); message.textContent = event.data; chat.appendChild(message); }; // Function to send messages function sendMessage() { const input = document.getElementById('message'); const message = input.value; socket.send(message); input.value = ''; } </script> </body> </html>
The above example demonstrates how to integrate a PHP WebSocket server with a JavaScript frontend, enabling real-time communication between clients.
:contentReference[oaicite:15]{index=15}Laravel provides built-in support for broadcasting events using drivers like Pusher. Below is an example of setting up broadcasting in Laravel.
:contentReference[oaicite:18]{index=18}// .env configuration BROADCAST_DRIVER=pusher PUSHER_APP_ID=your-app-id PUSHER_APP_KEY=your-app-key PUSHER_APP_SECRET=your-app-secret PUSHER_HOST= PUSHER_PORT=443 PUSHER_SCHEME=https // Event class namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class MessageSent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; public $message; public function __construct($message) { $this->message = $message; } public function broadcastOn() { return new Channel('chat'); } }
<script src="https://js.pusher.com/7.0/pusher.min.js"></script> <script src="/js/app.js"></script> <script> // Initialize Laravel Echo with Pusher import Echo from 'laravel-echo'; window.Pusher = require('pusher-js'); window.Echo = new Echo({ broadcaster: 'pusher', key: 'your-app-key', cluster: 'mt1', encrypted: true }); // Listen for the MessageSent event window.Echo.channel('chat') .listen('MessageSent', (e) => { console.log('Message received:', e.message); }); </script>
<?php
$apiKey = 'your-api-key';
$apiUrl = 'https://api.openai.com/v1/completions';
$data = [
'model' => 'text-davinci-003',
'prompt' => 'What is PHP?',
'max_tokens' => 100
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: AI's response to the prompt, e.g., "PHP is a server-side scripting language..."
<?php
$apiKey = 'your-api-key';
$apiUrl = 'https://api.openai.com/v1/completions';
$data = [
'model' => 'text-davinci-003',
'prompt' => 'Please analyze the sentiment of the following text: "I love using PHP for web development!"',
'max_tokens' => 100
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: "Positive sentiment"
<?php
$apiKey = 'your-deepai-api-key';
$apiUrl = 'https://api.deepai.org/api/image-recognition';
$imagePath = 'path_to_image.jpg';
$imageData = [
'image' => new CURLFile($imagePath)
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $imageData);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: JSON response with image classification details
<?php
require 'vendor/autoload.php';
use Google\Cloud\Speech\V1\SpeechClient;
use Google\Cloud\Speech\V1\RecognitionConfig;
use Google\Cloud\Speech\V1\RecognitionAudio;
$client = new SpeechClient();
$audio = (new RecognitionAudio())
->setUri('gs://your-bucket/audio-file.flac');
$config = (new RecognitionConfig())
->setEncoding(RecognitionConfig\AudioEncoding::LINEAR16)
->setSampleRateHertz(16000)
->setLanguageCode('en-US');
$response = $client->recognize($config, $audio);
foreach ($response->getResults() as $result) {
echo $result->getAlternatives()[0]->getTranscript();
}
?>
Output: Transcription of the audio file
<?php
$apiKey = 'your-dialogflow-api-key';
$apiUrl = 'https://api.dialogflow.com/v1/query?v=20150910';
$data = [
'query' => 'What is PHP?',
'lang' => 'en',
'sessionId' => '12345'
];
$options = [
'http' => [
'header' => "Authorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: DialogFlow chatbot response
<?php
require 'vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;
$translate = new TranslateClient();
$text = 'Hello, how are you?';
$target = 'es';
$translation = $translate->translate($text, ['target' => $target]);
echo $translation['text'];
?>
Output: "Hola, ¿cómo estás?" (Translation to Spanish)
<?php
$apiKey = 'your-api-key'; // Store your OpenAI API key
$apiUrl = 'https://api.openai.com/v1/completions'; // OpenAI API endpoint for completions
// Define the data to send in the POST request
$data = [
'model' => 'text-davinci-003', // The model to use
'prompt' => 'Generate a short paragraph about AI in PHP.', // The prompt for the model
'max_tokens' => 100 // Limit the response tokens
];
// Create an HTTP context with appropriate headers
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set content type and authorization
'method' => 'POST', // Use POST method
'content' => json_encode($data) // Encode the data to JSON
]
];
// Create the stream context for the request
$context = stream_context_create($options);
// Send the request and capture the response
$response = file_get_contents($apiUrl, false, $context);
// Output the response
echo $response;
?>
Output: Generated AI text
<?php
$apiKey = 'your-deepai-api-key'; // Replace with your actual DeepAI API key
$apiUrl = 'https://api.deepai.org/api/text2img'; // API endpoint for DeepAI text-to-image
// Define the data to send with the POST request
$data = [
'text' => 'A futuristic city with flying cars' // The text prompt describing the image to generate
];
// Set the HTTP context options including headers and content
$options = [
'http' => [
'header' => "Api-Key: $apiKey", // Authorization header with API key
'method' => 'POST', // Use POST method to send the request
'content' => http_build_query($data) // URL-encode the data for the POST body
]
];
// Create a stream context from the options array
$context = stream_context_create($options);
// Send the HTTP request and capture the response
$response = file_get_contents($apiUrl, false, $context);
// Output the result returned from the API
echo $response;
?>
Output: JSON response with image URL
<?php
$apiKey = 'your-api-key'; // Replace with your DeepAI API key
$apiUrl = 'https://api.deepai.org/api/video-thumbnail'; // API endpoint for generating video thumbnails
// Prepare the video file for upload using CURLFile
$data = [
'video' => new CURLFile('video.mp4') // Replace 'video.mp4' with the path to your video file
];
// Initialize cURL session
$ch = curl_init();
// Set the URL to send the POST request to
curl_setopt($ch, CURLOPT_URL, $apiUrl);
// Set to return the response as a string instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set the HTTP headers, including your API key
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Authentication header
]);
// Indicate that this is a POST request
curl_setopt($ch, CURLOPT_POST, 1);
// Attach the video file as POST data
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Execute the cURL session and store the response
$response = curl_exec($ch);
// Close the cURL session to free up resources
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: JSON response with generated thumbnail image URL
<?php
// Example assumes that a pre-trained AI model is hosted via an API.
$apiKey = 'your-model-api-key'; // Your API key for authentication
$apiUrl = 'https://api.custom-ai.com/model-inference'; // The endpoint of the AI model's API
// Prepare the data payload to send to the model
$data = [
'input' => 'text or image data here' // Replace with actual input data
];
// Create HTTP request options
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers including content type and API key
'method' => 'POST', // Use the POST method
'content' => json_encode($data) // Convert the data array to JSON
]
];
// Create the stream context with the options
$context = stream_context_create($options);
// Send the HTTP request and capture the response
$response = file_get_contents($apiUrl, false, $context);
// Output the response from the API
echo $response;
?>
Output: Inference results from the custom AI model
<?php
// Set the API key used for authentication
$apiKey = 'your-api-key';
// Define the URL endpoint of the forecasting API
$apiUrl = 'https://api.ai-forecasting.com/v1/predict';
// Prepare the data to be sent to the AI forecasting API
$data = [
'model' => 'trend-prediction', // Specify the model name
'data' => [10, 20, 30, 40, 50] // Example dataset for trend prediction
];
// Configure the HTTP options for the POST request
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for JSON content and API key
'method' => 'POST', // HTTP request method
'content' => json_encode($data) // Encode the data array to JSON format
]
];
// Create a stream context with the above options
$context = stream_context_create($options);
// Send the request and receive the response
$response = file_get_contents($apiUrl, false, $context);
// Output the API response
echo $response;
?>
Output: Predicted trend values for the input data
<?php
$apiKey = 'your-api-key';
$apiUrl = 'https://api.ai-visualization.com/v1/chart';
$data = [
'data' => [15, 30, 45, 60],
'type' => 'bar',
'labels' => ['A', 'B', 'C', 'D']
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: JSON response with chart data or image URL
<?php
$apiKey = 'your-api-key';
$apiUrl = 'https://api.nlp.ai/v1/classify';
$data = [
'text' => 'PHP is a popular scripting language used for web development.'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Text classification result, e.g., "Web Development"
<?php
$apiKey = 'your-api-key';
$apiUrl = 'https://api.ai-chatbot.com/v1/respond';
$data = [
'message' => 'Hello, how are you today?',
'sessionId' => '12345'
];
$options = [
'http' => [
'header' => "Authorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Chatbot's AI response, e.g., "I'm doing great, how about you?"
<?php
$apiKey = 'your-api-key';
$apiUrl = 'https://api.deepai.org/api/image-captioning';
$data = [
'image' => new CURLFile('path_to_image.jpg')
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: Generated image caption, e.g., "A dog playing in the park"
<?php
$apiKey = 'your-google-cloud-api-key';
$apiUrl = 'https://speech.googleapis.com/v1/speech:recognize';
$data = [
'config' => [
'encoding' => 'LINEAR16',
'sampleRateHertz' => 16000,
'languageCode' => 'en-US',
],
'audio' => [
'uri' => 'gs://your-bucket/audio.wav'
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context => stream_context_create($options);
$response => file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Speech-to-text conversion result (transcribed text)
<?php
$apiKey = 'your-google-cloud-api-key';
$apiUrl = 'https://texttospeech.googleapis.com/v1/text:synthesize';
$data = [
'input' => [
'text' => 'Hello, welcome to the AI integration tutorial.'
],
'voice' => [
'languageCode' => 'en-US',
'name' => 'en-US-Wavenet-D'
],
'audioConfig' => [
'audioEncoding' => 'MP3'
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context => stream_context_create($options);
$response => file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Audio content in MP3 format
<?php
$apiKey = 'your-google-cloud-api-key';
$apiUrl = 'https://translation.googleapis.com/language/translate/v2';
$data = [
'q' => 'Hello, how are you?',
'target' => 'es' // Spanish translation
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context => stream_context_create($options);
$response => file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Translated text in Spanish, e.g., "Hola, ¿cómo estás?"
<?php
$apiKey = 'your-sentiment-api-key';
$apiUrl = 'https://api.sentimentanalysis.com/v1/analyze';
$data = [
'text' => 'I love this product, it is amazing!'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context => stream_context_create($options);
$response => file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Sentiment analysis result, e.g., "Positive"
<?php
$apiKey = 'your-fraud-detection-api-key';
$apiUrl = 'https://api.frauddetection.com/v1/check';
$data = [
'transaction' => [
'amount' => 1000,
'location' => 'New York',
'account' => '123456789'
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context => stream_context_create($options);
$response => file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Fraud detection result, e.g., "Fraudulent transaction detected"
<?php
$apiKey = 'your-recommendation-api-key'; // Your API key
$apiUrl = 'https://api.recommendation.com/v1/recommend'; // Endpoint URL
$data = [
'user' => 'user123', // User identifier
'preferences' => ['action', 'comedy', 'drama'] // User preferences
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Headers
'method' => 'POST', // Use POST
'content' => json_encode($data) // JSON-encoded payload
]
];
// Create the stream context for the HTTP request
$context = stream_context_create($options);
// Send the request and get the response
$response = file_get_contents($apiUrl, false, $context);
// Output the API response
echo $response;
?>
Output: Recommended movies based on user preferences
<?php
$apiKey = 'your-api-key'; // Your API key for DeepAI
$apiUrl = 'https://api.deepai.org/api/torch-srgan'; // DeepAI endpoint for image enhancement
$data = [
'image' => new CURLFile('path_to_image.jpg') // Path to the image for enhancement
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the API request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return response as string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Use POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach image data for POST
// Execute the request and get the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: Enhanced version of the uploaded image
<?php
$apiKey = 'your-api-key'; // Your API key for DeepAI
$apiUrl = 'https://api.deepai.org/api/detect-object'; // DeepAI object detection endpoint
$data = [
'image' => new CURLFile('path_to_image.jpg') // Path to the image for object detection
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the API request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return response as string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Use POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach image data for POST
// Execute the request and get the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: JSON response with detected objects and bounding boxes
<?php
$apiKey = 'your-api-key'; // Your API key for DeepAI
$apiUrl = 'https://api.deepai.org/api/face-recognition'; // DeepAI face recognition endpoint
$data = [
'image' => new CURLFile('path_to_image.jpg') // Path to the image for face recognition
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the API request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return response as string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Use POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach image data for POST
// Execute the request and get the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: Detected faces with coordinates in JSON format
<?php
$apiKey = 'your-emotion-api-key'; // Your API key for emotion detection
$apiUrl = 'https://api.emotiondetection.com/v1/detect'; // Emotion detection API endpoint
$data = [
'audio' => new CURLFile('path_to_audio.wav') // Path to the audio file for emotion detection
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the API request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return response as string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Use POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach audio data for POST
// Execute the request and get the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: Emotional tone detected in the audio (e.g., "Happy", "Sad")
<?php
$apiKey = 'your-nlp-api-key'; // Your API key for NLP services
$apiUrl = 'https://api.nlp.com/v1/summarize'; // NLP API endpoint for text summarization
$data = [
'text' => 'The quick brown fox jumps over the lazy dog. The dog then barks loudly and runs away.' // Text to summarize
];
// Set HTTP options for the request
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers with API key
'method' => 'POST', // Set HTTP method to POST
'content' => json_encode($data) // Convert the data to JSON format
]
];
// Create the context for the request
$context => stream_context_create($options);
// Send the request and get the response
$response = file_get_contents($apiUrl, false, $context);
// Output the response
echo $response;
?>
Output: A summarized version of the input text
<?php
$apiKey = 'your-style-transfer-api-key'; // Your API key for style transfer service
$apiUrl = 'https://api.imagestyletransfer.com/v1/style-transfer'; // API endpoint for style transfer
$data = [
'content_image' => new CURLFile('path_to_content_image.jpg'), // Path to content image
'style_image' => new CURLFile('path_to_style_image.jpg') // Path to style image
];
// Initialize the cURL session
$ch = curl_init();
// Set the cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set API endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key in the headers
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Set the data to send
// Execute the request and capture the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: Image with the style of the chosen artwork applied
<?php
$apiKey = 'your-predictive-text-api-key'; // Your API key for predictive text service
$apiUrl = 'https://api.predictivetext.com/v1/next-word'; // API endpoint for next-word prediction
$data = [
'input' => 'The weather today is' // Text input to predict the next word
];
// Set up HTTP context options
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set content type and authorization header
'method' => 'POST', // Set method to POST
'content' => json_encode($data) // Convert input data to JSON format
]
];
// Create the HTTP context
$context => stream_context_create($options);
// Send the HTTP request and get the response
$response = file_get_contents($apiUrl, false, $context);
// Output the response from the API
echo $response;
?>
Output: Predicted next word based on the input text
<?php
$apiKey = 'your-video-analysis-api-key'; // Your API key for video analysis service
$apiUrl = 'https://api.videoanalysis.com/v1/analyze'; // API endpoint for video analysis
$data = [
'video' => new CURLFile('path_to_video.mp4') // Path to the video file to be analyzed
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the API URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set API key for authentication
]);
curl_setopt($ch, CURLOPT_POST, 1); // Use POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the video file to the request
// Execute the cURL request and get the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: Analysis of video content (e.g., identified objects, events, or actions)
<?php
$apiKey = 'your-speech-recognition-api-key'; // Your API key for speech recognition service
$apiUrl = 'https://api.speechrecognition.com/v1/convert'; // API endpoint for speech-to-text conversion
$data = [
'audio_file' => new CURLFile('path_to_audio_file.wav') // Path to the audio file to be transcribed
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the API URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set API key for authentication
]);
curl_setopt($ch, CURLOPT_POST, 1); // Use POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the audio file to the request
// Execute the cURL request and get the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: Text representation of the spoken words from the audio file.
<?php
$apiKey = 'your-recommendation-api-key'; // Your API key for recommendation service
$apiUrl = 'https://api.recommendationai.com/v1/products/recommend'; // API endpoint for product recommendations
$data = [
'user_id' => '12345', // User ID for personalized recommendations
'purchase_history' => 'purchase_history.json' // Path to user's purchase history file
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set content type and authorization header
'method' => 'POST', // Use POST method for sending data
'content' => json_encode($data) // Convert data array to JSON format
]
];
// Create a stream context with the specified options
$context => stream_context_create($options);
// Send the HTTP request and capture the response
$response = file_get_contents($apiUrl, false, $context);
// Output the response from the API
echo $response;
?>
Output: List of recommended products based on the user’s previous purchases.
<?php
$apiKey = 'your-maintenance-api-key'; // Your API key for maintenance service
$apiUrl = 'https://api.maintenanceai.com/v1/predict'; // API endpoint for predictive maintenance
$data = [
'machine_id' => '123', // Machine ID for which to predict maintenance needs
'sensor_data' => 'sensor_data.json' // Path to the sensor data file
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set content type and authorization header
'method' => 'POST', // Use POST method for sending data
'content' => json_encode($data) // Convert data array to JSON format
]
];
// Create a stream context with the specified options
$context => stream_context_create($options);
// Send the HTTP request and capture the response
$response = file_get_contents($apiUrl, false, $context);
// Output the response from the API
echo $response;
?>
Output: Prediction result for maintenance requirements (e.g., ‘No Maintenance Required’, ‘Maintenance Due Soon’)
<?php
$apiKey = 'your-text-generation-api-key'; // Your API key for text generation service
$apiUrl = 'https://api.textgeneration.com/v1/generate'; // API endpoint for text generation
$data = [
'prompt' => 'Once upon a time, in a faraway land,', // Initial prompt for text generation
'length' => 100 // Desired length of the generated text
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set content type and authorization header
'method' => 'POST', // Use POST method for sending data
'content' => json_encode($data) // Convert data array to JSON format
]
];
// Create a stream context with the specified options
$context => stream_context_create($options);
// Send the HTTP request and capture the response
$response = file_get_contents($apiUrl, false, $context);
// Output the response from the API
echo $response;
?>
Output: AI-generated continuation of the given prompt.
<?php
$apiKey = 'your-image-recognition-api-key'; // Your API key for image recognition service
$apiUrl = 'https://api.imagerecognition.com/v1/detect'; // API endpoint for image detection
$data = [
'image' => new CURLFile('path_to_image.jpg') // Path to the image you want to analyze
];
$ch = curl_init();
// Set the URL for the API request
curl_setopt($ch, CURLOPT_URL, $apiUrl);
// Return the response as a string instead of outputting it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set the authorization header with the API key
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
// Set the request method to POST
curl_setopt($ch, CURLOPT_POST, 1);
// Attach the data to the request
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Execute the cURL request and get the response
$response = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Output the response from the API
echo $response;
?>
Output: List of objects detected in the image with coordinates.
<?php
$apiKey = 'your-voice-synthesis-api-key'; // Your API key for voice synthesis service
$apiUrl = 'https://api.voicesynthesis.com/v1/synthesize'; // API endpoint for synthesizing voice
$data = [
'text' => 'Hello, welcome to the AI course!', // Text you want to convert to speech
'voice' => 'en_us_male' // Choose the voice type (e.g., male, female, language)
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the headers with content type and authorization
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode data as JSON for the request body
]
];
$context = stream_context_create($options); // Create a stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: Audio file of the synthesized speech.
<?php
$apiKey = 'your-data-analytics-api-key'; // Your API key for data analytics service
$apiUrl = 'https://api.dataanalytics.com/v1/analyze'; // API endpoint for data analysis
$data = [
'sales_data' => 'sales_data.csv' // Path to your sales data file (CSV format)
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the headers with content type and authorization
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode data as JSON for the request body
]
];
$context = stream_context_create($options); // Create a stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: Generated insights from sales data (e.g., trends, patterns, predictions)
<?php
$apiKey = 'your-financial-analysis-api-key'; // Your API key for financial analysis service
$apiUrl = 'https://api.financialanalysis.com/v1/risk-assess'; // API endpoint for risk assessment
$data = [
'investment_data' => 'investment_data.json' // Path to your investment data file (JSON format)
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the headers with content type and authorization
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode data as JSON for the request body
]
];
$context = stream_context_create($options); // Create a stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: Financial risk analysis report (e.g., low, medium, high risk)
<?php
$apiKey = 'your-virtual-assistant-api-key'; // Your API key for the virtual assistant service
$apiUrl = 'https://api.virtualassistant.com/v1/assist'; // API endpoint for virtual assistant
$data = [
'command' => 'What is the weather today?' // Command to ask the virtual assistant about the weather
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the headers with content type and authorization
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode data as JSON for the request body
]
];
$context = stream_context_create($options); // Create a stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the virtual assistant API
?>
Output: Response from the virtual assistant (e.g., 'The weather today is sunny and 25°C.')
<?php
$apiKey = 'your-fraud-detection-api-key'; // Your API key for the fraud detection service
$apiUrl = 'https://api.frauddetection.com/v1/detect'; // API endpoint for fraud detection
$data = [
'transaction_data' => 'transaction_data.json' // The transaction data in JSON format
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the headers with content type and authorization
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode the data as JSON for the request body
]
];
$context = stream_context_create($options); // Create a stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the fraud detection API
?>
Output: Fraud detection result (e.g., 'Fraudulent Transaction Detected' or 'No Fraud Detected')
<?php
$apiKey = 'your-chatbot-api-key'; // Your API key for the chatbot service
$apiUrl = 'https://api.chatbot.com/v1/message'; // API endpoint for sending a message to the chatbot
$data = [
'message' => 'How can I help you today?' // The message to be sent to the chatbot
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the headers with content type and authorization
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode the data as JSON for the request body
]
];
$context = stream_context_create($options); // Create a stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the chatbot API
?>
Output: Chatbot response (e.g., 'I am here to assist you. How can I help?')
<?php
$apiKey = 'your-image-enhancement-api-key'; // Your API key for the image enhancement service
$apiUrl = 'https://api.imageenhancement.com/v1/enhance'; // API endpoint for enhancing the image
$data = [
'image' => new CURLFile('low_res_image.jpg') // The image file to be enhanced
];
$ch = curl_init(); // Initialize the cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the API endpoint URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Set the option to return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key for authorization
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the HTTP method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the image data to the request
$response = curl_exec($ch); // Execute the cURL request and store the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the image enhancement API
?>
Output: Enhanced high-resolution image.
<?php
$apiKey = 'your-nlp-api-key'; // Your API key for the NLP service
$apiUrl = 'https://api.nlp.com/v1/summarize'; // API endpoint for text summarization
$data = [
'text' => 'Your long text to be summarized here.' // The long text to be summarized
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and API key in the request header
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Convert the data array to a JSON string
]
];
$context = stream_context_create($options); // Create the stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and store the response
echo $response; // Output the response from the NLP API
?>
Output: A brief summary of the provided text.
<?php
$apiKey = 'your-time-series-api-key'; // Your API key for time series forecasting
$apiUrl = 'https://api.timeseriesforecasting.com/v1/predict'; // API endpoint for time series forecasting
$data = [
'historical_data' => 'historical_stock_data.csv' // Path to the historical stock data CSV file
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and API key in the request header
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Convert the data array to a JSON string
]
];
$context = stream_context_create($options); // Create the stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and store the response
echo $response; // Output the response from the time series API
?>
Output: Predicted future stock prices for the given data.
<?php
$apiKey = 'your-image-captioning-api-key'; // Your API key for image captioning
$apiUrl = 'https://api.imagecaptioning.com/v1/generate-caption'; // API endpoint for generating captions for images
$data = [
'image' => new CURLFile('path_to_image.jpg') // Path to the image you want to generate a caption for
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the API endpoint URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key in the request header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the HTTP method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the data to the POST request
$response = curl_exec($ch); // Execute the cURL request and store the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response (caption generated for the image)
?>
Output: Generated caption for the image (e.g., 'A group of people sitting at a table with laptops.')
<?php
$apiKey = 'your-style-transfer-api-key'; // Your API key for style transfer
$apiUrl = 'https://api.imagestyletransfer.com/v1/apply-style'; // API endpoint for applying style transfer to an image
$data = [
'image' => new CURLFile('input_image.jpg'), // Path to the input image
'style' => 'painting_style.jpg' // Path to the style image
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the API endpoint URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key in the request header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the HTTP method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the data to the POST request
$response = curl_exec($ch); // Execute the cURL request and store the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response (style-transferred image result)
?>
Output: The image with the applied artistic style.
<?php
$apiKey = 'your-translation-api-key'; // Your API key for translation service
$apiUrl = 'https://api.translation.com/v1/translate'; // API endpoint for translation
$data = [
'text' => 'Hello, how are you?', // Text to be translated
'target_language' => 'es' // Target language code (Spanish in this case)
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers with API key
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode data to JSON format
]
];
$context = stream_context_create($options); // Create stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response (translated text)
?>
Output: Translated text (e.g., 'Hola, ¿cómo estás?')
<?php
$apiKey = 'your-sentiment-analysis-api-key'; // Your API key for sentiment analysis service
$apiUrl = 'https://api.sentimentanalysis.com/v1/analyze'; // API endpoint for sentiment analysis
$data = [
'text' => 'I love this product! It works perfectly.' // Text to be analyzed
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers with API key
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode data to JSON format
]
];
$context = stream_context_create($options); // Create stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response (sentiment analysis result)
?>
Output: Sentiment analysis result (e.g., 'Positive sentiment detected.')
<?php
$apiKey = 'your-recommendation-api-key'; // Your API key for recommendation service
$apiUrl = 'https://api.recommendation.com/v1/recommend'; // API endpoint for recommendations
$data = [
'user_id' => '12345' // User ID to get personalized recommendations
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers with API key
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode data to JSON format
]
];
$context = stream_context_create($options); // Create stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response (recommendation result)
?>
Output: Recommended products or content for the user based on AI algorithms.
<?php
$apiKey = 'your-speech-recognition-api-key'; // Your API key for speech recognition service
$apiUrl = 'https://api.speechrecognition.com/v1/recognize'; // API endpoint for speech recognition
$data = [
'audio' => new CURLFile('audio_file.wav') // The audio file to be processed
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Set to return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the authorization header with the API key
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the data (audio file) to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response (recognized text)
?>
Output: The transcribed text from the audio file.
<?php
$apiKey = 'your-object-detection-api-key'; // Your API key for object detection service
$apiUrl = 'https://api.objectdetection.com/v1/detect'; // API endpoint for object detection
$data = [
'image' => new CURLFile('image.jpg') // The image file to be processed for object detection
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Set to return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the authorization header with the API key
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the image to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response (object detection result)
?>
Output: Detected objects in the image with their labels and confidence scores.
<?php
$apiKey = 'your-text-summary-api-key'; // Your API key for text summarization service
$apiUrl = 'https://api.textsummarization.com/v1/summarize'; // API endpoint for text summarization
$data = [
'text' => 'Your lengthy article or text content goes here. It can be multiple paragraphs long, and the AI will condense it into a shorter summary.' // The text to be summarized
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for the request
'method' => 'POST', // Set method to POST
'content' => json_encode($data) // Send the data as JSON
]
];
$context = stream_context_create($options); // Create stream context with options
$response = file_get_contents($apiUrl, false, $context); // Make the request and get the response
echo $response; // Output the response (the summary)
?>
Output: A concise summary of the provided text.
<?php
$apiKey = 'your-text-classification-api-key'; // Your API key for text classification service
$apiUrl = 'https://api.textclassification.com/v1/classify'; // API endpoint for text classification
$data = [
'text' => 'This product is absolutely fantastic! It works perfectly, and I love it.' // The text to be classified
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for the request
'method' => 'POST', // Set method to POST
'content' => json_encode($data) // Send the data as JSON
]
];
$context = stream_context_create($options); // Create stream context with options
$response = file_get_contents($apiUrl, false, $context); // Make the request and get the response
echo $response; // Output the response (the classification result)
?>
Output: Classification result (e.g., 'Positive')
<?php
$apiKey = 'your-chatbot-api-key'; // Your API key for the chatbot service
$apiUrl = 'https://api.chatbot.com/v1/chat'; // API endpoint for sending messages to the chatbot
$data = [
'message' => 'Hello, how can I help you today?' // The message to be sent to the chatbot
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for the request
'method' => 'POST', // Set method to POST
'content' => json_encode($data) // Send the message as JSON
]
];
$context = stream_context_create($options); // Create stream context with options
$response = file_get_contents($apiUrl, false, $context); // Make the request and get the response
echo $response; // Output the response (the chatbot's reply)
?>
Output: The chatbot's response to the user's input.
<?php
$apiKey = 'your-text-to-speech-api-key'; // Your API key for the Text-to-Speech service
$apiUrl = 'https://api.texttospeech.com/v1/synthesize'; // API endpoint for text-to-speech synthesis
$data = [
'text' => 'Hello! Welcome to the world of AI.' // The text to be converted into speech
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for the request
'method' => 'POST', // Set method to POST
'content' => json_encode($data) // Send the text as JSON
]
];
$context = stream_context_create($options); // Create stream context with options
$response = file_get_contents($apiUrl, false, $context); // Make the request and get the response
echo $response; // Output the response (the audio URL or error message)
?>
Output: The speech output of the given text.
<?php
$apiKey = 'your-realtime-analytics-api-key'; // Your API key for the Real-Time Analytics service
$apiUrl = 'https://api.realtimeanalytics.com/v1/analyze'; // API endpoint for real-time analytics
$data = [
'data' => 'Social media post data or other real-time data to analyze.' // The data to be analyzed
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for the request
'method' => 'POST', // Set method to POST
'content' => json_encode($data) // Send the data as JSON
]
];
$context = stream_context_create($options); // Create stream context with options
$response = file_get_contents($apiUrl, false, $context); // Make the request and get the response
echo $response; // Output the response from the API
?>
Output: The real-time analytics results, such as sentiment trends or engagement data.
<?php
$apiKey = 'your-colorization-api-key'; // Your API key for the colorization service
$apiUrl = 'https://api.imagecolorization.com/v1/colorize'; // API endpoint for colorization
$data = [
'image' => new CURLFile('black_and_white_image.jpg') // The image to be colorized
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Add API key to the request headers
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach data (image) to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the API
?>
Output: The colorized version of the black-and-white image.
<?php
$apiKey = 'your-video-analysis-api-key'; // Your API key for the video analysis service
$apiUrl = 'https://api.videoanalysis.com/v1/analyze'; // API endpoint for video analysis
$data = [
'video' => new CURLFile('video.mp4') // The video file to be analyzed
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Add API key to the request headers
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach data (video) to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the API
?>
Output: Analysis results such as detected actions or objects within the video.
<?php
$apiKey = 'your-fraud-detection-api-key'; // Your API key for fraud detection service
$apiUrl = 'https://api.frauddetection.com/v1/detect'; // API endpoint for fraud detection
$data = [
'transaction_data' => 'Transaction details for analysis.' // The transaction details for analysis
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for request
'method' => 'POST', // Request method is POST
'content' => json_encode($data) // Encode data as JSON
]
];
$context = stream_context_create($options); // Create the stream context with options
$response = file_get_contents($apiUrl, false, $context); // Execute the request and get the response
echo $response; // Output the response from the API
?>
Output: Fraud detection results indicating whether the transaction is fraudulent or not.
<?php
$apiKey = 'your-predictive-analytics-api-key'; // Your API key for predictive analytics service
$apiUrl = 'https://api.predictiveanalytics.com/v1/predict'; // API endpoint for predictive analytics
$data = [
'historical_data' => 'Previous sales data to predict future trends.' // The historical data for prediction
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for request
'method' => 'POST', // Request method is POST
'content' => json_encode($data) // Encode data as JSON
]
];
$context = stream_context_create($options); // Create the stream context with options
$response = file_get_contents($apiUrl, false, $context); // Execute the request and get the response
echo $response; // Output the response from the API
?>
Output: Predicted future sales trends based on the input data.
<?php
$apiKey = 'your-sentiment-analysis-api-key'; // Your API key for sentiment analysis service
$apiUrl = 'https://api.sentimentanalysis.com/v1/analyze'; // API endpoint for sentiment analysis
$data = [
'text' => 'I absolutely love this product! It works amazingly well.' // The text to analyze for sentiment
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set headers for request
'method' => 'POST', // Request method is POST
'content' => json_encode($data) // Encode data as JSON
]
];
$context = stream_context_create($options); // Create the stream context with options
$response = file_get_contents($apiUrl, false, $context); // Execute the request and get the response
echo $response; // Output the response from the API
?>
Output: Sentiment score (e.g., Positive)
<?php
$apiKey = 'your-facial-recognition-api-key'; // Your API key for facial recognition service
$apiUrl = 'https://api.facialrecognition.com/v1/recognize'; // API endpoint for facial recognition
$data = [
'image' => new CURLFile('face_image.jpg') // The image file to be analyzed
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the API request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key in the header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the data (image) to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the API
?>
Output: Detected faces and associated details such as names or IDs.
<?php
$apiKey = 'your-translation-api-key'; // Your API key for the translation service
$apiUrl = 'https://api.translation.com/v1/translate'; // API endpoint for translation
$data = [
'text' => 'Hello, how are you?', // The text to be translated
'source_language' => 'en', // The source language (English)
'target_language' => 'es' // The target language (Spanish)
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and authorization header
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode the data as JSON
]
];
$context = stream_context_create($options); // Create the context for the request
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: Translated text (e.g., 'Hola, ¿cómo estás?')
<?php
$apiKey = 'your-music-generation-api-key'; // Your API key for the music generation service
$apiUrl = 'https://api.musicgeneration.com/v1/generate'; // API endpoint for music generation
$data = [
'style' => 'classical', // The style of music to generate (e.g., classical)
'duration' => '3' // Duration of the generated music in minutes
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and authorization header
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode the data as JSON
]
];
$context = stream_context_create($options); // Create the context for the request
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: Generated music file in the specified style.
<?php
$apiKey = 'your-video-generation-api-key'; // Your API key for the video generation service
$apiUrl = 'https://api.videogeneration.com/v1/generate'; // API endpoint for video generation
$data = [
'text' => 'This is a sample video description for AI to generate a video.' // Text input for video generation
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and authorization header
'method' => 'POST', // Set the HTTP method to POST
'content' => json_encode($data) // Encode the data as JSON
]
];
$context = stream_context_create($options); // Create the context for the request
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: Generated video based on the provided text or images.
<?php
$apiKey = 'your-style-transfer-api-key'; // Your API key for the style transfer service
$apiUrl = 'https://api.imagetransfer.com/v1/style-transfer'; // API endpoint for style transfer
$data = [
'image' => new CURLFile('original_image.jpg'), // The original image to apply style transfer to
'style_image' => new CURLFile('style_image.jpg') // The image that defines the desired style
];
$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL to the API endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Set the API key for authorization
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the data to the request
$response = curl_exec($ch); // Execute the cURL request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the API
?>
Output: The transformed image with the artistic style applied.
<?php
$apiKey = 'your-text-summary-api-key'; // Your API key for the text summarization service
$apiUrl = 'https://api.textsummary.com/v1/summarize'; // API endpoint for text summarization
$data = [
'text' => 'A long text that needs to be summarized...' // The text that you want to summarize
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and authorization headers
'method' => 'POST', // Set the request method to POST
'content' => json_encode($data) // Attach the data to the request
]
];
$context = stream_context_create($options); // Create the stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: A short summary of the input text.
<?php
$apiKey = 'your-keyword-extraction-api-key'; // Your API key for keyword extraction service
$apiUrl = 'https://api.keywordextraction.com/v1/extract'; // API endpoint for keyword extraction
$data = [
'text' => 'AI is transforming the world by automating tasks and making processes more efficient.' // The text from which you want to extract keywords
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and authorization headers
'method' => 'POST', // Set the request method to POST
'content' => json_encode($data) // Attach the data to the request
]
];
$context = stream_context_create($options); // Create the stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the API
?>
Output: Extracted keywords (e.g., AI, world, automating, tasks, efficient).
<?php
$apiKey = 'your-chatbot-api-key'; // Your API key for the chatbot service
$apiUrl = 'https://api.chatbot.com/v1/ask'; // API endpoint for sending queries to the chatbot
$data = [
'query' => 'How can I reset my password?' // The question/query you want to ask the chatbot
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and authorization headers
'method' => 'POST', // Set the request method to POST
'content' => json_encode($data) // Attach the data to the request
]
];
$context = stream_context_create($options); // Create the stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the chatbot
?>
Output: A chatbot response to the customer's question.
<?php
$apiKey = 'your-data-cleaning-api-key'; // Your API key for the data cleaning service
$apiUrl = 'https://api.datacleaning.com/v1/clean'; // API endpoint for cleaning data
$data = [
'data' => 'Raw data with errors or inconsistencies.' // The data that needs cleaning
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Set the content type and authorization headers
'method' => 'POST', // Set the request method to POST
'content' => json_encode($data) // Attach the data to the request
]
];
$context = stream_context_create($options); // Create the stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the data cleaning service
?>
Output: Cleaned data with inconsistencies removed.
<?php
$apiKey = 'your-visual-search-api-key'; // Your API key for the visual search service
$apiUrl = 'https://api.visualsearch.com/v1/search'; // API endpoint for visual search
$data = [
'image' => new CURLFile('search_image.jpg') // The image file to be searched
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Add the API key in the request header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the image data to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the visual search service
?>
Output: Results of visual search, identifying objects or similar images.
<?php
$apiKey = 'your-speech-recognition-api-key'; // Your API key for the speech recognition service
$apiUrl = 'https://api.speechrecognition.com/v1/recognize'; // API endpoint for speech recognition
$data = [
'audio_file' => new CURLFile('audio_sample.wav') // The audio file to be recognized
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Add the API key in the request header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the audio data to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the speech recognition service
?>
Output: Recognized text from the voice command.
<?php
$apiKey = 'your-image-recognition-api-key'; // Your API key for the image recognition service
$apiUrl = 'https://api.imagerecognition.com/v1/recognize'; // API endpoint for image recognition
$data = [
'image' => new CURLFile('image.jpg') // The image file to be recognized
];
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $apiUrl); // Set the URL for the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey // Add the API key in the request header
]);
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Attach the image data to the request
$response = curl_exec($ch); // Execute the request and get the response
curl_close($ch); // Close the cURL session
echo $response; // Output the response from the image recognition service
?>
Output: A list of objects detected in the image, such as "dog", "cat", or "car".
<?php
$apiKey = 'your-translation-api-key'; // Your API key for the translation service
$apiUrl = 'https://api.translation.com/v1/translate'; // API endpoint for translation
$data = [
'text' => 'Hello, how are you?', // Text to be translated
'target_language' => 'es' // Target language (Spanish)
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey", // Headers for the request
'method' => 'POST', // Set the request method to POST
'content' => json_encode($data) // Attach the data to the request as JSON
]
];
$context = stream_context_create($options); // Create a stream context with the options
$response = file_get_contents($apiUrl, false, $context); // Send the request and get the response
echo $response; // Output the response from the translation service
?>
Output: Translated text (e.g., "Hola, ¿cómo estás?" for Spanish).
<?php
$apiKey = 'your-text-generation-api-key';
$apiUrl = 'https://api.textgen.com/v1/generate';
$data = [
'prompt' => 'Write a short story about a dragon and a knight.'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: AI-generated text, such as a short story about a dragon and a knight.
<?php
$apiKey = 'your-sentiment-analysis-api-key';
$apiUrl = 'https://api.sentimentanalysis.com/v1/analyze';
$data = [
'text' => 'I love this product, it’s amazing!'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Sentiment score (e.g., Positive sentiment)
<?php
$apiKey = 'your-speech-to-text-api-key';
$apiUrl = 'https://api.speechtotext.com/v1/convert';
$data = [
'audio' => new CURLFile('audio_input.wav')
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: Transcribed text from the speech in the audio file.
<?php
$apiKey = 'your-predictive-analytics-api-key';
$apiUrl = 'https://api.predictiveanalytics.com/v1/predict';
$data = [
'data' => [
['date' => '2023-01-01', 'value' => 150],
['date' => '2023-01-02', 'value' => 170],
['date' => '2023-01-03', 'value' => 160]
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Predicted values based on historical data trends.
<?php
$apiKey = 'your-object-detection-api-key';
$apiUrl = 'https://api.objectdetection.com/v1/detect';
$data = [
'image' => new CURLFile('image_with_objects.jpg')
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: List of objects detected in the image, along with their positions.
<?php
$apiKey = 'your-text-summarization-api-key';
$apiUrl = 'https://api.textsummarization.com/v1/summarize';
$data = [
'text' => 'Artificial Intelligence (AI) is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans and animals. Leading AI textbooks define the field as the study of "intelligent agents": any device that perceives its environment and takes actions that maximize its chance of successfully achieving its goals.'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: A brief summary of the provided text.
<?php
$apiKey = 'your-speech-recognition-api-key';
$apiUrl = 'https://api.speechrecognition.com/v1/recognize';
$data = [
'audio' => new CURLFile('speech_audio.wav')
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: Text transcript of the speech in the audio file.
<?php
$apiKey = 'your-chatbot-api-key';
$apiUrl = 'https://api.chatbot.com/v1/message';
$data = [
'message' => 'Hello, how are you?',
'session_id' => '123456'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: AI-generated response to the chatbot message (e.g., "I am doing well, thank you!")
<?php
$apiKey = 'your-recommendation-api-key';
$apiUrl = 'https://api.recommendations.com/v1/recommend';
$data = [
'user_id' => 123,
'items' => ['item1', 'item2', 'item3']
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: A list of personalized product or service recommendations.
<?php
$apiKey = 'your-anomaly-detection-api-key';
$apiUrl = 'https://api.anomalydetection.com/v1/detect';
$data = [
'data' => [100, 200, 150, 300, 1000, 120, 110]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Detected anomaly (e.g., the value "1000" is an anomaly).
<?php
$apiKey = 'your-data-analysis-api-key';
$apiUrl = 'https://api.dataanalysis.com/v1/analyze';
$data = [
'data' => [
['date' => '2023-01-01', 'sales' => 200],
['date' => '2023-01-02', 'sales' => 250],
['date' => '2023-01-03', 'sales' => 180]
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Data analysis insights, such as sales trends and patterns.
<?php
$apiKey = 'your-fraud-detection-api-key';
$apiUrl = 'https://api.frauddetection.com/v1/detect';
$data = [
'transaction_data' => [
'amount' => 1500,
'location' => 'New York',
'transaction_type' => 'purchase'
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Fraud detection result, such as "Fraudulent transaction detected."
<?php
$apiKey = 'your-image-recognition-api-key';
$apiUrl = 'https://api.imagerecognition.com/v1/recognize';
$data = [
'image' => new CURLFile('image.jpg')
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: Detected objects in the image (e.g., "cat", "dog").
<?php
$apiKey = 'your-nlp-api-key';
$apiUrl = 'https://api.nlp.com/v1/analyze';
$data = [
'text' => 'Artificial intelligence is transforming the world.'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Analysis of the text (e.g., sentiment, keywords).
<?php
$apiKey = 'your-video-processing-api-key';
$apiUrl = 'https://api.videoprocessing.com/v1/analyze';
$data = [
'video' => new CURLFile('video.mp4')
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: Video analysis results (e.g., detected faces, motion).
<?php
$apiKey = 'your-object-tracking-api-key';
$apiUrl = 'https://api.objecttracking.com/v1/track';
$data = [
'video' => new CURLFile('tracking_video.mp4')
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Api-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Output: Object tracking data (e.g., coordinates of the tracked object).
<?php
$apiKey = 'your-predictive-analytics-api-key';
$apiUrl = 'https://api.predictiveanalytics.com/v1/predict';
$data = [
'data' => [
['month' => 'January', 'sales' => 100],
['month' => 'February', 'sales' => 150],
['month' => 'March', 'sales' => 130]
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Predicted sales for the next quarter.
<?php
$apiKey = 'your-data-classification-api-key';
$apiUrl = 'https://api.dataclassification.com/v1/classify';
$data = [
'data' => ['email_subject' => 'Special Offer on Electronics!']
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Classification result (e.g., "Promotional Email").
<?php
$apiKey = 'your-sentiment-analysis-api-key';
$apiUrl = 'https://api.sentimentanalysis.com/v1/analyze';
$data = [
'text' => 'I love this product, it works perfectly!'
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
echo $response;
?>
Output: Sentiment analysis result (e.g., "Positive sentiment").