Hiển thị các bài đăng có nhãn code php. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn code php. Hiển thị tất cả bài đăng

Thứ Hai, 14 tháng 9, 2026

Mãn dữ liệu function code

$is_allowed = in_array((int)$mbrow["user_level"], array(3, 4, 5, 6));

$disabled_class = !$is_allowed ? 'disabled' : '';

$menu_items = array(

    array(

        'op'     => 'user_verified',

        'title'  => 'Profile',

        'active' => 'active'

    ),

    array(

        'op'     => 'page_create',

        'title'  => 'Page tự tạo (Giới thiệu, Giải pháp)',

        'active' => 'active'

    ),

    array(

        'op'     => 'supplier_pagemenu',

        'title'  => 'Tạo menu',

        'active' => 'select'

    ),

    array(

        'op'     => 'supplier_pagehome',

        'title'  => 'Giao diện trang chủ NCC',

        'active' => 'select'

    )

);

// 3. Xuất HTML dùng echo chuỗi (tương thích tốt với các CMS cũ như NukeViet)

echo'<ul>';

foreach ($menu_items as $item) {

    $is_active_class = ($op == $item['op']) ? $item['active'] : '';

    $link = $is_allowed ? $site_live .'modules.php?name=Your_Account&op='.$item['op'] : 'javascript:void(0);';

    echo '<li class="'.$is_active_class.' user-super '.$disabled_class.'">

        <a href="'.$link.'">

            <i class="fa fa-long-arrow-right"></i> ' . $item['title'] . '

        </a>

    </li>';

}

?>

<style type="text/css">

    /* Styling cho menu bị khóa */

    li.disabled {

        /* Làm mờ 60% */

        opacity: 0.4; 

        /* Đổi con trỏ chuột thành biểu tượng cấm */

        cursor: not-allowed; 

    }

    li.disabled a {

        /* Chặn hoàn toàn sự kiện click */

        pointer-events: none;

        /* Ép màu chữ thành xám */

        color: #999 !important;

    }

</style>

<?php

echo'</ul>';

Thứ Tư, 2 tháng 9, 2026

Thiết lập get dữ liệu đuôi.php cùng Module PHP

 


Đang sử dụng file Edit_Supplier.php và gọi đến file upload.momento.php

**** JS

function uploadMomentoFile_<?php echo $uniqueId; ?>() {

        

    var form = document.getElementById('form_<?php echo $uniqueId; ?>');

    var formData = new FormData(form);

    var status = document.getElementById('status_<?php echo $uniqueId; ?>');

    var targetUrl = '<?php echo rtrim($site_live, "/"); ?>/modules.php?name=Shoping&file=upload_momento';

    status.textContent = "Đang lưu ảnh...";

    fetch(targetUrl, {

        method: 'POST',

        body: formData

    })

    .then(function(response) {

        return response.text(); // Lấy dữ liệu thô dạng text

    })

    .then(function(text) {

        // Tách lọc lấy phần chuỗi JSON chuẩn {...} phòng trường hợp bị dính HTML

        var jsonStart = text.indexOf('{');

        var jsonEnd = text.lastIndexOf('}') + 1;

        

        if (jsonStart !== -1 && jsonEnd !== -1) {

            var cleanJson = text.substring(jsonStart, jsonEnd);

            var data = JSON.parse(cleanJson);


            if (data.success) {

                status.textContent = "Lưu thành công: " + data.filename;

                loadPanorama_<?php echo $uniqueId; ?>(data.url + '?v=' + new Date().getTime());

            } else {

                alert('Lỗi: ' + data.message);

                status.textContent = "Lưu thất bại!";

            }

        } else {

            console.error("Dữ liệu server trả về không phải JSON:", text);

            alert("Lỗi server trả về dữ liệu không hợp lệ! Kiểm tra Console (F12)");

            status.textContent = "Lỗi phản hồi!";

        }

    })

    .catch(function(err) {

        console.error(err);

        alert('Lỗi kết nối máy chủ!');

        status.textContent = "Lỗi tải lên!";

    });

}

Thứ Năm, 16 tháng 4, 2026

lấy giá trị form - code php ajax

 <form id="#send-supplier-fast">

<a id="tensanpham" href="'.$link.'" target="_blank" class="link">'.$title.'</a>            

<input type="text" placeholder="Số lượng"  name="soluong" oninput="this.value = this.value.replace(/[^0-9]/g, \'\')" required>

<textarea class="input-textarea" id="content" name="content" required></textarea> 

<button type="submit" id="inquirySend"></button>    

</form>

$(document).on('submit', '#send-supplier-fast', function (e) {

    e.preventDefault();

    const form = $(this);

    const btn  = $('#inquirySend');

    let formData = new FormData();

    // lấy data thường

    formData.append('soluong', $('input[name=soluong]').val());

    formData.append('donvitinh', $('select[name=donvitinh]').val());

    formData.append('content', $('#content').val());

    formData.append('senderMail', $('#senderMail').val());

    formData.append('pid', $('input[name=pid]').val());

    // formData.append('title', $('input[name=title]').val());

    formData.append('title', $('#tensanpham').text().trim());

    formData.append('userid', $('input[name=userid]').val());

    // chỉ append file từ selectedFiles

    selectedFiles.forEach(function(file) {

        if (file && file.size > 0) {

            formData.append('files[]', file);

        }

    });

    btn.prop('disabled', true).text('Đang gửi...');

    $.ajax({

        url: '/send-supplier-product',

        type: 'POST',

        data: formData,

        processData: false,

        contentType: false,

        dataType: 'json',

        success: function (res) {

            // console.log(res);

            if (res && res.status === 'success') {

                showNotify('✅ Gửi yêu cầu thành công!');

                form[0].reset();            

                window.location.href = '/?sendmail=' + res.mail_data.mail_id+ '&token=' + res.mail_data.token;

            } else {

                showNotify('❌ ' + (res.message || 'Có lỗi xảy ra'), 'error');

            }

        },

        error: function () {

            showNotify('❌ Lỗi server', 'error');

        },

        complete: function () {

            btn.prop('disabled', false).text('Gửi yêu cầu');

        }

    });

});

