I've got this little CMS thing going, and the user has the ability to preview the post before submitting. I'd like to have a feature that checks whether a URL entered is valid (I.E. points to a resource that exists, not whether it's in the correct format or not). Preferably, I'd like to do it with JavaScript (I do开发者_Python百科n't have to use AJAX and PHP then), but PHP is fine.
Can someone point me towards a way of doing this? Just in case, I want a yes/no response from something like running the UNIX ping
command. I don't care about what's at the other end of the URL, just whether it actually points to something navigable.
Thanks,
James
you could simply use fopen to see if the url will work ... of course, this could be resource overkill depending on how often you are doing it.
http://php.net/manual/en/function.fopen.php
Alternately, you can use a jquery plugin:
http://binarykitten.me.uk/dev/jq-plugins/88-jquery-plugin-ajax-head-request.html
An alternate, and probably the easiest way which isn't live ... but you can use jquery to call another php script that implements it:
http://php.net/manual/en/function.get-headers.php
Load it into a new img
object, and see what the response is. Since you're not actually displaying the image, the fact that you may be loading up plain text or other non-image data is mostly irrelevant, you just want to see what the HTTP status code for the image request is.
The benefit is that if a malicious user tries to load in a URL that points to an obscenely large file, they'd only DoS themselves, as the request would go out from their browser and not your server. On the down side, nothing would stop them from spoofing a proper response and STILL put in that large-size resource and submit the form anyways.
精彩评论