Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

วิธีซ่อน href จากลิงก์ใน PHP (และทางเลือกอื่น)

สรุปสั้นๆ: ไม่สามารถซ่อน href จากแท็ก <a> ได้จริงๆ เพราะ Browser ต้องรู้ URL เพื่อนำทางเมื่อ User คลิก แม้จะซ่อนด้วย JavaScript/CSS ก็ยังดูได้จาก Inspector หรือ View Source

วิธีที่ 1: URL Rewriting (ทำให้ URL ดูสวย/ไม่ระบุไฟล์โดยตรง)

ใช้ .htaccess (Apache) หรือ Nginx config เพื่อเขียน URL ใหม่

# .htaccess
RewriteEngine On
RewriteRule ^item/([0-9]+)/?$ item.php?id=$1 [L,QSA]

URL จะกลายเป็น: https://example.com/item/5001 แทนที่จะเป็น item.php?id=5001

วิธีที่ 2: ใช้ POST Request แทน GET (ซ่อน Parameter จาก URL)

<form method="post" action="process.php">
    <input type="hidden" name="packageID" value="5001">
    <button type="submit" class="btn-link">Go to Package</button>
</form>

CSS ทำให้ Button ดูเหมือน Link:

.btn-link {
    background: none;
    border: none;
    color: #0066cc;
    text-decoration: underline;
    cursor: pointer;
    padding: 0;
    font: inherit;
}
.btn-link:hover { color: #004499; }

วิธีที่ 3: ใช้ JavaScript Redirect (ยังคงมองเห็นได้ใน Source)

<a href="#" onclick="goToItem(5001); return false;">Go to Item</a>

<script>
function goToItem(id) {
    // ตัวเลือก 1: Redirect ธรรมดา
    window.location.href = '/item.php?id=' + id;
    
    // ตัวเลือก 2: POST ด้วย Form Dynamic
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '/item.php';
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'id';
    input.value = id;
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
}
</script>

วิธีที่ 4: Token/Session แทน ID โดยตรง (ปลอดภัยกว่า)

 5001, 'expire' => time() + 300]; // 5 นาที
?>
<a href="/item.php?token=">Go to Item</a>

process.php:

 time()) {
    $itemId = $_SESSION['tokens'][$token]['id'];
    unset($_SESSION['tokens'][$token]); // ใช้ครั้งเดียว
    // ดำเนินการกับ $itemId...
} else {
    die("Invalid or expired token");
}
?>

สรุป: เลือกวิธีไหนดี?

วิธีความปลอดภัยSEOความซับซ้อน
URL Rewritingปานกลางดีต่ำ
POST Formดี (Parameter ไม่อยู่ใน URL)ไม่ได้ (Bot ไม่ Submit Form)ต่ำ
JS Redirectต่ำ (เห็นใน Source)ไม่ได้ปานกลาง
Token/Sessionสูง (ID ไม่อยู่ใน URL, หมดอายุ)ไม่ได้สูง