Thứ Năm, 12 tháng 3, 2026

Lấy userid duy nhất trong vòng lặp + Câu lệnh sql FIND_IN_SET

 Ví dụ:

pid 1 → userid 10
pid 2 → userid 10
pid 3 → userid 9

→ kết quả cần:

9,10 -------------------- $sum = 0;
$json_data = array();
$list_userid = array();

foreach($data_sp as $sp){

$total = $sp['g_count'] * $sp['g_price'];
$sum += $total;
$pid = $sp['g_pid'];

$shopemail = RETURN__CatalogSPShop__shopname($pid);
$userid = RETURN__UserID__Email($shopemail);

/* lưu userid */
$list_userid[] = $userid;

$json_data[] = array(
"gid" => $sp['gid'],
"g_pid" => $sp['g_pid'],
"g_price" => $sp['g_price'],
"g_point" => $sp['g_point'],
"g_count" => $sp['g_count'],
"g_code" => $sp['g_code'],
"g_title" => $sp['g_title'],
"total" => $total,
"userid" => $userid,
"is_view" => 0
);
}

/* lấy userid duy nhất */

$list_userid = array_unique($list_userid);

/* nếu muốn dạng chuỗi */

$userid_string = implode(",", $list_userid);

echo $userid_string; -------------------- $list_userid = [10,10,9]

array_unique →

[10,9]

implode →

"10,9" ---------------------

$sql = "SELECT *
FROM orders
WHERE FIND_IN_SET('$userid', order_shopids)
ORDER BY order_date DESC";

$rs = mysql_query($sql);

Thứ Hai, 2 tháng 3, 2026

ShopOrder - Show đơn hàng thuộc shopname

$shopid = $userid;

$sql = "SELECT * FROM  shop_orders";

$result = $db->sql_query($sql);

while($row = $db->sql_fetchrow($result)){

    $items = json_decode($row['order_text'], true);

    foreach($items as $item){

        if($item['shop_id'] == $shop_id){

            echo "Sản phẩm: ".$item['g_title'];

            echo " - Khách: ".$row['order_uname'];

            echo "<br>";

        }

    }

}

Thứ Ba, 25 tháng 11, 2025

Thay đổi ngôn ngữ ngay đường link không cần quay về trang chủ

#### MMLABEL #### 


#### Áp dụng vào ngôn ngữ 2 lá cờ ANH - VIỆT 
$urls = $this->get_lang_urls($op, $currentlang);

$vn_url = $urls['vn'];

$en_url = $urls['en'];  


#### Các Funtion

public function get_lang_urls($op, $currentlang) {

        

    $current_url = $_SERVER['REQUEST_URI'];

    $current_path = parse_url($current_url, PHP_URL_PATH);

    $segments = explode('/', trim($current_path, '/'));

    $slug_con = strtolower(end($segments));


    // map chính từ data_superlink

    $data_chill = data__superlink();  

    $super1 = explode("**", $data_chill['super1']);  

    $super2 = explode("**", $data_chill['super2']);  

    $map_main = array();  

    foreach ($super1 as $k => $v) {  

        $map_main[$v] = isset($super2[$k]) ? $super2[$k] : '';  

    }  


    // map phụ theo op và ngôn ngữ

    switch ($op) {  

        case 'display_category':  

            $ch_title = $this->ShopCid__Title__lang($slug_con);  

            break;  

        case 'display_product':  

            $ch_title = $this->ShopPid__Title__lang($slug_con);  

            break;  

        case 'page_category':  

            $ch_title = $this->pageCatgory__Catidlink__lang($slug_con);  

            break;  

        case 'page_detail':  

            $ch_title = $this->pageDetail__Sidlink__lang($slug_con);  

            break;  

        default:  

            $ch_title = '';  

            break;  

    }  


    $map_sub = ($currentlang == "vietnamese" && $ch_title) ? array($slug_con => $ch_title) : ($ch_title ? array($ch_title => $slug_con) : array());  


    $links = $this->mobi__switch_language_url($current_url, $map_main, $map_sub);  


    return array(  

        'vn' => $links['vn'],  

        'en' => $links['en']  

    );  

        

}

#### Function 2

public function ShopCid__Title__lang($cidlink){


    global $db,$prefix,$site_live,$currentlang;


    $langid = get_lang_id();


    // Chuẩn hóa slug con

    $cidlink = strtolower($cidlink);


    $sql ="SELECT a.cid 

    FROM ".$prefix."_shop_categories a,

    ".$prefix."_shop_categories_lang b  

    WHERE a.cid=b.cid 

    AND LOWER(b.cid_link) = LOWER('".$cidlink."')

    AND b.lang_id=$langid";     


    $rs = $db->sql_query($sql);

    $row = $db->sql_fetchrow($rs);


    if(!$row){

        return ''; // Không tìm thấy → tránh báo lỗi

    }


    $cid = $row["cid"];


    // Đổi: VN → EN hoặc EN → VN

    if($langid==1){

        return $this->cidlink__tienganh($cid,2);

    }else{

        return $this->cidlink__tienganh($cid,1);

    }

}



