FreeBenzine
FreeBenzine

Reputation: 25

How to get a web link from a html form field

I am using a simple html form to for getting data from users, which the user first previews and then is posted in a Mysql database. The form is:

<form name="MyForm" enctype="multipart/form-data" method="post" action="myupload.php">
<p>Your name <input type="text" name="FormName" size="25" maxlength="50"> </p>
<p>Your email <input type="text" name="FormEmail" size="25" maxlength="50"></p>
<p> Link <input type="text" name="FormLink" size="25" maxlength="50"></p>
<p> <input type="submit" name="Submit" value="Submit"></p> 
</form>

In the php page I am using the folling code:

$_SESSION['MyName']= $_POST['FormName'];
$_SESSION['MyEmail']= $_POST['FormEmail'];
$_SESSION['MyLink']= $_POST['FormLink'];

$myName = $_SESSION['MyName'];
$myEmail = $_SESSION['MyEmail'];    
$myLink = $_SESSION['MyLink'];

echo "Name: $myConName <br> "; 
echo "Email: $myConEmail <br>";  
echo "<a href=$myLink target=\"_blank\"> Read more</a></p>";

However, if the user enters http://www.google.com/ then it works fine but if the user enters www.google.com/ then the webpage (Google.com) cannot be shown.

Any tips will be greatly appreciated.

Upvotes: 0

Views: 78

Answers (3)

tillinberlin
tillinberlin

Reputation: 439

something like this should work:

if (substr($url, 0, 7) != 'http://') { 

  $myLink = "http://".$myLink;

}

actually it should also check if there's no "https://" – so either this could be an option:

if ((substr($url, 0, 7) != 'http://')&&(substr($url, 0, 8) != 'https://')) { 

  $myLink = "http://".$myLink;

}

or also this could be an option:

if (substr($url, 0, 4) != 'http') { 

  $myLink = "http://".$myLink;

}

…pretty close to powtac's suggestion though…

This might actually be an "almost duplicate" to this:

Checking if string contains "HTTP://"

Upvotes: 1

Quentin
Quentin

Reputation: 943142

http://www.google.com/ is an absolute URI, www.google.com/ is a relative URI so it doesn't point at Google's servers (unless the page displaying the link is too).

You can:

  • Do nothing and make it the responsibility of the user to get the URL correct (there are lots of other errors they could make)
  • Try to resolve all the URLs and reject or require the user to confirm the URL if the response isn't a 200
  • Parse all the URIs and reject any that are not absolute URIs

Upvotes: 1

powtac
powtac

Reputation: 41040

After: $myLink = $_SESSION['MyLink']; add

$myLink = substr($myLink, 0, 4) == 'http' ? $myLink : 'http://'.$myLink;

Upvotes: 0

Related Questions