how to check if youtube url exist or not in laravel? - laravel

I want to check if entered URL exist on YouTube or not before saving that URL in my database
I am using this code
$url = 'https://www.youtube.com/watch?v=KeaoSIKaxeg';
if(preg_match('/http:\/\/www\.youtube\.com\/watch\?v=[^&]+/', $url))
{
dd('match');
}
else
{
dd('not match');
}
I have tried everything but nothing works. It always returns 'not match' even if the URL is valid.

$headers = get_headers('http://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=KeaoSIKaxeg');
if (!strpos($headers[0], '200')) {
echo "The YouTube video you entered does not exist";
}

You're trying to match against http://, not https://:
$url = 'https://www.youtube.com/watch?v=KeaoSIKaxeg';
if(preg_match('/https:\/\/www\.youtube\.com\/watch\?v=[^&]+/', $url)) {
dd('match');
}
else {
dd('not match');
}

Related

Elastic Search bulk request does not import all data, but shows no error

I use GuzzleHttp to send data via "_bulk" to an Elastic Search index. It is only a small dataset of 850 records. When I transfer the data record by record, I get an error message for 17 records. That's fine for me, so I can fix the errors.
But when I use _bulk, I do not get any error message at all. The 17 incorrect records are just ignored and are missing inside the index. How can I get an error message here? Are there some kind of options that I can use? Any ideas?
The endpoint is:
Here are my main code parts:
$jsonData = "xxxxx"; // the payload for the request
$elasticUrl = "https://xxxx.xx/xxxxx/_doc/_bulk";
$client = new Client([
"verify" => false, // disable ssl certificate verification
"timeout" => 600, // maximum timeout for requests
"http_errors" => false // disable exceptions
]);
$header = ["Content-Type" => "application/json"];
$result = $client->post($elasticUrl,
[
"headers" => $header,
"body" => $jsonData
]
);
if ($result->getStatusCode() != 200) {
$ret = "Error ".$result->getStatusCode()." with message: ".$result->getReasonPhrase();
}
A bulk request will always succeed with HTTP 200.
However, in the bulk response, you should see an indication whether each item succeeded or not. If you see errors: true in the response, then you know some of the items could not get indexed and looking into the items array, you'll find the error for the corresponding items.
As #Val pointed out the use of $response->getBody() gives the needed information:
$body = (string) $result->getBody();
$bodyArray = json_decode($body, true);
if ($bodyArray["errors"]) {
$retArray = [];
foreach ($bodyArray["items"] as $key => $item) {
if (isset($item["create"]["error"])) {
$retArray[] = $item["create"]["error"]["reason"].": ".json_encode($data[$key]);
}
}
$ret = implode(", ", $retArray);
}
As side note: in $data I keep the data as php array before sending it to Elastic Search.

Is that possible to use IF statement to get data from database and save it into String?