public function ShopPid__Title__lang($pidlink){


    global $db,$prefix,$site_live,$currentlang;


    $langid = get_lang_id();


    $sql ="select a.pid from ".$prefix."_shop a,".$prefix."_shop_lang b where a.pid=b.pid AND b.pid_link ='".$pidlink."' and b.lang_id=".$langid;

    // echo $sql;

    $rs  = $db->sql_query($sql);

    $data = array();

    $row = $db->sql_fetchrow($rs);

    $pid = $row["pid"];


    if($langid==1){

        return  $this->pidlink__tienganh($pid,2);

    }else{

        return  $this->pidlink__tienganh($pid,1);

    }

}


public function pageCatgory__Catidlink__lang($catid_link){


    global $db,$prefix,$site_live,$currentlang;


    $langid = get_lang_id();


    $sql ="select catid from ".$prefix."_stories_cat_lang where catid_link ='".$catid_link."' and lang_id=".$langid;

    // echo $sql;

    $rs  = $db->sql_query($sql);

    $data = array();

    $row = $db->sql_fetchrow($rs);

    $catid = $row["catid"];


    if($langid==1){

        return $this->catidlink__tienganh($catid,2);

    }else{

        return $this->catidlink__tienganh($catid,1);

    }

}


public function pageDetail__Sidlink__lang($sid_link){


    global $db,$prefix,$site_live,$currentlang;


    $langid = get_lang_id();


    $sql ="select sid from ".$prefix."_stories where sid_link ='".$sid_link."' and langid=".$langid;

    // echo $sql;

    $rs  = $db->sql_query($sql);

    $data = array();

    $row = $db->sql_fetchrow($rs);

    $sid = $row["sid"];


    if($langid==1){

        return $this->sidlink__tienganh($sid,2);

    }else{

        return $this->sidlink__tienganh($sid,1);

    }

}


#### Function 3

public function cidlink__tienganh($cid,$langid){


    global $db,$prefix,$site_live,$currentlang;


    $sql ="select * from ".$prefix."_shop_categories_lang  where cid ='".$cid."' and lang_id=$langid";

    // echo $sql;

    $rs  = $db->sql_query($sql);

    $data = array();

    while($row = $db->sql_fetchrow($rs)){

        $cid_link = $row["cid_link"];

        return $cid_link;       

    }

}


public function pidlink__tienganh($pid,$langid){


    global $db,$prefix,$site_live,$currentlang;


    $sql ="select * from ".$prefix."_shop_lang  where pid ='".$pid."' and lang_id=$langid";

    // echo $sql;

    $rs  = $db->sql_query($sql);

    $data = array();

    while($row = $db->sql_fetchrow($rs)){

        $pid_link = $row["pid_link"];

        return $pid_link;       

    }

}


public function catidlink__tienganh($catid,$langid){


    global $db,$prefix,$site_live,$currentlang;


    $sql ="select * from ".$prefix."_stories_cat_lang  where catid ='".$catid."' and lang_id=$langid";

    // echo $sql;

    $rs  = $db->sql_query($sql);

    $data = array();

    while($row = $db->sql_fetchrow($rs)){

        $catid_link = $row["catid_link"];

        return $catid_link;     

    }

}


public function sidlink__tienganh($sid,$langid){


    global $db,$prefix,$site_live,$currentlang;


    $sql ="select * from ".$prefix."_stories where sid ='".$sid."' and langid=$langid";

    // echo $sql;

    $rs  = $db->sql_query($sql);

    $data = array();

    while($row = $db->sql_fetchrow($rs)){

        $sid_link = $row["sid_link"];

        return $sid_link;       

    }

}


#### Note: code cơ bản ban đầu (code thuần), chưa đưa dữ liệu vào.


// $current_url = "/San-pham/nhan-decal-trong-nha";

// $map_main = array(

    'San-pham' => 'Product'

);

// $map_sub = array(

    'nhan-decal-trong-nha' => 'indoor-decals'

);


// $map_main = array(

//     'gioi-thieu' => 'about-us',

//     'tin-tuc-su-kien'  => 'news-event',

//     'tin-tuc'     => 'news',

//     'Tin-tuc'     => 'News',

//     'lien-he'    => 'contact-us',

//     'San-pham'   => 'Product',

//     'san-pham'   => 'product',

//     'trang-chu'  => 'home-page',

// );

👉 Cách 2:

///////////////////////////////////////////////////////////////////////////////////////////////

KEIEIJUKU

