so i have this website where people can submit url's for certain items, but I dont know how i can validate that a url was submitted not just some crap!.
Atm i have this piece of code:
if(filter_var('http://www.example.com/test.html', FILTER_VALIDATE_URL)) {
echo 'this is URL';
} else {
echo 'this is no url!';
}
But this piece of code is easy to bypass since it only checks for "http" in the string,
And users will submit "host" separately so i need to check if $host is a valid host.
Thx in advance! you guys rock!
Here is an example that solves your problem :
<?php
$url = "http://www.example.com/test.html";
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i", $url)) {
echo "URL is valid";
}
else {
echo "URL is invalid";
}
?>
How about sending it an HTTP request?
function isValid($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true); //make it a HEAD request
curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $statusCode == 200;
}
var_dump(isValid('http://www.google.co.uk')); // bool(true)
var_dump(isValid('some invalid URL')); // bool(false)
Related
Hello everyone I am trying to validate the mobile number using abstract api validation but I am stuck to check which number is valid and which number is not valid for this I write a code.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://phonevalidation.abstractapi.com/v1/?api_key=my_api&phone=14152007986');
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
$check = (string)$data;
if (strpos($check, 'true') == true)
{
echo "PhoneNo is valid";
}
if (strpos($check, 'false') == false)
{
echo "PhoneNo is invalid";
}
In the above code the phone number is correct as I am giving the phone number as example but still its showing me PhoneNo is invalid can any one help me to create a logic for it
strpos — Find the position of the first occurrence of a substring in a string
So if the result is "true" string your validation with strpos should look like
if (strpos($check, 'true') !== false)
{
echo "PhoneNo is valid";
} else
echo "PhoneNo is invalid";
}
Because function returns false if the needle was not found.
The Problem what i see is: You get a string then you parse the string into an array to cast it back into a string. so you can use your response right away. I don't know what the response looks like when it succeeds or fails. I only get api key missing.
curl_setopt($ch, CURLOPT_URL, 'https://phonevalidation.abstractapi.com/v1/?api_key=my_api&phone=14152007986');
$response = curl_exec($ch);
curl_close($ch);
if (strpos($response, 'true') == true)
{
echo "PhoneNo is valid";
} else {
echo "PhoneNo is invalid";
}
I have to do a plugin that allows you to insert videos from youtube in website. For this purpose I have encountered a problem, I want to validate the correctness of the url address from youtube. I want to check the correctness of the address, under the account:
- check if the id of the movie is included in the address
- Check if the address contains (youtube.com or youtu.be)
My code only checks if the url contains (youtu.be or youtube.com). I do not know how to check if the address has a movie id of 11 characters long. Do you have any idea?
<?php
$url = 'https://www.youtube.com/watch?v=knfrxj0T5NY';
if (strpos($url, 'youtube.com') || strpos($url, 'youtu.be')){
echo 'ok';
}else{
echo 'no';
}
?>
Method using cURL:
function isValidYoutubeURL($url) {
// Let's check the host first
$host = parse_url($url, PHP_URL_HOST);
if (!in_array($host, array('youtube.com', 'www.youtube.com'))) {
return false;
}
$ch = curl_init('www.youtube.com/oembed?url='.urlencode($url).'&format=json');
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($status !== 404);
}
I am getting a image source from a URL dynamically, but sometimes the URL returns empty or the image does not exist so i created a PHP function to check if the image source do exist or not so i can display a default image to my users when the image is not accessible.
My concern, is my function enough to catch the data?
My current php function which works when its sure that a image do exist.
function get_image_by_id($ID) {
$url = 'http://proweb/process/img/'.$ID.'.jpg';
if(empty($url)){
return 'default.jpg';
}else{
return $url;
}
}
My index.php
<img src="<?php echo get_image_by_id($ID);?>" />
Here CURL can also be helpful, tested it and working fine. Here we are using curl to get HTTP response code for the URL. If status code is 200 it means it exists.
function get_image_by_id($ID)
{
$url = 'http://proweb/process/img/' . $ID . '.jpg';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$info = curl_getinfo($ch);
if ($info["http_code"] != 200)
{
return 'default.jpg';
}
else
{
return $url;
}
}
You can use php is_file()to determine.
if (is_file($url) {
//its a file
}
You can use a ternary operator(one liner)
return is_file($url) ? $url : 'default.jpg';
you can use like this
<?PHP
function get_image_by_id($ID) {
$url = 'http://proweb/process/img/'.$ID.'.jpg';
// Checks to see if the reomte server is running
if(file_get_contents(url) !== NULL)
{
return $url;
}
else
{
return 'default.jpg';
}
}
?>
function get_image_by_id($ID) {
if(empty($url)){
$url = 'http://proweb/process/img/default.jpg;
}else{
$url = 'http://proweb/process/'.$ID.'.jpg';
}
return $url
}
I am new to php.
I want to check the valid youtube URL and if video is exists or not.
Any suggestion would be appreciated.
Here's a solution I wrote using Youtube's oembed.
The first function simply checks if video exists on Youtube's server. It assumes that video does not exists ONLY if 404 error is returned. 401 (unauthorized) means video exists, but there are some access restrictions (for example, embedding may be disabled).
Use second function if you want to check if video exists AND is embeddable.
<?php
function isValidYoutubeURL($url) {
// Let's check the host first
$parse = parse_url($url);
$host = $parse['host'];
if (!in_array($host, array('youtube.com', 'www.youtube.com'))) {
return false;
}
$ch = curl_init();
$oembedURL = 'www.youtube.com/oembed?url=' . urlencode($url).'&format=json';
curl_setopt($ch, CURLOPT_URL, $oembedURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Silent CURL execution
$output = curl_exec($ch);
unset($output);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] !== 404)
return true;
else
return false;
}
function isEmbeddableYoutubeURL($url) {
// Let's check the host first
$parse = parse_url($url);
$host = $parse['host'];
if (!in_array($host, array('youtube.com', 'www.youtube.com'))) {
return false;
}
$ch = curl_init();
$oembedURL = 'www.youtube.com/oembed?url=' . urlencode($url).'&format=json';
curl_setopt($ch, CURLOPT_URL, $oembedURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$data = json_decode($output);
if (!$data) return false; // Either 404 or 401 (Unauthorized)
if (!$data->{'html'}) return false; // Embeddable video MUST have 'html' provided
return true;
}
$url = 'http://www.youtube.com/watch?v=QH2-TGUlwu4';
echo isValidYoutubeURL($url) ? 'Valid, ': 'Not Valid, ';
echo isEmbeddableYoutubeURL($url) ? 'Embeddable ': 'Not Embeddable ';
?>
You never read the preg_match docs, did you?
You need a delimiter. / is most common but since you deal with an URL, # is easier as it avoid some escaping.
You need to escape characters with a special meaning in regex such as ? or .
The matches are not returned (it returns the number of matches or false if it failed), so to get the matched string you need the third param of preg_match
preg_match('#https?://(?:www\.)?youtube\.com/watch\?v=([^&]+?)#', $videoUrl, $matches);
as #ThiefMaster said,
but i'd like to add something.
he has asked how to determine if a video exists.
do a curl request and then execute curl_getinfo(...) to check the http status code.
When it is 200, the video exists, else it doesn't exist.
How that works, read here: curl_getinfo
you need change the answer above a little bit otherwise you just got the very first character,
try this
<?php
$videoUrl = 'http://www.youtube.com/watch?v=cKO6GrbdXfU&feature=g-logo';
preg_match('%https?://(?:www\.)?youtube\.com/watch\?v=([^&]+)%', $videoUrl, $matches);
var_dump($matches);
//array(2) {
// [0]=>
// string(42) "http://www.youtube.com/watch?v=cKO6GrbdXfU"
// [1]=>
// string(11) "cKO6GrbdXfU"
//}
I need to create a function that returns if a URL is reachable or valid.
I am currently using something like the following to determine a valid url:
static public function urlExists($url)
{
$fp = #fopen($url, 'r');
if($fp)
{
return true;
}
return false;
}
It seems like there would be something faster, maybe something that just fetched the page header or something.
You can use curl as follows:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true); // set to HEAD request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // don't output the response
curl_exec($ch);
$valid = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200;
curl_close($ch);
You could check http status code.
Here is a code you could use to check that an url returns 2xx or 3xx http code to ensure the url works.
<?php
$url = "http://stackoverflow.com/questions/1122845";
function urlOK($url)
{
$url_data = parse_url ($url);
if (!$url_data) return FALSE;
$errno="";
$errstr="";
$fp=0;
$fp=fsockopen($url_data['host'],80,$errno,$errstr,30);
if($fp===0) return FALSE;
$path ='';
if (isset( $url_data['path'])) $path .= $url_data['path'];
if (isset( $url_data['query'])) $path .= '?' .$url_data['query'];
$out="GET /$path HTTP/1.1\r\n";
$out.="Host: {$url_data['host']}\r\n";
$out.="Connection: Close\r\n\r\n";
fwrite($fp,$out);
$content=fgets($fp);
$code=trim(substr($content,9,4)); //get http code
fclose($fp);
// if http code is 2xx or 3xx url should work
return ($code[0] == 2 || $code[0] == 3) ? TRUE : FALSE;
}
echo $url;
if (urlOK($url)) echo " is a working URL";
else echo " is a bad URL";
?>
Hope this helps!
You'll likely be limited to sending some kind of HTTP request. Then you can check HTTP status codes.
Be sure to send only a "HEAD" request, which doesn't pull back all the content. That ought to be sufficient and lightweight enough.