The goal is to check if a string is a URL, no regex needed.
I have a form that lets users upload an image or add an image from a URL.
I get:
van_gogh_shoes.jpg
or
http://t2.gstatic.com/images?q=tbn:ANd9GcR2YNtlcmDDBpseEqUkMhe7-netq7RL2u_bw3_34VwB-Tsv2V-B
Users can add just 1 image, either uploaded or URL. So in mysql I’m updating the same column named entry_image with one of the values above.
When displaying images I need to check in the simplest way possible if the value from entry_image column is a URL. If so, display the full URL otherwise my own path to the uploaded image.
<img src="<?php (filter_var($row->entry_image, FILTER_VALIDATE_URL)) ? $row->entry_image : "uploads/entries/{$row->user_id}/{$row->entry_image} ?>">
I’m using FILTER_VALIDATE_URL which seems to work but as with most things I didn’t use before I’m not sure if it’s the best solution.. What are your thoughts?
I’m trying to avoid regex or other heavy validation codes when displaying images because I’m already validating the values when entering data to mysql. Please share a simpler solution if it exists.
filter_var()is the best solution for this. Thumbs up for not wanting a regex as a solution.Other than that, I just want to point out that transferring the image file from an external URL to your server is a better way (in my opinion). It will keep you from problems like deleted external images, and connection issues with external servers. You won’t also have to worry about validating URLs. This is just a suggestion though.