function google_translate_web(){
    ?>

    <!-- Ẩn widget gốc -->
    <div id="google_translate_element" style="display:none;"></div>

    <!-- Nút chọn ngôn ngữ -->
    <!-- <div id="translateBox">
        <button onclick="changeLang('vi')">🇻🇳 VI</button>
        <button onclick="changeLang('en')">🇺🇸 EN</button>
        <button onclick="changeLang('zh-CN')">🇨🇳 中文</button>
        <button onclick="changeLang('ko')">🇰🇷 한국어</button>
        <button onclick="changeLang('ja')">🇯🇵 日本語</button>
    </div> -->

    <style type="text/css">
        #translateBox {
            position: fixed;
            top: 80px;
            right: 30px;
            z-index: 9999;
        }

        #translateBox button {
            margin: 2px;
            padding: 6px 10px;
            border: none;
            background: #eee;
            cursor: pointer;
            border-radius: 5px;
            font-size: 13px;
        }

        #translateBox button:hover {
            background: #ddd;
        }

        /* Ẩn thanh Google */
        .goog-te-banner-frame.skiptranslate {
            display: none !important;
        }

        .goog-te-banner-frame,
        .goog-logo-link,
        .goog-te-gadget {
            display: none !important;
        }
        /* Ẩn toàn bộ Google Translate */
        .skiptranslate {
            display: none !important;
        }

        /* Fix lỗi bị đẩy trang xuống */
        body {
            top: 0 !important;
        }
        .languageTop .popup li a img {
            width: 25px;
            height: 18px;
            border: 1px solid rgba(0, 0, 0, 0.1);
        } 

    </style>

    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function () {

            var langMap = {
                "vi": "Tiếng Việt",
                "en": "English",
                "ja": "日本語",
                "ko": "한국어",
                "zh": "中文"
            };

            function getCookie(name) {
                var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
                if (match) return match[2];
                return null;
            }

            var lang = 'vi';

            // 👉 Ưu tiên Google Translate
            var match = document.cookie.match(/googtrans=\/vi\/(.*?)($|;)/);
            if (match) {
                lang = match[1];
            } else {
                lang = getCookie('site_lang') || 'vi';
            }

            // 👉 chuẩn hóa
            lang = lang.toLowerCase();
            if (lang.indexOf('-') !== -1) {
                lang = lang.split('-')[0];
            }

            var el = document.getElementById("selected-lang");
            if (el && langMap[lang]) {
                el.childNodes[0].nodeValue = langMap[lang] + " ";
            }

        });
    </script>
    

    <script>
        window.__gt_inited = false;

        // INIT GOOGLE
        function googleTranslateElementInit() {
            if (window.__gt_inited) return;
            window.__gt_inited = true;

            new google.translate.TranslateElement({
            pageLanguage: 'vi',
            includedLanguages: 'vi,en,ja,ko,zh-CN',
            autoDisplay: false,
            multilanguagePage: true
            }, 'google_translate_element');
        }

        // ĐỔI NGÔN NGỮ
        function changeLang(lang) {

            // Xóa cookie cũ
            document.cookie = "googtrans=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;";

            // googtrans (Google dùng)
            document.cookie = "googtrans=/vi/" + lang + "; path=/; domain=" + location.hostname+ "; max-age=2592000";

            // cookie riêng của bạn
            document.cookie = "site_lang=" + lang + "; path=/; domain=" + location.hostname + "; max-age=2592000";

            // Lưu lại
            localStorage.setItem("lang", lang);

            // Reload
            setTimeout(function () {
            location.reload();
            }, 200);
        }

            // LẤY NGÔN NGỮ HIỆN TẠI
        function getCurrentLang() {
            var match = document.cookie.match(/googtrans=\/vi\/(.*?)($|;)/);
            return match ? match[1] : 'vi';
        }

            // AUTO LOAD NGÔN NGỮ
            window.addEventListener("load", function () {

            var lang = localStorage.getItem("lang") || getCurrentLang();

            if (lang && lang !== 'vi') {
                document.cookie = "googtrans=/vi/" + lang + "; path=/; domain=" + location.hostname + "; max-age=2592000";
            }

        });
    </script>

    <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    <?php
}

function languageTop__supplier(){
        
    global $site_live, $currentlang, $ThemeSel,$op,$module_name;    

     $lang_num = 1; // mặc định VI

    if (isset($_COOKIE['site_lang_num'])) {
        $lang_num = intval($_COOKIE['site_lang_num']);
    }

    if (!in_array($lang_num, array(1,2,3,4,5))) {
        $lang_num = 1;
    }


    $LANG = array(

        1 => array(
            'content'   => '1',
            'icon'      => 'vi',
            'ngonngu'   => 'Tiếng Việt',
        ),

        2 => array(
            'content'   => '2',
            'icon'      => 'en',
            'ngonngu'   => 'English',
        ),
        
        
        3 => array(
            'content'   => '3',
            'icon'      => 'ja',
            'ngonngu'   => 'Japanese',
        ),
        4 => array(
            'content'   => '4',
            'icon'      => 'ko',
            'ngonngu'   => 'Korean',
        ),
        5 => array(
            'content'   => '5',
            'icon'      => 'zh-CN',
            'ngonngu'   => 'Chinese',
        )
    );


    echo'<ul class="lang-switch language panel-items langList-options">';

        echo '<li class="option-lang">
            <a class="nail-link" href="javascript:void(0)" onclick="changeLang(\'vi\')" translate="no">
                Tiếng Việt
            </a>
        </li>';

        echo '<li class="option-lang">
            <a class="nail-link" href="javascript:void(0)" onclick="changeLang(\'en\')" translate="no">
                English
            </a>
        </li>';
       

        echo'<li class="option-lang">
            <a class="nail-link" href="javascript:void(0)" onclick="changeLang(\'zh-CN\')" translate="no">
                Chinese
            </a>
        </li>

        <li class="option-lang">
            <a class="nail-link" href="javascript:void(0)" onclick="changeLang(\'ja\')" translate="no">
               Japanese
            </a>
        </li>

        <li class="option-lang">
            <a class="nail-link" href="javascript:void(0)" onclick="changeLang(\'ko\')" translate="no">
               Korean
            </a>
        </li>';

    echo'</ul>';


    echo'<div id="google_translate_element"></div>';
              
}

