Jump to content

[SOLVED] If variable contains 'http://'


Recommended Posts

As part of a CMS I'm currently building for a client, the system allows for the user to add links to their site.

 

Basically, the link submitted from the form must start with a valid url start thingy, ie http://. I'm not sure how I would get php to check the submitted variable for this.

 

See below if I;m not making sense here!

<?php
$url_types = array('http://', 'https://', 'ftp://');
$url = $_POST['url'];

// If ( $url starts with $array_types ) {
// Add to database
} else {
$error = $error."Your link must start with 'http://', 'https://' or 'ftp://'.<br />";
}

Hope this makes sense!

Thanks for any light that can be shed here!
Stephen

Link to comment
https://forums.phpfreaks.com/topic/123919-solved-if-variable-contains-http/
Share on other sites

Here's the full script in its entirity for this section of the back end:

 

// Add Link to Database
if ($_POST['a'] == 'add_link') {
$url = $_POST['url'];
$title = $_POST['title'];
$uni_id = $_POST['uni_id'];
$target = $_POST['target'];

if ($title == '') {
	$error = $error.'A link title was not provided.<br />';
} else {
	++$trigger;
}
if ($url == '') {
	$error = $error.'A link url was not provided.<br />';
} else if (eregi ($url, ^('http://') | ('https://') | ('ftp://'))) {
	++$trigger;
} else {
	$error = $error.'An invalid URL was posted.<br />';
}

if ($trigger == 2) {
	$insertSQL = sprintf("INSERT INTO links (uni_id, title, target, url) VALUES (%s, %s, %s, %s)",
		GetSQLValueString($uni_id, "text"),
		GetSQLValueString($title, "text"),
		GetSQLValueString($target, "text"),
		GetSQLValueString($url, "text"));

	mysql_select_db($database_sql, $sql);
	$result = mysql_query($insertSQL, $sql) or die(mysql_error());

	if ($result) {
		$success = $success.'Link added successfully.<br/>';
	}
}
}

also can try:

 

<?php
  if(!parse_url($url))
    die("Invalide URL");
?>

 

...or to restrict to http, https, ftp:

<?php
  $allowed_scheme = array('http','https','ftp');
  if(!($parts = parse_url($url)))
    die("Invalide URL");
  if(!in_array($parts['scheme'],$allowed_scheme))
    die("Invalid scheme");
?>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.