To make links work without specifying the http://
or https://
protocols, you can use PHP to check if the inputted URL includes a protocol. If it doesn’t, you can add http://
to the beginning of the URL before displaying it. Here’s a basic example:
php
$userInput = 'www.foo.com'; // This would be the user's input
// Check if the URL does not contain a protocol
if (!preg_match("~^(?:f|ht)tps?://~i", $userInput)) {
// Add http:// to the beginning of the URL
$userInput = 'http://' . $userInput;
}
// Output the modified URL
echo '$userInput . '">' . $userInput . '';
?>
This code snippet checks if the user’s input does not start with http://
or https://
. If it doesn’t, it adds http://
to the beginning of the URL before displaying it as a link. This way, users can input URLs without specifying the protocol, and the link will still work correctly.
المزيد من المعلومات
لحل مشكلة الروابط التي لا تعمل بدون تحديد بروتوكول http://
أو https://
، يمكنك استخدام دالة PHP filter_var
مع الفلتر FILTER_VALIDATE_URL
للتحقق من صحة الرابط المدخل. إذا كان الرابط غير صحيح (يعني أنه لا يحتوي على بروتوكول)، يمكنك إضافة بروتوكول http://
قبل عرض الرابط. هنا مثال على كيفية تطبيق هذا النهج:
php
$userInput = 'www.foo.com'; // هذا سيكون إدخال المستخدم
// تحقق مما إذا كان الرابط يحتوي على بروتوكول أو لا
if (!filter_var($userInput, FILTER_VALIDATE_URL)) {
// إضافة بروتوكول http:// إذا لم يحتوي الرابط على بروتوكول
$userInput = 'http://' . $userInput;
}
// عرض الرابط المعدل
echo '$userInput . '">' . $userInput . '';
?>
هذا الكود يستخدم filter_var
للتحقق من صحة الرابط المدخل. إذا لم يكن الرابط صحيحًا (يعني أنه لا يحتوي على بروتوكول)، يتم إضافة http://
إلى بداية الرابط قبل عرضه كرابط. بهذه الطريقة، يمكن للمستخدمين إدخال الروابط دون تحديد البروتوكول، وستعمل الروابط بشكل صحيح.