Basic synthesis of learning PHP programming for beginners (p2)

Basic synthesis of learning PHP programming for beginners (p2)

Welcome back to the basic programming lesson at tuandc.com. If you have not read part 1 of this article, please review Here. In this section we will go through the remaining 8 sections in basic PHP programming.

9. Browser redirection in PHP

To redirect in PHP we can use the function header(). The syntax of this function is as follows:

header ($string, $replace = true, $http_response_code = null) {}

Inside::

  • $string: This series will tell you what to do next.
  • $replace: This parameter defaults to true, which means the string replaces, and so you leave it without many headers
  • $http_response_code: Server code returned. as 404 is not found or 301 is intentional redirection,…

Some examples are as follows

//Redirect to 1 page
header('Location: http://www.domain.net/');

//Redirect the destination to a page
header('Location: http://www.domain.net/', true, 301);

//404 redirects like switching from pages not found to the home page
header('Location: http://www.domain.net/', true, 404);

//Redirect downloading files instead of using download links
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"download.js\"");

10. GET & POST

There are 2 common methods to send data to the server, that is GET and POST.

GET method in PHP

This method is sent to the server by sending the keys and values assigned behind the “?” of the URL. For example

http://www.test.com/index.htm?namea=value1&nameb=value2

This method is not a secure method, it is not encrypted and displayed publicly. The maximum number of characters for this method is 1024 characters. You can use this method to search, retrieve actions, get article ids, … not allowed for passwords, card numbers, sensitive information, ….

To send data by this method, you create the Form as follows:

<form action="php file is transmitted" method="GET">
     Họ tên: <input type="text" name="name" />
     Tuổi: <input type="text" name="age" />
     <input type="submit" />
 </form>

These variables will be taken as follows

$ten = $_GET["name"]
$tuoi = $_GET["age"]

POST method in PHP

This method uses HTTP headers to transmit information to the server. This method is much more secure by encrypting and decrypting the server. However, many cases of hackers can still steal your data. SSL is added to help you transfer data more securely.

To send this data, you can change the GET method to POST in the form only.

<form action="php file is transmitted" method="POST">
     Họ tên: <input type="text" name="name" />
     Tuổi: <input type="text" name="age" />
     <input type="submit" />
</form>

To receive this data is similar

$ten = $_POST["name"]
$tuoi = $_POST["age"]

11. Insert file (File Inclusion)

You use this way to insert different files into a file, such as header, footer, sidebar, … To insert a file we have two functions that are include()andrequire().

The include() function in PHP

This function will take the entire contents of the included file and insert it into the current file. When the error arises, it still works and generates some warning lines. Usage is as follows:

<html>
  <body>
     <?php include("header.php"); ?>
     <p>An example of how to include header.php!</p>
  </body>
</html>

The above code will insert the header.php file content into the current file.

The require() function in PHP

Similar to include, however, when an error arises, it does not work and indicates a fatal error. This is necessary if the file you need to insert is very important in the entire content displayed. Similar usage.

<html>
  <body>
     <?php require("header.php"); ?>
     <p>Illustrative example of how to require header.php!</p>
  </body>
</html>

12. Open / Close and Read / Write files

Open the file in PHP

To open the file in PHP we use the fopen function. Syntax fopen ($path, $option). In which $path is the path to the file, $option is the right to manipulate.

Ví dụ

 $path = 'demo.txt';
 $fo = @fopen($path, "r");
 // Does the file open successfully?
 if (!$fo) {
 echo 'Open file failed';
 }
 else{
   echo 'Open file successfully';
 }

Read the file in PHP

There are three ways to read the file in PHP: read each character using fgetc ($fo), read each line using fgets ($fo), use feof ($fo) and while loop to read each line and character , and finally read through the file using fread ($fp, $size). Where $fo is the object that opens the @fopen file, $size is the file size to read. You can use filesize ($path) to get the file size.

Example of reading each file character in PHP

$fo = @fopen('demo.txt', "r");
// Does the file open successfully?
  if (!$fo) {
     echo 'Open file failed';
  }
  else
  {
     // Repeat over each letter to read
     while(!feof($fo))
     {
        echo fgetc($fo);
     }
  }

Example of reading each file line in php

  $fo = @fopen('demo.txt', "r");
   // Does the file open successfully?
   if (!$fo) {
      echo 'Open file failed';
   }
   else
   {
       // Repeat through each line to read
       while(!feof($fo))
      {
        echo fgets($fo);
      }
   }

Example of reading all files in PHP

  $fo = @fopen('demo.txt', "r");
  // Does the file open successfully?
  if (!$fo) {
      echo 'Open file failed';
   }
   else
   {  
   // Read files and return content
     $data = fread($fo, filesize('demo.txt'));
     echo $data;
   }

Write files in PHP

To write the file in PHP use the fwrite function ($fo, $content). Where $fo is the object that opens the @fopen file, $content is the content you want to write to. Examples are as follows:

  $fo = @fopen('demo.txt', "w");   
  // Does the file open successfully?   
  if (!$fo) {       
       echo 'Open file failed';   
  } else   
     { 
       $data = 'Content to write to file';        
       fwrite($fo, $data);   
     }

Close the file in PHP

If you open the file without closing it will cause some serious errors, to close the file please use fclose ($fo). $fo is an open object of the @fopen file, specific example:

  $fo = @fopen('demo.txt', "w");   
  // Does the file open successfully?   
  if (!$fp) 
  { echo 'Open file failed';}   
  else
  { $data = 'Content to write to file';  
    // Write file  
    fwrite($fp, $data);       
    // Close the file      
    fclose($fp);   
  }

