Facebook

Monday, December 28, 2015

Function to generate clean url slugs from string with duplication check


Function to generate clean url slugs from string with duplication check


function generateClassifiedSlug($string, $id=0){
    //Set char set to UTF-8 - to manage accented characters
    setlocale(LC_ALL, "en_US.UTF8");
    //Remove everything except alphabets and digits
    $url_string=preg_replace("/[^a-z0-9]/i"," ", ltrim(rtrim(strtolower($string))));
    //Remove multiple spaces
    $url_string = preg_replace("/\s+/", " ", $url_string);
    //Replace space with dashes
    $newurl_string=str_replace(" ","-",$url_string);
    //Condition for add / update
    if(!empty($id) && $id!=0){
        $condition = "BlogId!='".$id."' AND ";
    }else{
        $condition ="";
    }
    $queryCount = 'SELECT blog_url from tblblogs WHERE '.$condition.'
                    blog_url LIKE "'.$newurl_string.'"';

    //Check duplicate
    $rqC = mysql_num_rows(mysql_query($queryCount));
    $i=0;
    while($rqC != 0) {
        $i++;
        //Add number to avoid duplicate
        $newurl_string = $newurl_string."-".$i;
        $queryCount = 'SELECT blog_url from tblblogs WHERE '.$condition.'
                    blog_url LIKE "'.$newurl_string.'-'.$i.'"';
        $rqC = mysql_num_rows(mysql_query($queryCount));
    }

    $newurl_string = $newurl_string.(!empty($i) ? "-".$i : "");

    return $newurl_string;
}

Sunday, December 6, 2015

php file upload: clean name of uploaded file, check for duplicate


File upload: clean name of uploaded file, check for duplicate
$config['upload_path'] = DIR_UPLOAD_BANNER;

$file_parts = pathinfo($_FILES['cms_banner_image']['name']);

//Clean file name, replace all specialcharacters with dahs "-" $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $file_parts['filename']);

//Replace multiple dash with single $file_name = preg_replace('/-+/', '-', $file_name); $config['file_name'] = $file_name.'.'.$file_parts['extension'];

//Check for duplicate file names $counter = 0;
while (file_exists($config['upload_path'].$config['file_name'])) {
    $counter++;
    $config['file_name'] = $file_name.'_'.
                           $counter.'.'.
                           $file_parts['extension'];
}