Submitting query when certain element is present in query text
I have a PHP script that redirects the user to a website that they input into the text box. If the user types www.google.co开发者_运维知识库m into the box Google.com would be loaded and if they type http://facebook.com (without the www) Facebook.com would be loaded. Is there any way I can make it so that the script will only go to the address if it has www. in front of it? I hope you can understand my question.
My PHP script is:
<?php
if($_GET){
header('Location:http://'.$_GET['q']);
}
?>
<form method='get' action=''>
<input type='text' name='q'>
<input type='submit'>
</form>
if (strpos($_REQUEST['q'], 'www.') === 0) {
// string starts with www.
}
As Jonhoo noted it's probably better to use:
if (stripos($_REQUEST['q'], 'www.') === 0) {
// string starts with www.
}
This makes sure it also works when there are some (or all) uppercase characters in the www-part of the string.
Several ways of doing it, but the simplest one might just be a simple substr() call:
if ( substr ( $_GET['q'], 0, 4 ) == 'www.' ) {
header ( ... );
}
You might want to be careful here though, because what you are providing here is a perfect means for an attacker to redirect unknowing users to different URLs...
if(preg_match('/((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+(www\.)[\w\d:#@%/;$()~_?\+-=\\\.&]*)/',$_GET['q']) > 0){
// process $_GET['q']
}
This will return any valid urls which contain "www." after the protocol
Check out strpos()... FALSE = not found, else it's the position (0 = 1st char).
精彩评论