12 résultats taggé php

Remplacement propre des caractères spéciaux en PHP

function filtre($string) {
    $search = array ('@(é|è|ê|ë|Ê|Ë)@','@(á|ã|à|â|ä|Â|Ä)@i','@(ì|í|i|i|î|ï|Î|Ï)@i','@(ú|û|ù|ü|Û|Ü)@i','@(ò|ó|õ|ô|ö|Ô|Ö)@i','@(ñ|Ñ)@i','@(ý|ÿ|Ý)@i','@(ç)@i','@( )@i','@(^a-zA-Z0-9_)@', '@(\'|\.)@');
    $replace = array ('e','a','i','u','o', 'n', 'y', 'c','-','', '');
    $in = preg_replace($search, $replace, $string);
    $in = preg_replace('/([^.a-z0-9]+)/i', '-', $string);
    return strtolower($string);
}

The Perfect URL Regular Expression

%^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/
<‍input type="url" /‍>
SELECT field FROM table 
WHERE field 
REGEXP "^(https?://|www\\.)[\.A-Za-z0-9\-]+\\.[a-zA-Z]{2,4}

PHP: tricking highlight_file to use CSS classes instead of inline styles

<?php
# Author: Andy Wrigley wptest.means.us.com
ini_set('highlight.default', '"class="aw_default');
ini_set('highlight.keyword','"class="aw_keyword'); 
ini_set('highlight.string', '"class="aw_string');
ini_set('highlight.html', '"class="aw_htmlsrc');
ini_set('highlight.comment', '"class="aw_comment');
$aw_source = highlight_file('your_sourcefile.ext', TRUE);
echo str_replace('style="color: "', '' , $aw_source );
?>

Virer tous les accents d’une chaîne unicode (latin)

$texte = htmlentities($texte, ENT_QUOTES, 'UTF-8');
$texte = preg_replace('#&([a-z]{1,2})(acute|grave|circ|uml|cedil|tilde|ring|slash|caron|lig);#', '$1', $texte);

Post slug generator, for creating clean urls from titles

<?php
function remove_accent($str)
{
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

function post_slug($str)
{
  return strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'),
  array('', '-', ''), remove_accent($str)));
}
?>

Example:

post_slug(' -Lo#&@rem  IPSUM //dolor-/sit - amet-/-consectetur! 12 -- ')
will output: lorem-ipsum-dolor-sit-amet-consectetur-12

Delete file in PHP

if (is_file($databaseFile)) {
        $success = unlink($databaseFile);
        if ($success) {
            $msg = 'Base purgée.';
        } else {
            $msg = 'La base n\'a pas pu être purgée. Supprimez le fichier data/base.php';
        }
    }

Export database in JSON

Depends of:
Write JSON file
Download a file

if (isset($_GET['export'])) {
    if (is_file('data/base.php')) {
        $export = 'data/go-export_'.date('Y-m-d_His').'.json';
        $success = writeJSON($base, $export);
        if ($success) {
            $success = downloadFile($export);
            if (!$success) {
                $msg = "Problème de téléchargement. Votre export est disponible à l'emplacement <a href='".$export."'>".$export."</a>";
            }
        } else {
            $msg = "Erreur d'écriture.";
        }
    } else {
        $msg = "Il n'y a rien à exporter."
    }
}

Import database in JSON

Depends of:
Upload a file
Read JSON file
Write JSON file

if (isset($_FILES['import'])) {
    $file = 'data/go-import.json';
    $success = uploadFile($_FILES['import'], $file);
    if (!is_array($success)) {
        $json = readJSON($file);
        if(is_array($json)) {
            foreach ($json as $code => $url) {
                $base[$code]=strip_tags($url);
            }
            save('data/base.php',$base);
            $msg = "Les liens ont bien été importés.";
        } else {
            $msg = "Erreur de lecture du fichier.";
        }
    } else {
        $msg = "Il y a eu un problème avec l'upload du fichier :";
        foreach ($success as $key => $value) {
            $msg .= "<br />" . $value;
        }
    }
}

Read JSON file

function readJSON($file) {
    $json = file_get_contents($file);
    $decoded = json_decode($json,true);
    if (is_array($decoded)) {
        unlink($file); // Delete after parsing
        return $decoded;
    } else {
        return false;
    }  
}

Write JSON file

function writeJSON($data, $file) {
    $fp = fopen($file, 'w');
    $result = fwrite($fp, json_encode($data));
    fclose($fp);
    if($result===false) {
        return $result;
    }
    return true;    
}

Upload a file

function uploadFile($file, $path) {
    $errors = [];
    $extensions = ['json'];
    $fileExtension = strtolower(end(explode('.',$file['name'])));

    // $uploadPath = $path . DIRECTORY_SEPARATOR . basename($file['name']);

    if (isset($_POST['submit'])) {
        if (!in_array($fileExtension, $extensions)) {
            $errors[] = "Ce type de fichier n'est pas accepté. Veuillez uploader un fichier JSON.";
        }
        if ($file['size'] > 2000000) {
            $errors[] = "La taille de ce fichier est supérieure à 2 Mo. Veuillez uploader un fichier plus léger.";
        }
        if (empty($errors)) {
            $success = move_uploaded_file($file['tmp_name'], $path);
            if ($success) {
                return true;
            } else {
                $errors[] = "Une erreur est survenue. Veuillez recommencer.";
            }
        }
        return $errors;
    }
}

Voir également https://cloudinary.com/blog/file_upload_with_php

Plus élégant niveau gestion des erreurs :

    if ($_FILES['fname']['error'] == 0 ) {
    move_uploaded_file($_FILES['fname']['tmp_name'], $_FILES['fname']['name']);
    echo "File uploaded successfully !!! <br />";
    echo "Filename : ". $_FILES['fname']['name'])."<br />";
    echo "Size : " . $_FILES['fname']['size']  . "<br />";
    }

    else {
    switch ($_FILES['fname']['error']) {
         case UPLOAD_ERR_NO_FILE:
                echo "Select a file to upload.";
            break;

         case UPLOAD_ERR_INI_SIZE:
            echo "The file size exceeds upload_max_filesize in php.ini";
            break;

         default:
        echo "Upload failed";
                break;
    }
    }

Download a file

function downloadFile($file) {
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        $result = readfile($file);
        unlink($file); // Delete after download and before the exit
        exit;
        if($result===false) {
            return $result;
        } 
    } else {
        return false;
    }
}