Jump to content

regex to accept a proper url, or none at all


sid0972

Recommended Posts

No, but there is an operator.

if ($variable === null)

...if it's exactly null. If you want to check if a variable is "empty" then

if (empty($variable))

empty() also returns true for "0" but that's not a valid URL so it's okay in this case.

<?php
function score_valid($score,$link)
{
if (!filled_out($score)) {

     echo "There's something wrong.
    <a href=\"my_oc.php\">Go back and change it.</a>";
     break;
   }

   if (strstr($link, 'http://') === false) {
      $link = 'http://'.$link;
   }
if($link!==NULL)
{

 if (!(@fopen($link, 'r'))) 
  {

 echo "There's something wrong<a href=\"my_oc.php\">Go back and change it.</a>";
 break;
  }
  else { return true; }
}
else { return true; }


}
?>

 

 

function filled_out

 

function filled_out($form_vars) {
 foreach ($form_vars as $key => $value) {
    if ((!isset($key)) || ($value == '')) {
       return false;
    }
 }
 return true;
}

Well, beside the obvious absence of any regular expressions, the problem you're having is quite easily spotted.

 

It's because of a flaw in your logic. If you go through the script step-by-step, and keep track of what happens to the contents of the $link variable, you should be able to spot it yourself.

I'll give you a hint: $link always contains a value when you get to the NULL test.

 

Also, your script won't work if the host has turned off fopen_url, which many hosts do. Not only that, but this script is quite open for attacks, which an attacker can utilize to run commands on your server.

You should, at the very least, actually use a RegExp to verify that you've got an URL, before trying to opening the location. I've previously posted a RegExp that validates URLs, and does a fairly good job at it. I recommend using it.

i think $link wont be NULL cause of this

 


if (strstr($link, 'http://') === false) {
$link = 'http://'.$link;

 

is this what you meant to say?? i have tried without this function included, and failed.

 

also, this might be open for attacks, and thank you for that link, but i didnt understand how it was working.

Care to elaborate?

Yes, that was exactly what I was thinking about. :)

 

The RegExp works like any other regular expression. Just copy it, and send it to preg_match () along with your link. It'll return 1 (true) if the string is indeed an URL, or 0 (false) if it's not.

Replace the $link !== null with the preg_match () call, and you should be good.

 

As for how the RegExp itself works, that's a "bit" too complex to explain right off the bat. Suffice to say, it checks all possible (or at least tested) permutations according to the URL RFC.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.