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";
}
Related
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 trying to retrieve an array from an API, but every time it is returning an empty array after every attempt.
This is my coding which is fetching data from api:
<?php
$array=array("name"=>"name1");
$url = "http://getsjobs.esy.es/registerapi.php?".http_build_query($array);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
?>
this is my api code
<?php
if(isset($_GET['Array'])) {
$array = $_GET['Array'];
header('Content-type: application/json');
}
?>
Even if i use json_encode($array). It is returning empty array. I can receive single value or single array element, but not able to send and receive entire
array from json.
I am not able to find any relevant post. Any link or suggestion will be helpful
My PHP is rusty, but the problem looks to me to be because your API is looking for a parameter called "Array", but nowhere in your calling block does it actually send a GET parameter called "Array".
Your code looks a bit incomplete, so maybe I'm misunderstanding something.
look here: you're decoding it twice.
$data = json_decode($json,true);
if (is_array(json_decode($data )) || is_object(json_decode($data)))
{ echo 'array exists'; }
else { echo 'Not an array'; }
simply:
$data = json_decode($json,true);
if (is_array($data ))
{ echo 'array exists'; }
else { echo 'Not an array'; }
if it still doesn't works, see what echo json_last_error_msg(); returns.
Try to check if your $json is a valid json too. Check if what echo $json; returns is valid here: http://jsonformatter.curiousconcept.com/
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)
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'm struggling with parsing a web service response JSON in cases where the service returns an error.
Example JSON - success flow:
{
"Response": [{
"iconPath" : "/img/theme/destiny/icons/icon_psn.png",
"membershipType": 2,
"membershipId": "4611686018429261138",
"displayName": "Spuff_Monkey"
}],
"ErrorCode": 1,
"ThrottleSeconds": 0,
"ErrorStatus": "Success",
"Message": "Ok",
"MessageData":{}
}
Example JSON - error flow:
{
"ErrorCode": 7,
"ThrottleSeconds": 0,
"ErrorStatus": "ParameterParseFailure",
"Message": "Unable to parse your parameters. Please correct them, and try again.",
"MessageData": {}
}
Now my PHP:
function hitWebservice($endpoint) {
$curl = curl_init($endpoint);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
$json_response = curl_exec($curl);
if(curl_exec($curl) === false) {
echo "Curl error: " . curl_error($curl);
}
curl_close($curl);
$array_response = json_decode($json_response, true);
$function_response = array();
if (!isset($array_response['Response'])) {
$function_response = $array_response;
} else {
$function_response = $array_response['Response'];
}
return $function_response;
}
What I'm trying to achieve is when the JSON includes the "Response" block I put that in a new array and return only that detail from the function, where "Response" isn't present I want to return the full JSON as an array.
However at present, where there is no "Response" I get an empty array.
There's something wrong with my logic and I can't get past it in my tiny mind, so it's time to reach out for help!
Judging from the fact that Response is an array of objects in the JSON, I suspect that the error-flow response may also contain a Response-field, but with an empty array as value ([]). That would explain your current result.
Therefore, do not check for the existence of Response. It may just be an empty array. Instead, check for the ErrorCode, ErrorStatus or ErrorMessage (whichever you think is most suitable). For example:
if ($array_response['ErrorStatus'] != "Success") {
$function_response = $array_response;
} else {
if (!isset($array_response['Response'])) {
$function_response = null;
} else {
$function_response = $array_response['Response'];
}
}
In the Success-case, you want to check for existence of Response, so that if it does not exist (but it is expected), you can raise some error).
Another possible solution is to count the number of responses:
if (!isset($array_response['Response'])) {
$function_response = $array_response;
} else {
if (count($array_response['Response']) > 0) {
$function_response = $array_response['Response'];
} else {
$function_response = $array_response;
}
}
If you notice, both a good and a bad response contain an ErrorCode
You would be better designing your code to work from this field rather than test a field that may or may not exist.
So try this instead :-
$array_response = json_decode($json_response, true);
switch ( $array_response['ErrorCode'] ) {
case 1 :
do_errorCode_1_processing($array_response)
break;
case 2 :
do_errorCode_2_processing($array_response)
break;
// etc etc
}
isset () is not the right function for checking if the key in an array is present or not.
Use array_key_exists () instead.
http://php.net/manual/en/function.array-key-exists.php
so your code should look like this:
$array_response = json_decode($json_response, true);
$function_response = array();
if (array_key_exists('Response', $array_response)) {
$function_response = $array_response['Response'];
} else {
$function_response = $array_response;
}
return $function_response;
The above should do the trick.