I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.
I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.
(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?
That's a (slightly modified) version of the official URI parsing regexp from RFC 2396. It allows for #fragments and ?querystrings to appear after the filename, which may or may not be what you want. It also matches any valid domain, including localhost, which again might not be what you want, but it could be modified.
A more traditional regexp for this might look like the below.
^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$
|-------- domain -----------|--- path ---|-- extension ---|
EDIT See my other comment, which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for karma-whoring completeness reasons.
Actually.
Why are you checking the URL? That's no guarantee what you're going to get is an image, and no guarantee that the things you're rejecting aren't images. Try performing a HEAD request on it, and see what content-type it actually is.
In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.
If you are keen on doing this, though, check out this question:
Getting parts of a URL (Regex)
Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like
(?i)\.(jpg|png|gif)$
Here's the basic idea in Perl. Salt to taste.
#!/usr/bin/perl use LWP::UserAgent; my $ua = LWP::UserAgent->new; @ARGV = qw(http://www.example.com/logo.png); my $response = $ua->head( $ARGV[0] ); my( $class, $type ) = split m|/|, lc $response->content_type; print "It's an image!\n" if $class eq 'image';
If you need to inspect the URL, use a solid library for it rather than trying to handle all the odd situations yourself:
use URI; my $uri = URI->new( $ARGV[0] ); my $last = ( $uri->path_segments )[-1]; my( $extension ) = $last =~ m/\.([^.]+)$/g; print "My extension is $extension\n";
Good luck, :)
If you really want to be sure, grabbing the first kilobyte or two of the given URL should be sufficient to determine everything you need to know about the image.
Here's an example of how you can get that information, using Python, and here's an example of it being put to use, as a Django form field which allows you to easily validate an image's existence, filesize, dimensions and format, given its URL.
^((http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.(jpg|png|gif))
This expression will match all the image urls -
^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$
Examples -
Valid -
https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png
http://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg
example.com/de_home_teaser-box_puzzle_in_the_sun.png
www.example.com/de_home_teaser-box_puzzle_in_the_sun.png
https://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg
http://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg
https://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg
Invalid -
https://www.example.com
http://www.example.com
www.example.com
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
http://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2
http://www.siteabcd.com:8008
Reference: See DecodeConfig section on the official go lang image lib docs here
I believe you could also use DecodeConfig to get the format of an image which you could then validate against const types like jpeg, png, jpg and gif ie
import (
"encoding/base64"
"fmt"
"image"
"log"
"strings"
"net/http"
// Package image/jpeg is not used explicitly in the code below,
// but is imported for its initialization side-effect, which allows
// image.Decode to understand JPEG formatted images. Uncomment these
// two lines to also understand GIF and PNG images:
// _ "image/gif"
// _ "image/png"
_ "image/jpeg"
)
func main() {
resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
data, _, err := image.Decode(resp.Body)
if err != nil {
log.Fatal(err)
}
reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
config, format, err := image.DecodeConfig(reader)
if err != nil {
log.Fatal(err)
}
fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format)
}
format here is a string that states the file format eg jpg, png etc
Just providing a better solution. You can just validate the uri and check the format then:
public class IsImageUriValid
{
private readonly string[] _supportedImageFormats =
{
".jpg",
".gif",
".png"
};
public bool IsValid(string uri)
{
var isUriWellFormed = Uri.IsWellFormedUriString(uri, UriKind.Absolute);
return isUriWellFormed && IsSupportedFormat(uri);
}
private bool IsSupportedFormat(string uri) => _supportedImageFormats.Any(supportedImageExtension => uri.EndsWith(supportedImageExtension));
}
const url = "https://www.laoz.com/image.png";
const acceptedImage = [".png", ".jpg", ".gif"];
const extension = url.substring(url.lastIndexOf("."));
const isValidImage = acceptedImage.find((m) => m === extension) != null;
console.log("isValidImage", isValidImage);
console.log("extension", extension);
I am working in Javascript based library (React). The below regex is working for me for the URL with image extension.
[^\\s]+(.*?)\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$
Working URL`s are:
https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg https://images.pexels.com/photos/674010/pexels-photo-674010.jpg https://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG http://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG images.pexels.com/photos/674010/pexels-photo-674010.JPEG
Got the solution from: https://www.geeksforgeeks.org/how-to-validate-image-file-extension-using-regular-expression/