Question: Check if Youtube ID is valid with ColdFusion

Question

Check if Youtube ID is valid with ColdFusion

Answers 2
Added at 2016-12-21 09:12
Tags
Question

I want to check if a YouTube Link/ID is valid. It should get me an answer with an if / else statement.

I tried this:

<cfset variables.key = "my_key_value_here">
<cfset variables.headers = "https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=#variables.key#">

<cfif (IsArray(#variables.headers#) ? ReMatch('(http:\/\/)(?:www\.)?youtu(?:be\.com\/(?:watch\?|user\/|v\/|embed\/)\S+|\.be\/\S+)',#variables.headers#) : false)>
     Correct Id!
<cfelse>
   There is no video with that Id!
</cfif>

The ID in the example is correct and should output: "Correct ID!" But it displays always the else-statement.

Thank you for helping!

Answers to

Check if Youtube ID is valid with ColdFusion

nr: #1 dodano: 2016-12-21 10:12

I think Best way to validate youtube videoId by checking it through youtube data API. Below are the steps you need to follow to validate video.

  1. Login to your google Account
  2. Go to Google API console
  3. In Api library click on YouTube Data API
  4. Create a project
  5. Create credential for the same project (this will give you API key)
  6. Enable API

Once you are done with above steps you can simply implement this API in ColdFusion using CFHTTP tag.

Here is a code snippet that can help you.

<cfset variables.youtubeId = "EUcaCKWk83Q" />
<cfset variables.youTubeApiKey = "YOUR_API_KEY" />
<cfhttp url="https://www.googleapis.com/youtube/v3/videos?part=id&id=#youtubeId#&key=#youTubeApiKey#" >
<cfset response = deserializeJSON(cfhttp.fileContent) />
<cfif response.pageInfo.totalResults>
    Correct Id!
<cfelse>
    There is no video with that Id!
</cfif>
nr: #2 dodano: 2016-12-21 14:12

Simple solution:

<cfset variables.key = "my_key_value_here">
<cfhttp method="Get" url="https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=#variables.key#">
<cfif cfhttp.statusCode EQ "200 OK">
    Correct Id!
<cfelse>
    There is no video with that Id!
</cfif>

<cfoutput>#cfhttp.statusCode#</cfoutput>

I do not need a RegEx because it is always the same link, just another ID.

Source Show
◀ Wstecz