I want to get some record from tbl_jadwal and save it into string in my laravel.
This is my code,
$get_time = if (now()->isMonday()) {
return DB::table('tbl_jadwal')->where('Hari', 'Senin')->value('Jadwal_masuk');
} else if(now()->isSaturday()) { {
return DB::table('tbl_jadwal')->where('Hari', 'Sabtu')->value('Jadwal_masuk');
};
$time = $get_time;
but i got message syntax error, unexpected token "if", is there any other way to solve this problem ?
Broadly speaking you can do:
if (now()->isMonday()) {
$get_time = DB::table('tbl_jadwal')->where('Hari', 'Senin')->value('Jadwal_masuk');
} else if(now()->isSaturday()) { {
$get_time = DB::table('tbl_jadwal')->where('Hari', 'Sabtu')->value('Jadwal_masuk');
}
// Caution: $get_time may not be defined here
return $get_time??null;
You can also use when:
if (!now()->isSaturday() && !now()->isMonday()) { return null; }
return DB::table('tbl_jadwal')
->when(now()->isSaturday(), function ($q) { $q->where('Hari', 'Sabtu'); )
->when(now()->isMonday(), function ($q) { $q->where('Hari', 'Senin'); )
->value('Jadwal_masuk');
However carbon also supports localisation so you may be able to get now()->dayName to actually return the day name according to your locale.

Laravel : Generate PDF file using Dompdf

i am submitting a search form and based on the posted values results are fetched from DB and shown on the result page. I want to download these results in a PDF file. I configured Dompdf and its downloading PDF with some test data as below :
public function Genderate_PDF()
{
$data = ['title' => 'some title'];
$pdf = PDF::loadView('pdf', $data);
return $pdf->download('mypdf.pdf');
}
but in my scenario instead of loading the pdf view I have to show results in a page and then export that page results to PDF on a button click( Export PDF). Can someone please guide me how can i achieve that
EDIT::
Below is the search result posted to view that i need to export as PDF
public function search(Request $request){
$result = \DB::table('matromonial_data');
if ($request->has('gender')) {
$result->where('gender', $request->input('gender'));
}
if ($request->has('age_from') && $request->has('age_to')) {
$datefrom=$request->input('age_from');
$dateto=$request->input('age_to');
$result->where(function($query) use ($datefrom,$dateto){
$query->whereBetween('age',array($datefrom,$dateto)) ;
});
}
if ($request->has('height_from') && $request->has('height_to')) {
$height_from=$request->input('height_from');
$height_to=$request->input('height_to');
$result->where(function($query) use ($height_from,$height_to){
$query->whereBetween('height',array($height_from,$height_to)) ;
});
}
if ($request->has('religion')) {
$result->whereIn('religion', $request->input('religion'));
}
if ($request->has('cast')) {
$result->whereIn('cast', $request->input('cast'));
}
if ($request->has('mother_tongue')) {
$result->whereIn('mother_tongue', $request->input('mother_tongue'));
}
if ($request->has('maritial_status')) {
$result->whereIn('maritial_status', $request->input('maritial_status'));
}
if ($request->has('country')) {
$result->whereIn('country', $request->input('country'));
}
if ($request->has('city')) {
$result->whereIn('city', $request->input('city'));
}
if ($request->has('profession')) {
$result->whereIn('profession', $request->input('profession'));
}
if ($request->has('education')) {
$result->whereIn('education', $request->input('education'));
}
if ($request->has('income')) {
$result->whereIn('income', $request->input('income'));
}
if ($request->has('keywords')) {
$result->where('keywords', 'like','%' . $request->input('keywords') .'%');
}
if ($request->has('smoking_status')) {
$result->where('smoking_status', $request->input('smoking_status'));
}
if ($request->has('drinking_status')) {
$result->where('drinking_status', $request->input('drinking_status'));
}
$data['result_set']=$result->get();
return view('admin/search_result', $data);
}

Mailgun webhook incoming payload is empty

I try to get payload from mailgun webhook in Codeignaiter but all these are empty.
function index($payload = '')
{
var_dump($_POST); // empty
var_dump($_GET); // empty
var_dump($payload); // empty
}
I test my webhook url from mailgun dashboard , it is ok and it works but with empty payload.
Response: array(0) {
}
array(0) {
}
string(0) ""
But when test with Postbin it returns data like this
{
"timestamp": "1602575614",
"token": "3d21344bf13e4999bc6233a2031984f5ed4a7d9b5a42df9189",
"signature": "b1269faef2b44ce7f1ceaada83838691ed00203d1eb228e9c7097b7ec725a19c"
}
...
What can be a reason of empty data ?
This one will return data I need
$postedData = json_decode(file_get_contents('php://input'), TRUE);
print_r($postedData);

How to validate youtube video ids?

I want to validate youtube video ids sbumitted in the URL to one of my sites before accessing the Youtube API, but I don't know what the allowed characters are in such an id. I see people on the net guessing it can contain numbers and characters, but I haven't yet seen an official specification of these video ids.
Is there one?
See this thread for official info.
you can hit this: http://gdata.youtube.com/feeds/api/videos/VIDEO_ID (Page now returns: "No longer available".)
and determine if the video is valid based on response
There's no way you can check the validity of the ID with RegEx, since not all alpha-numeric values are valid ID's.
p.s. i'm pretty sure i saw "dashes" in video ID's
p.p.s. "underscore" is a valid character also: http://www.youtube.com/watch?v=nrGk0AuFd_9
[a-zA-Z0-9_-]{11} is the regex (source), but there's no guarantee that the video will be there even if regex is valid
With v3 of the YouTube API I achieved this by calling:
GET https://www.googleapis.com/youtube/v3/videos?part=id&id=Tr5WcGSDqDg&key={YOUR_API_KEY}
This returns something like:
{
"kind": "youtube#videoListResponse",
"etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/P2cGwKgbH6EYZAGxiKCZSH8R1KY\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [{
"kind": "youtube#video",
"etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/Rgd0_ApwigPcJHVX1Z2SIQ5FJtU\"",
"id": "Tr5WcGSDqDg"
}]
}
So you can just do a check:
if(json.hasOwnProperty('pageInfo') && json.pageInfo.totalResults === 1) {
if(items[0].kind==='youtube#video') {
//valid video ID
}
}
If you are looking for a quicker and more scalable solution I would say to use REGEX with some logging/fallback for errors to be pro-active if YouTube changes their ID in the future.
I've been working with the YouTube API for a while now, dealing with millions of videos. Looping through them, I found this to be the most ideal:
/^[A-Za-z0-9_-]{11}$/
A more detailed example say in PHP:
public static function validId($id) {
return preg_match('/^[a-zA-Z0-9_-]{11}$/', $id) > 0;
}
I solved this issue in the same way Roman recommended. In my helper:
Be sure to include your requires at the top of the file:
require "net/http"
require "uri"
Then:
def validate_id(youtube_id)
uri = URI.parse("http://gdata.youtube.com/feeds/api/videos/#{ youtube_id }")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
%Q{ #{response.code} }
end
Be sure there is no white space between the brackets in "#{response.code}"
Lastly, compare it to the desired response:
def youtube_data(youtube_id)
if validate_id(youtube_id) == "200"
#video is good code
else %Q{ Video is no longer valid }
end
end
Here is a simple implementation in JavaScript:
async function validVideoId(id) {
const url = "http://img.youtube.com/vi/" + id + "/mqdefault.jpg";
const { status } = await fetch(url);
if (status === 404) return false;
return true;
}
console.log(validVideoId('60ItHLz5WEA'));
I just look to see if it is alphanumeric with possible dash or not. You might want to look into oEmbed, you can query YouTube to see if the ID is a valid video or not.
Here is a simple implementation of Roman's approach in PHP:
function validYoutube($id){
$id = trim($id);
if (strlen($id) === 11){
$file = #file_get_contents('http://gdata.youtube.com/feeds/api/videos/'.$id);
return !!$file;
}
return false;
}
And here are the tests:
echo validYoutube('Nv7U6_WhqvQ');
echo validYoutube('Nv7U6_Whqvf');
echo validYoutube('Nv7U6_Whqzz');
I think this works for checking if the video exists or not. Other validation can be done using REGEX as mentioned above. (Implemented using PHP)
public function verifyVideoID($videoID) {
parse_str(file_get_contents("http://youtube.com/get_video_info?el=detailpage&video_id=".$videoID), $info);
if (isset($info['errorcode'])) {
$response = ['response' => false];
return response()->json($response);
} else {
$response = ['response' => true];
return response()->json($response);
}
}
Here's one I came up with from combining info from other answers here and elsewhere:
function validId($id) {
return preg_match('/^[a-zA-Z0-9_-]{11}$/', $id) > 0;
}
function isvalYtube($url) {
$purl = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));
if (!strpos($url, 'youtu.be/') && ($purl != 'youtu.be')) {
if (strpos($url, 'watch') && ($purl = 'youtube.com')) {
parse_str(parse_url($url, PHP_URL_QUERY), $id);
if (!empty($id['v'])) { return(validId($id['v']) ? true : false); } else { return false; }
}
} else {
if (!empty(basename($url))) { return(validId(basename($url)) ? true : false); } else { return false; }
}
}
echo isvalYtube($url) ? 'valid link' : 'invalid link';
First function checks if we're dealing with a valid Youtube video ID.
Second function simply checks if it's a valid youtube VIDEO LINK or VIDEO from PLAYLIST LINK, excluding channel links.
Note: It doesn't determine if it's an active video nor does it check if it exists or not. These functions act merely as Youtube video-link syntax checkers and should be treated as such.
Usage examples:
$url = 'http://www.youtube.com/watch?v=o_QBk4VwnIA';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'http://youtu.be/o_QBk4VwnIA';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'http://www.youtube.com/watch?v=o_QBk4VwnIA&feature=youtu.be';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'https://www.youtube.com/watch?v=Sq3eLdixvCc&list=OLAK5uy_nvaYLo9AG_rZyqkXzYlkJfLjBuZS84bIU';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'https://www.youtube.com/channel/UCMPQY9gW0hQ9e_-IdQUKEAw';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'invalid link'
Simple use this code:
public class HelloWorld{
public static void main(String []args){
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
String video_url = "https://www.youtube.com/watch?v=as3tGTN2u98";
if (video_url.matches(expression)) {
System.out.println("It's valid");
}
}
}

Resources