Other necessary file handling functions

Check the existence of File in PHP

 if (file_exists('demo.txt'))  { echo 'File exists';  }
Check the write permissions of the file in PHP
$fp = @fopen('demo.txt', "w"); // Does the file open successfully? 
if (!$fp) {
    echo 'Open file failed'; }  
else {     
    if (is_writable ('demo.txt')) {fwrite($fp, 'Welcome');}  
 fclose($fp); }
Get the content of the file without using the file reader function in PHP:
// Get the file content 
echo file_get_contents('demo.txt');
Write the content for the file without using the file writing function in PHP:
file_put_contents('demo.txt', 'content');
Rename the file by rename method in PHP:
rename('demo.txt', 'demo2.txt');

Note: “r”, “w” are the execution modes. There are 6 execution modes as follows:

Mode Purpose
r  

Open the file and read only.

r+  

Open the file to read and write

w  

Open the write-only file, and create the file if it doesn’t already exist.

w+ Open the read and write file, and create the file if it doesn’t already exist.
a  

Open the file for recording only

a+  

Open the file to read and write, create the file if it doesn’t already exist.

13. PHP functions

Functions are one of the most important and popular, not just PHP, but most programming languages have functions. Function syntax is as follows:

/* Function definition */
  function ham()
  {
     echo "This is the string printed from the function";
  }
 /* Call the function */
 ham();

You can also pass parameters to the function to handle the following

   function hamTinh($num1, $num2)
   {
     $sum = $numa + $numb;
     echo "Total two numbers are: $sum";
  }
  hamTinh(12, 23);

The function that returns the value is written as follows

   function hamTinh2($num1, $num2)
   {
      $sum = $numa + $numb;
      return $sum;
   }
   $giaTriTraVe = hamTinh2(12, 23);

14. Cookie

Cookies are stored on clients for monitoring. When client browsers access a cached domain, cookie contents are sent to the server and can be used $_COOKIE or $HTTP_COOKIE_VARS["name cookie"].

Set client cookies to use PHP

setcookie(name, value, expire, path, domain, security);

Inside:

  • Name − Set the name of Cookie, this variable is used to access Cookies.
  • Value − Is the content you really want to store Cookies.
  • Expiry − Is the expiry date of the cookie, as of January 1, 1970. When it expires, cookies will not be used.
  • Path − Where the cookie is valid. The cross (/) allows Cookie to be valid on all folders.
  • Domain − Determine the domain name for which Cookie is valid.
  • Security −It can be set to 1 to indicate that this Cookie is only sent by secure transmission using HTTPS, whereas if set to 0, it means that Cookies can be sent using regular HTTP.

Examples are as follows:

<?php
  setcookie("name", "Nguyen Van Minh", time()+3600, "/","", 0);
  setcookie("age", "25", time()+3600, "/", "", 0);
?>

The above cookies will expire in 1 hour, be allowed to store on all directories and it can be sent by regular http.

Access cookies using PHP

You can access the code in two ways

 echo $_COOKIE["name"]. "<br />";
 /* is equal to */
 echo $HTTP_COOKIE_VARS["name"]. "<br />";

The isset function should be used to check for the existence of a cookie

 <?php
  if( isset($_COOKIE["name"]))
  echo "Welcome " . $_COOKIE["name"] . "<br />";
  else
  echo "No cookies found ...!!!" . "<br />";
 ?>

Delete cookies using PHP

To delete cookies that your website has stored on the client, you can set to show the browser that the cookie has expired by:

setcookie( "name", "", time()- 60, "/","", 0);

15. Session

Session or session will be created and stored on the server.

Create Session variable

Session variables will be stored in $_SESSION[] code. For example, to store a login user you can create the following:

$_SESSION['user'] = $user;

Use Session variable

Session variables can be used as a storage variable or can be used to check the required requirements. Examples are as follows

$user = $_SESSION['user']; Or use isset () to check for the existence of a variable.

Cancel the Session variables

To cancel a session variable specified you use unset($_SESSION['user']);

To cancel all Session variables you use session_destroy();

16. Upload file

Downloading files such as images, audio, video, etc. on the website is the job required by most websites. To do this, we use the Upload file method with the variable $_FILES.

Create file upload form in PHP

   <form method="post" action="" enctype="multipart/form-data">         
     <input type="file" name="avatar"/>         
     <input type="submit" name="uploadclick" value="Upload"/>     
   </form>

Specific handling code is as follows:

<?php 
// Upload Processing      
// If user clicks Upload      
if (isset($_POST['uploadclick'])){          
// If the user has selected the file to upload          
if (isset($_FILES['avatar'])){              
// If the upload file is not corrupted,             
// That is the error attribute> 0            
if ($_FILES['avatar']['error'] > 0)
{echo 'Failed Upload File'; }              
else{ // Upload file                  
move_uploaded_file($_FILES['avatar']['tmp_name'], './folder/'.$_FILES['avatar']['name']);                  echo 'File Uploaded'; }          }          else{ echo 'Bạn chưa chọn file upload'; }      } ?>

Note: move_uploaded_file () will have two parameters, $ client_path and $ server_path, with $ client_path as the client file path, this will be taken from the form. and $ server_path is the path at the server you want to save the file name at the end. You can customize this name accordingly to avoid duplication like extra days, …

Good luck !

Related post
View