**** CSS
.rfq-form .title_wrap .langList .selected-lang {
    line-height: 21px;
    display: inline-block;
    padding: 5px 10px;
    border-radius: 3px;
}
.rfq-form .title_wrap .langList .langList-options {
    display: none;
    position: absolute;
    right: -1px;
    top: 100%;
    background: #fff;
    white-space: nowrap;
    padding: 5px 0;
    border: 1px solid #dae0e6;
    border-radius: 3px;
    box-shadow: 3px 3px 6px rgba(0, 0, 0, .15);
    z-index: 99;
    list-style: none;
}
.rfq-form .title_wrap .langList:hover .langList-options {
    display: block;
}
.rfq-form .title_wrap .langList:hover .selected-lang {
    color: #e64545;
}
.rfq-form .title_wrap .langList .langList-options::before {
    content: "";
    display: block;
    position: absolute;
    width: 7px;
    height: 7px;
    border-top: 1px solid #dae0e6;
    border-left: 1px solid #dae0e6;
    transform: rotate(45deg);
    background: #fff;
    top: -5px;
    left: auto;
    right: 13px;
}
.rfq-form .title_wrap .langList .langList-options a {
    padding: 5px 10px;
    font-size: 14px;
    display: block;
    color: #222;
}
.rfq-form .title_wrap .langList .langList-options a:hover {
    background: #e6ecf2;
    text-decoration: none;
}
.rfq-form .title_wrap .langList:hover .fa-icon {
    transform: rotate(-180deg);
}

**** HTML
<div class="langList">
    <span class="selected-lang" id="selected-lang">'.$LANG[$lang_num]['ngonngu'].'
    <i class="fa fa-angle-down fa-icon" aria-hidden="true"></i></span>';
    languageTop__supplier();    
</div>


Chủ Nhật, 5 tháng 10, 2025

Phân trang ngay Trang Chủ (pagination)

 

global $prefix,$currentlang,$db,$site_live,$multilingual,$ThemeSel;

$uil    = new Uil();

$thum   = new thumnail();

$whe    = $uil->getWhereCat("Duan",1);

if (isset($_POST['page'])) {

    // Số sản phẩm mỗi trang

    $limit = 9;

    // Trang hiện tại

    $page  = (int)$_POST['page'];

    if ($page < 1) $page = 1;

    // Vị trí bắt đầu

    $start = ($page - 1) * $limit;

    // Điều kiện ngôn ngữ

    if ($multilingual == 1) {

        $querylang = "AND (alanguage='$currentlang' OR alanguage='')";

    } else {

        $querylang = "";

    }

    // Điều kiện chuyên mục (tạm fix luôn = 1)

    // $whe = "catid=27";

    // Đếm tổng


    $sql_count = "SELECT COUNT(*) AS total

    FROM ".$prefix."_stories 

    WHERE $whe $querylang";


    $rs_count  = $db->sql_query($sql_count);

    $row_count = $db->sql_fetchrow($rs_count);

    $total     = $row_count['total'];

    $total_pages = ceil($total / $limit);


    // Lấy dữ liệu

    $sql = "SELECT * FROM ".$prefix."_stories 

    WHERE $whe $querylang 

    ORDER BY sid DESC

    LIMIT $start, $limit";

    $rs = $db->sql_query($sql);

    $data = array();

    while ($row = $db->sql_fetchrow($rs)) {

        $data[] = $row;

    }


    // Xuất HTML

    foreach ($data as $value) {


        $link = "/du-an/".$value['sid_link'];


        echo '<div class="catsp">

            <a href="'.$link.'" class="case-link">

                <img src="/uploads/News/pic/'.$value["images"].'" alt="">

                <p class="view">View</p>

            </a>

            <div class="title">'.$value["title"].'</div>

        </div>';

    }


    // Xuất nút phân trang

    if ($total_pages > 1) {

        echo '<div class="pagination">';

        for ($i = 1; $i <= $total_pages; $i++) {

            $active = ($i == $page) ? "active" : "";

            echo '<a href="#" class="page-link '.$active.'" data-page="'.$i.'">'.$i.'</a>';

        }

        echo '</div>';

    }

    exit; // Chặn không cho load phần HTML phía dưới

}

?>

    <div id="gallery" class="gallery"></div>

    <div id="loading"></div>

    <script>

    function load_data(page) {

        $.ajax({

            // url: "gallery.php",

            url: "/index.php?op=show__duan",

            type: "POST",

            data: {page: page},

            beforeSend: function() {

                $("#loading").html("<p>Đang tải...</p>");

            },

            success: function(data) {

                $("#gallery").html(data);

                $("#loading").html("");

            }

        });

    }


    // Load trang đầu tiên

    load_data(1);


    // Sự kiện click phân trang

    $(document).on("click", ".page-link", function(e) {

        e.preventDefault();

        var page = $(this).data("page");

        load_data(page);

    });


</script>


