Snippet PHP

With snippet PHP, you can free your mind

  1. Convert Number Character to Japanese Number Character

    string function japanese($text) {
      $find = array('1', '2', '3', '4', '5', '6', '7', '8', '9');
      $replace = array('①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨');
      return strtr($text, array_combine($find, $replace));
    }
    
  2. Form File

    a. Check file uploaded success or fail

    bool is_uploaded_file($_FILES["import_file"]["tmp_name"])
    

    b. Get file info

    // server tmp path
    $_FILES["import_file"]["tmp_name"]
    // file name
    $_FILES["import_file"]["name"]
    // file type
    $_FILES["import_file"]["type"]
    // file size (bytes)
    $_FILES["import_file"]["size"]
    

    c. Move file from tmp to new directory

    move_uploaded_file($_FILES["import_file"]["tmp_name"], $destPathDir);
    
  3. Session

    a. Start session

    session_start();
    

    b. Usage session

    $_SESSION['name'] = 'Zero';
    

    c. Example

    session_start();
    $success = $_SESSION['success'];
    $error_list = $_SESSION['error'];
    if (empty($error_list)) {
      $error_list = array();
    }
    $_SESSION['success'] = null;
    $_SESSION['error'] = array();
    
  4. Redirect action to another page

    header("HTTP/1.1 301 Moved Permanently");
    header("Location: upload_csv_result.php");
    
  5. For Loop

    // foreach
    foreach ($collection as $index => $item) {
      if ($index > 0) {
        // your code;
      }
    }
    // for with defined range
    for ($i=0; $i<=10; $i++) {
      // your code;
    }
    
  6. String

    // split string to array
    array explode(",", $string);
    // join array to string
    string implode(",", $array);
    // concatenate string
    $new_str = $str1 . "_" . $str2;
    // check empty string
    empty($value) || $value == ""
    // check string with Regular Expression
    preg_match('/^[0-9]+$/', $value) == 1
    preg_match('/^[0-9]+\.[0-9]{1,2}$/', $value) == 1
    preg_match("/^UPCASE$/i", trim($type) == 1
    
  7. Array

    // initialize
    $result_list = array();
    // add item to array
    $result_list[] = "New Value";
    // count array items
    int count($result_list);
    // change item value with condition
    array_walk_recursive($input, 'refine');
    function refine(&$item, $key) {
      if ($item == "") {
        $item = 0;
      }
    }
    
  8. DateTime

    // parse string to Unix timestamp
    int strtotime($value);
    // format datetime with format
    string date('Ymd', strtotime($value));
    
  9. Read File Line by Line

    // use fgets()
    $handle = fopen("input.txt", "r");
    if ($handle) {
      while (($line = fgets($handle)) !== false) {
        // process the line read
      }
      fclose($handle);
    } else {
      // error opening the file
    }
    
  10. Parse CSV Line

    // use fgetcsv(file[,length][,separator][,enclosure])
    // length: maximum length of a line (must be greater than the longest line)
    // separator: field separator, default is comma ,
    // enclosure: field enclosure character, default is double quotes "
    $file= fopen("input.csv", "r");
    while (!feof($file)) {
      print_r(fgetcsv($file));
    }
    fclose($file);
    
  11. Formats Line as CSV and Write to File

    // use fputcsv(file,fields[,seperator][,enclosure])
    // fields: array to get the data from
    // separator: field separator, default is comma ,
    // enclosure: field enclosure character, default is double quotes "
    $list = array (
      "1,2,3,4,5",
      "A,B,C,D,E",
    );
    $file = fopen("output.csv","w");
    foreach ($list as $line) {
      fputcsv($file, explode(',', $line));
    }
    fclose($file);
    
  12. Generate Token for Confirmation Email or Forgot Password

    $token = base64_encode(openssl_random_pseudo_bytes(128));
    

Comments

Popular posts from this blog

Reduce TIME_WAIT Socket Connections