본문 바로가기

IT

PHP 예제 코드 17개

PHP 예제 코드 17개

PHP 예제 코드 17개
PHP 예제 코드 17개

 

1. Hello World:

<?php
echo "Hello World";
?>

 

2. Variables:

<?php
$name = "John Doe";
$age = 30;
echo "My name is $name and I am $age years old.";
?>

 

3. Arrays:

<?php
$fruits = array("apple", "banana", "cherry");
echo "I like eating " . $fruits[0] . ", " . $fruits[1] . " and " . $fruits[2] . ".";
?>

 

4. Conditional Statements:

<?php
$age = 20;
if ($age >= 18) {
    echo "You are eligible to vote.";
} else {
    echo "You are not eligible to vote.";
}
?>

 

5. Loops:

<?php
for ($i = 1; $i <= 10; $i++) {
    echo $i . " ";
}

$fruits = array("apple", "banana", "cherry");
foreach ($fruits as $fruit) {
    echo $fruit . " ";
}
?>

 

6. Functions:

<?php
function greet($name) {
    echo "Hello $name";
}
greet("John");
?>

 

7. Form Processing:

<form action="process.php" method="post">
  Name: <input type="text" name="name"><br>
  Age: <input type="text" name="age"><br>
  <input type="submit" value="Submit">
</form> 

<!-- process.php -->
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = $_POST["name"];
  $age = $_POST["age"];
  echo "Hello $name, you are $age years old.";
}
?>

 

8. Database Connections:

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

9. File Upload:

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form> 

<!-- upload.php -->
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {

 

10. Sessions:

<?php
session_start();
$_SESSION["username"] = "John";
echo "Session is set.";

// On another page
session_start();
echo "Hello " . $_SESSION["username"];
?>

 

11. Cookies:

<?php
$cookie_name = "username";
$cookie_value = "John";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

// On another page
echo "Cookie '" . $cookie_name . "' is set to value '" . $_COOKIE[$cookie_name] . "'";
?>

 

12. JSON:

<?php
$json = '{"name":"John", "age":30, "city":"New York"}';
$obj = json_decode($json);
echo "Name: " . $obj->name . "<br>";
echo "Age: " . $obj->age . "<br>";
echo "City: " . $obj->city;
?>

 

13. Include and Require:

<!-- header.php -->
<header>
  <nav>
    <a href="#">Home</a> |
    <a href="#">About</a> |
    <a href="#">Contact</a>
  </nav>
</header>

<!-- index.php -->
<?php
include "header.php";
echo "Welcome to my website";
?>

 

14. Email:

<?php
$to = "receiver@example.com";
$subject = "Test email";
$message = "This is a test email";
$headers = "From: sender@example.com\r\n";
mail($to, $subject, $message, $headers);
echo "Email sent";
?>
I hope these examples help you in understanding the basics of PHP programming.

 

15. 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" name="submit">
</form>

<!-- upload.php -->
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}
// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

 

16. File Download:

<a href="download.php?file=myfile.txt">Download</a>

<!-- download.php -->
<?php
$file = $_GET["file"];
header("Content-Disposition: attachment; filename=" . basename($file));
readfile($file);
?>

 

17. Pagination:

<?php
// connect to database
$conn = mysqli_connect("localhost", "username", "password", "database");

// number of results to show per page
$results_per_page = 5;

// get the number of total results
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$number_of_results = mysqli_num_rows($result);

// calculate number of pages required
$number_of_pages = ceil($number_of_results/$results_per_page);

// get the current page
if (!isset($_GET['page'])) {
  $page = 1;
} else {
  $page = $_GET['page'];
}

// determine the starting result for the current page
$this_page_first_result = ($page-1)*$results_per_page;

// get the results for the current page
$sql = "SELECT * FROM users LIMIT " . $this_page_first_result . ',' .  $results_per_page;
$result = mysqli_query($conn, $sql);

// display the results
echo "<table>";
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['username'] . "</td>";
  echo "<td>" . $row['email'] . "</td>";
  echo "</tr>";
}
echo "</table>";

// display the links to the other pages
for ($page=1;$page<=$number_of_pages;$page++) {
  echo '<a href="index.php?page=' . $page . '">' . $page . '</a> ';
}

// close the database connection
mysqli_close($conn);
?>


홈페이지 / PHP / ASP /JAVA / JSP 유지보수

셈틀컴퍼니 1688-8802

 

PHP 유지보수, 홈페이지 유지보수, 웹사이트 유지보수, 셈틀컴퍼니

PHP,MySQL,홈페이지 유지보수, 웹사이트 유지보수,LINUX서버유지보수, 리눅스,윈도우서버 관리, JAVA, ASP, PHP 유지보수

samtle.com

 

캠핑/글램핑장 창업 및 실시간 예약솔루션 (에어바운스캠프)

셈틀컴퍼니 1688-8802

 

에어바운스캠프

에어바운스,캠핑장 운영,실시간 예약시스템

naeils.co.kr