<style>


    .gallery {

        display: grid;

        grid-template-columns: repeat(3, 1fr);

        gap: 10px; /* khoảng cách đều nhau giữa các ảnh */

        width: 100%;

        height: auto; /* để auto chiều cao, đừng fix 100vh */

    }


    .gallery .catsp {

        position: relative;

        overflow: hidden;

        /*aspect-ratio: 1/1;  hoặc bỏ nếu muốn giữ theo tỉ lệ ảnh */

        /* aspect-ratio: 16/9; hình nằm ngang */

        aspect-ratio: 4/3; /* cao hơn 16/9 */

        border-radius: 8px;

    }

    .catsp img {

        width: 100%;

        height: 100%;

        object-fit: cover;

        transition: transform 0.5s ease;

        display: block;

    }

    .catsp:hover img {

        transform: scale(1.05);

    }


    /* Title luôn có nhưng animate khi load */

    .title {

        position: absolute;

        bottom: 1px;

        left: 2px;

        width: 99%;

        text-align: center;

        font-size: 15px;

        color: #fff;

        background: rgba(0, 0, 0, 0.5);

        padding: 10px;

        transform: translateY(100%);

        animation: slideUp 0.8s ease forwards;

        opacity: 1;

    }


    @keyframes slideUp {

        from { transform: translateY(100%); opacity: 0; }

        to { transform: translateY(0); opacity: 1; }

    }

    .catsp:hover .title {

        opacity: 0.5;

        display: none;

    }

    a.case-link p {

        position: absolute;

        bottom: 0;

        left: 0;

        right: 0;

        text-align: center;

        display: grid;

        align-content: center;

        z-index: 999999;

        color: white;

        text-transform: uppercase;

        font-size: 18px !important;

        letter-spacing: 5px !important;

        top: -10px;

        opacity: 0;

        transition: .15s ease-in-out !important;

    }


    p:not(.has-background):last-of-type {

        padding-bottom: 0;

    }


    a.case-link:hover p {

        top: 0;

        opacity: 1;

    }

    .vhtitlehome h2 {

        border-left: 5px solid red;

        text-transform: uppercase;

        padding-left: 10px;

    }

    .vhtitlehome {

        margin-bottom: 15px;

    }


    /* ===== Responsive ===== */


    /* Tablet (dưới 992px): 2 cột */


    @media (max-width: 992px) {


        .gallery {

            grid-template-columns: repeat(2, 1fr);

            padding: 10px;

        }

    }


    /* Mobile (dưới 576px): 1 cột */

    @media (max-width: 576px) {


        .gallery {

            grid-template-columns: 1fr;

            padding: 10px;

        }

    }

    .pagination {

        grid-column: 1 / -1;   /* chiếm hết chiều ngang grid */

        text-align: center;    /* căn giữa */

        margin-top: 20px;

    }

    .pagination .page-link {


        display: inline-block;

        padding: 8px 15px;

        margin: 0 5px;

        border: 1px solid #ddd;

        border-radius: 5px;

        background: #f5f5f5;

        color: #333;

        text-decoration: none;

        transition: 0.3s;

    }

    .pagination .page-link:hover {

        background: #e0e0e0;

    }


    .pagination .page-link.active {

        background: #333;

        color: #fff;

        border-color: #333;

    }


    /* Mobile pagination: nút nhỏ hơn */

    @media (max-width: 480px) {


        .pagination .page-link {


            padding: 6px 12px;


            font-size: 13px;


            margin: 3px;


        }


    }


    </style>


<?php

Thứ Năm, 11 tháng 9, 2025

PHP - .htaccess

 PHP 5.3


Options +FollowSymLinks -Indexes

RewriteEngine On

RewriteCond %{HTTPS} !=on [NC]

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

ErrorDocument 404 https://qkmedica.com

#--------

# Chặn các tham số URL chứa dấu gạch chéo (/) lạ trong giá trị

RewriteCond %{QUERY_STRING} ^.*(=|%3D)[^&\s]*\/[^&\s]* [NC]

RewriteRule ^.*$ - [F,L]


# Chặn các file có đuôi .phtml, .php, .asp, .aspx... trong tham số

RewriteCond %{QUERY_STRING} \.(phtml|php|asp|aspx) [NC]

RewriteRule ^.*$ - [F,L]


# Chặn các query string đáng ngờ

RewriteCond %{QUERY_STRING} (^|&)ID= [NC,OR]

RewriteCond %{QUERY_STRING} (^|&)App= [NC,OR]

RewriteCond %{QUERY_STRING} (^|&)([a-z0-9]+)=.*(win88|bet|casino|alternatif|188|sbotop|fun88|cmd|cmd368|1xbet|22bet|m88) [NC]



# Khi có lỗi 404 hoặc 403 → chuyển về trang chủ

ErrorDocument 404 https://domain.com or https://domain.com.vn

ErrorDocument 403 https://domain.com or https://domain.com.vn


#-----------------#

 

LARAVEL PHP > 8.2 


#-----------------#

3. Bật cache cho trình duyệt

<IfModule mod_expires.c>

  ExpiresActive On

  ExpiresByType image/jpeg "access plus 1 year"

  ...

</IfModule>


4. Ép kiểu file SCSS/SASS/Less thành CSS

<Files ~ "\.(scss|sass|less|postcss)$">

ForceType 'text/css; charset=UTF-8'

</Files>


5. Bật Rewrite URL & bảo vệ thư mục

<IfModule mod_rewrite.c>

    RewriteEngine On


    # Chặn truy cập trực tiếp vào file PHP trong /public/

    RewriteCond %{REQUEST_URI} ^/public/.*\.php$ [NC]

    RewriteRule ^ - [F]


    # Chặn xem file .git và .env

    RedirectMatch 404 /\.git(/|$)

    RedirectMatch 404 /\.env(/|$)


7. Giữ nguyên thông tin HTTP Authorization

RewriteCond %{HTTP:Authorization} ^(.+)$

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Cho phép các request giữ lại token/bearer trong header (thường dùng cho API).

8. Chuyển mọi request về index.php (router Laravel/PHP)

RewriteCond %{REQUEST_URI} !=/favicon.ico

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php [QSA,L]

Mọi URL không trỏ tới file/thư mục thật sẽ chạy qua index.php → xử lý bằng code PHP (kiểu framework).

9. Chặn truy cập file nhạy cảm

<FilesMatch "phpunit.xml|composer.lock|...">

  Require all denied

</FilesMatch>

Chặn các file test, file cấu hình package, file markdown… không cho ai truy cập qua web.    

Thứ Tư, 23 tháng 4, 2025

Hàm loại bỏ các từ khoá đặc biệt Mysql trên link

Example: Vitamin C from Food vs. Supplements: Which Is Better for Your Immune Health? 

Link: op=page_detail&title=Vitamin-C-Food-vs-Supplements-Which-Is-Better-for-Your-Immune-Health-&sid=318&newlang=english

function sanitize_sql_input($input) {

    // Danh sách các từ khóa SQL cần loại bỏ

    $keywords = array('select', 'from', 'where', 'union', 'insert', 'update', 'delete', 'drop', 'alter', 'create', 'truncate');

    // Kiểm tra và thay thế các từ khóa SQL trong chuỗi

    foreach ($keywords as $keyword) {

        // Dùng preg_replace để loại bỏ từ khóa SQL (cả chữ hoa và chữ thường)

        $input = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/i', '', $input);

    }

    return $input;

}

Thứ Tư, 1 tháng 1, 2025

PHP OOP - Classes and Objects

 class MyClass

{

    // Declare a public constructor

    public function __construct() {

        echo'0000';

    }


    // Declare a public method

    public function MyPublic() {

        echo'11111';

    }


    // Declare a protected method

    protected function MyProtected() {

       echo'2222';     

    }


    // Declare a private method

    private function MyPrivate() { 

       echo'3333';     

    }


    // This is public

    function Test()

    {

        $this->MyPublic();

        $this->MyProtected();

        $this->MyPrivate();

    }

}

Select 1:

$apple = new MyClass();

$apple ->Test();

Select 2:

MyClass::Test();


code Js input - Kiểm tra field

 **** HTML

<form action="" method="POST" role="form" name="fromdathang">

    <legend>Form title</legend>


    <div class="form-group">

        <label for="">label</label>

        <input type="text" class="form-control" placeholder="Input field" name="txt_email">

    </div>

    <button type="submit" class="btn btn-primary">Submit</button>

</form>


**** JS

$('#save__muahang').submit(function(e) {

    

    // e.preventDefault();

    data = new FormData($('#save__muahang')[0]);


    if(kiemtra()==true){


        $(".waiting").show();

        $("body").addClass("modal-open");

        $(".sendmail").addClass("modal-backdrop fade in");


        $.ajax({

            type: 'POST',

            url: '/op=save__muahang',

            data: data,

            cache: false,

            contentType: false,

            processData: false

        }).done(function(data) {


            if(data==1){


                $(".waiting").hide();

                $("body").removeClass("modal-open");

                $(".sendmail").removeClass("modal-backdrop fade in");


                $('.muahangthanhcong').addClass("error");    

                $('.muahangthanhcong').addClass("is-active");    

                load_muahang();

            }else{

                console.log(data);

            }


        }).fail(function(jqXHR,status, errorThrown) {

            console.log(errorThrown);

            console.log(jqXHR.responseText);

            console.log(jqXHR.status);

        });

    }    

});

function kiemtra(){

    /**test**/

    let u = document.fromdathang.txt_email.value;

    let hoten = document.fromdathang.txt_hoten.value;

    let dt = document.fromdathang.txt_dienthoai.value;

    let dc = document.fromdathang.txt_diachi.value;

    let tinh = document.fromdathang.customer_shipping_province.value;

    let ward = document.fromdathang.customer_shipping_district.value;

    let pho = document.fromdathang.customer_shipping_phuongxa.value;

    let note = document.fromdathang.txt_ghichu.value;

    let cod = document.fromdathang.cod.value;

    let magg = document.fromdathang.txt_magiamgia.value;

    let ship = document.fromdathang.txt_freeship.value;    

    if (u=="") { //quy tắc 1

        // console.log("not-email");

        location.href = "/op=save__gialap&txt_hoten="+hoten+"&txt_dienthoai="+dt+"&txt_diachi="+dc+"&customer_shipping_province="+tinh+"&customer_shipping_district="+ward+"&customer_shipping_phuongxa="+pho+"&txt_ghichu="+note+"&cod="+cod+"&txt_magiamgia="+magg+"&txt_freeship="+ship+"";

        return;

    }

    return true;

}

Thứ Năm, 26 tháng 12, 2024

Download file website khác về bằng url về host - code php

Link: https://php101.net/how-to/download-file-from-url-using-php/

$fileUrl = 'https://php101.net/wp-content/uploads/2021/12/php101-logo-horizontal-250x74-1.png';

// Initialize CURL
$ch = curl_init( $url );

// Get the file name and extension using basename()
$fileName = basename( $fileUrl );

// Specify file save path
$savePath = '/dir/' . $fileName;

// Initialize fopen pointer to store the file.
// 'w' is write mode, and 'b' is binary mode, can be excluded if the file is a text-based file
$fp = fopen( $savePath, 'wb' );

// Set the file transfer option and header to CURL
curl_setopt( $ch, CURLOPT_FILE, $fp );
curl_setopt( $ch, CURLOPT_HEADER, 0 );

// Execute the CURL session
curl_exec( $ch );

// Close the session after running to free resources
curl_close( $ch );

// Close file pointer
fclose( $fp ); 

Thứ Ba, 24 tháng 12, 2024

Hàm file_put_contents() trong PHP

Link gốc: https://codetutam.com/ham-file_put_contents-trong-php/ 

Định Nghĩa.

Hàm file_put_contents() dùng để ghi dữ liệu vào một file. Hàm này tương tự nhu các hàm fopen(), fwrite() và fclose() cùng đều ghi dữ liệu tới một file. Nếu filename không tồn tại, thì file được tạo. Nếu tồn tại, file sẽ được ghi đè, trừ khi FILE_APPEND flags được thiết lập.

Cú pháp.

Cú pháp:

file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int

Trong đó.

  • $filename là đường dẫn tới file.
  • $data là nội dung của file.
  • $flag là tham số, mang một trong các giá trị sau:
    • FILE_USE_INCLUDE_PATH : hàm sẽ tìm kiếm $filename trong include directory, xem thêm include_path  để tìm hiểu.
    • FILE_APPEND : nếu file đã tồn tại, hám sẽ không ghi đè $data vào nội dung sẵn có mà sẽ nối $data vào cuối file.
    • LOCK_EX Có được một khóa độc quyền trên tệp trong khi tiến hành viết. Nói cách khác, một cuộc gọi flock () xảy ra giữa cuộc gọi fopen () và cuộc gọi fwrite (). Điều này không giống với cuộc gọi fopen () với chế độ “x”.
  • $contextMột context resource hợp lệ được tạo bởi stream_context_create().

Giá trị trả về.

  • Hàm này trả về số lượng byte đã được ghi tới file, hoặc FALSE nếu thất bại.
Lưu ý: 
Hàm này có thể trả về Boolean FALSE, nhưng cũng có thể trả về giá trị không Boolean ước tính cho FALSE.
Vui lòng đọc phần trên Booleans để biết thêm thông tin. Sử dụng toán tử === để kiểm tra giá trị 
trả về của hàm này.

Errors/Exceptions.

  • Một lỗi mức E_WARNING được tạo nếu không thể tìm thấy filename, maxlength nhỏ hơn 0 hoặc nếu tìm kiếm  offset chỉ định trong luồng không thành công.

Ví dụ.

ví dụ 1 sử dụng đơn giản

code:

<?php
$file = 'people.txt';
// Mở tệp để lấy nội dung hiện có
$current = file_get_contents($file);
// Thêm nội dung mới vào file.
$current .= "John Smith\n";
// Viết thêm nội dung vào file.
file_put_contents($file, $current);
?>

Ví dụ 2 sử dụng flags.

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Viết nội dung vào một tập tin,
//sử dụng cờ FILE_APPEND để nối nội dung vào cuối tệp
// và cờ LOCK_EX để ngăn chặn bất kỳ ai khác ghi vào tệp cùng một lúc
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

Sự thay đổi qua các phiên bản.

  • PHP 5.1.0 đã thêm hỗ trợ cho LOCK_EX và khả năng truyền tài nguyên luồng cho tham số dữ liệu

Ghi chú.

  • Hàm này là kiểu binary-safe.(Nhị phân).
  • tiền boa Một URL có thể được sử dụng làm tên tệp với chức năng này nếu trình  fopen wrappers đã được bật. Xem fopen() để biết thêm chi tiết về cách chỉ định tên tệp. Xem các Supported Protocols and Wrappers để biết các liên kết đến thông tin về khả năng của các trình bao bọc khác nhau, ghi chú về cách sử dụng và thông tin về bất kỳ biến được xác định trước nào mà chúng có thể cung cấp.

Hàm liên quan.

Thông tin thêm.

  • Tập tin đặt nội dung thất bại nếu bạn cố gắng đặt một tập tin trong một thư mục không tồn tại. Điều này tạo ra thư mục.
    1. <?php
    2.     function file_force_contents($dir, $contents){
    3.         $parts = explode('/', $dir);
    4.         $file = array_pop($parts);
    5.         $dir = '';
    6.         foreach($parts as $part)
    7.             if(!is_dir($dir .= "/$part")) mkdir($dir);
    8.         file_put_contents("$dir/$file", $contents);
    9.     }
    10. ?>
  • Rõ ràng là chỉ nên sử dụng điều này nếu bạn đang viết một lần, nếu bạn đang viết nhiều lần vào cùng một tệp, bạn nên tự xử lý nó bằng fopen và fwrite, fclose khi bạn viết xong. So sánh tốc độ của file_put_contents() với các hàm tương tự, – Sử dụng file_put_contents() 1.000.000 lần.
    1. Thực tế 0m3.932s
    2. Người dùng 0m2.487s
    3. Hệ thống 0m1.437s
    – Sử dụng fopen() fwrite() cũng 1.000.000 Lần.
    1. Thực tế 0m2.265s
    2. Người dùng 0m1.819s
    3. Hệ thống 0m0.445s
  • Một phiên bản đơn giản hóa của phương thức: http://php.net/manual/ru/feft.file-put-contents.php#84180
    1. <?php
    2. function file_force_contents( $fullPath, $contents, $flags = 0 ){
    3. $parts = explode( '/', $fullPath );
    4. array_pop( $parts );
    5. $dir = implode( '/', $parts );
    6. if( !is_dir( $dir ) )
    7. mkdir( $dir, 0777, true );
    8. file_put_contents( $fullPath, $contents, $flags );
    9. }
    10.  
    11. file_force_contents( ROOT.'/newpath/file.txt', 'message', LOCK_EX );
    12. ?>

Các bạn có thể xem chi tiết hơn trên php.net.

Hi vọng với bài viết này, bạn đã hiểu rõ ứng dụng của hàm file_put_contents() trong PHP. Nếu bạn thấy bài viết hay và có ý nghĩa hãy like và chia sẻ bài viết này để mọi người cùng nhau học tập nhé. Cảm ơn các bạn đã ghé thăm codetutam.com