i am trying to dynamically generate the goo.gl links via function.php ,when a post is created ...but its not getting updating the field with the link created on localhost..and i just cant figure out the issue
function newlinks($post_id){
$permaurl=get_permalink($post_id);
$shorturl=make_my_url($permaurl);
update_post_meta('$post_id','shorturl',$shorturl)
}
add_action( 'save_post', 'newlinks' );
function make_my_url($myurl)
{
//got te key from https://console.developers.google.com/iam-admin/projects
$key = 'AIzBP0';
$googer = new GoogleURLAPI($key);
// Test: Shorten a URL
$shortDWName = $googer->shorten($myurl);
return $shortDWName; // returns the short url
}
// Declare the class
class GoogleUrlApi {
// Constructor
function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
// Keep the API Url
$this->apiURL = $apiURL.'?key='.$key;
}
// Shorten a URL
function shorten($url) {
// Send information along
$response = $this->send($url);
// Return the result
return isset($response['id']) ? $response['id'] : false;
}
// Send information to Google
function send($url,$shorten = true) {
// Create cURL
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$this->apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);
}
}
your code is good. I've created my own API key and tried this and works fine. The problem may be in google console.
Please login to https://developers.google.com/apis-explorer/?hl=pl#p/urlshortener/v1/ and try to generate short url there. Google should ask you to authorize the key you created before. After that code should work fine.
Related
For a custom WordPress API endpoint, I try to receive a custom header for a GET request. I'm sending the request via JavaScript with axios:
let response = await axios.get('url', {
headers: {
'_key': 'mykey'
}
});
The PHP side:
public function get_option( $request ) {
$data = $request->get_header('_key');
return $data;
}
The result is an empty string. The method seems to be the correct one:
https://developer.wordpress.org/reference/classes/wp_rest_request/get_header/
It is not possible inside WordPress to get custom header data? Or what's the issue here?
function wpse_288865_featch_header() {
$response = wp_remote_get('https://www.amazon.com/');
$custom_header = wp_remote_retrieve_header($response, 'X-Amz-Cf-Id');
var_dump($custom_header);
exit;
}
add_action('init', 'wpse_288865_featch_header');
I have a function for Facebook authentication.
public function loginWithFacebook(Request $request){
// get data from request
$code = $request->get('code');
// get fb service
$fb = \OAuth::consumer('Facebook');
// check if code is valid
// if code is provided get user data and sign in
if ( ! is_null($code))
{
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken($code);
// Send a request with it
$result = json_decode($fb->request('/me?fields=name,email,gender,age_range'), true);
print_r($result1);
}
// if not ask for permission first
else
{
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return redirect((string)$url);
}
}
I want to call this function from another controller.
So I do this:
app('App\Http\Controllers\socialMedia')->loginWithFacebook(Request $request);
but it returns the error
syntax error, unexpected '$request' (T_VARIABLE)
How do I solve this?
public function loginWithFacebook(Request $request){
This is called type hinting. The method is declared in a way that it will only accept a first parameter that is an instance of Request.
app('App\Http\Controllers\socialMedia')->loginWithFacebook(Request $request);
That is a method call, and in those you just pass the parameter – to specify a type at this point makes no sense.
So the correct way to call the method should be
app('App\Http\Controllers\socialMedia')->loginWithFacebook($request);
How does Url::remember() work? I thought it stores the URL in a cookie, but I don't see it. It's working locally, but not on Heroku.
According to source code, it saves URL in session:
public static function remember($url = '', $name = null)
{
$url = static::to($url);
if ($name === null) {
Yii::$app->getUser()->setReturnUrl($url);
} else {
Yii::$app->getSession()->set($name, $url);
}
}
setReturnUrl will call:
Yii::$app->getSession()->set($this->returnUrlParam, $url);
Official docs:
Session set()
User setReturnUrl()
I am using codeigniter for the application. First,I created the View that consist of Message TextArea Box , DropDownlist which value comes from database, and submit button. I have database of two colums one for mobile number and another for service provider.I have predefined url with query string value (http://www.something.com?mobno=numbervar&msg=messagevar)
In model class, I have function called getProvider1, to get return the array of mobile number of particular provider. I should use the above url with query string passing mobile number and message that inputted by user. Here I have used foreach loop to pass message to different mobile number through query string .
The problem is that I couldn't get idea how to pass message to multiple mobile number without visiting that something.com pages and show result which query string value is passed and which are failed... Here, I couldn't pass the different query string value in that url using foreach. It only visited one page or redirect once....Is there any function something like redirect()....or any other options. Please want some suggestion... will be greatly appreciated.... Following is the controller's function to send message
function message()
{ $message = $this->input->post('message');
$provider = $this->input->post('provider');
if($provider == 'provider1')
{
$number = $this->message_model->getProvider1();
$mobile = array();
foreach($number as $no)
{
$mobile = $no;
redirect('http://something.com?mobno='.$mobile.'&msg='.$message);
}
}
else if
{
// same process for service provider2
}
else
{
//other service provider
}
}
Firstly, I'm not 100% sure what it is you want to do exactly, but redirect will clearly only work once (since after you have redirected you are no longer on your page).
What you could do, based on my understanding of your code, is look in to cURL. It gives you the opportunity to load several pages and look at their results "behind the scenes" and display whatever you want to your users.
Some other notes.
/* Instead of doing the same thing for all provides with IFs, rewrite you message model to take the provider name as a input variable insdead. */
$number = $this->message_model->getProvider($provider);
/* $mobile = array(); // you never use this array, no need for it */
foreach($number as $mobile)
{
/* $mobile = $no; //completly useless, just name it in the foreach */
/* --- do a cURL request here --- */
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://something.com?mobno='.$mobile.'&msg='.$message);
$curl_info = curl_getinfo($curl);
curl_close($curl);
if ($curl_info['http_code'] != 200) /* Handle error if any */
{
$errors[] = 'ERROR WITH REQUEST: http://something.com?mobno='.$mobile.'&msg='.$message;
}
}
I have been trying for quite a while to check if submitted links are valid film-clips from youtube.com or vimeo.com but I didn't succeed.
Any ideas how to check url's like:
http://www.youtube.com/watch?v=jc0rnCBCX2c&feature=fvhl (valid)
http://www.youtube.com/watch?v=jc0FFCBCX2c&feature=fvhl (not valid)
http://www.youtube.com/v/jc0rnCBCX2c (valid)
http://www.youtube.com/v/ddjcddddX2c (not valid)
http://www.vimeo.com/463l522 (not valid)
http://www.vimeo.com/1483909 (valid)
http://www.vimeo.com/lumiblue (not valid)
http://www.youtube.com/user/dd181921 (not valid)
?
I use php.
If you check the response headers from a request to http://gdata.youtube.com/feeds/api/videos/videoId where videoId is the google video Identifier, you should get a 200 if the video exists and a 400 (bad request) if the video doesn't exist.
// PHP code
// Check if youtube video item exists by the existance of the the 200 response
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $youtubeId);
if (!strpos($headers[0], '200')) {
echo "The YouTube video you entered does not exist";
return false;
}
i see a answer in this site :
www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_23765374.html
and he said :
I would suggest using youtube's API since you are trying to validate if the video exists.
or if you don't want to go into API stuff then you can do simple trick.
check this link:
http://code.google.com/apis/youtube/developers_guide_php.html#RetrievingVideoEntry
to check for the existence of a video you will need to extract "v" value and send a request that contains the video id to :
http://gdata.youtube.com/feeds/api/videos/videoID
where videoID is the "v" value
for example a video FLE2htv9oxc
will be queried like this
http://gdata.youtube.com/feeds/api/videos/FLE2htv9oxc
if it does not exist then you will get a page with "Invalid id"
if it exists, will return an XML feed having various info about the video.
this way you can check that the video exists.
hope this will get you in the right direction.
the same thing with vimeo , try to look in api documentation in there site.
http://www.vimeo.com/api
I wrote this function to check if the link is a valid youtube link.
/**
* This function will check if 'url' is valid youtube video and return the ID.
* If the return value === false then this is **not** a valid youtube url, otherwise the youtube id is returned.
*
* #param <type> $url
* #return <type>
*/
private static function get_youtube_id($url) {
$link = parse_url($url,PHP_URL_QUERY);
/**split the query string into an array**/
if($link == null) $arr['v'] = $url;
else parse_str($link, $arr);
/** end split the query string into an array**/
if(! isset($arr['v'])) return false; //fast fail for links with no v attrib - youtube only
$checklink = YOUTUBE_CHECK . $arr['v'];
//** curl the check link ***//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$checklink);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
$return = $arr['v'];
if(trim($result)=="Invalid id") $return = false; //you tube response
return $return; //the stream is a valid youtube id.
}
You can try to catch the 301 header that you tube throws if the video is no longer valid
/*
* Verify YouTube video status
*/
$videoID = "o8UCI7r1Aqw";
$header = get_headers("http://gdata.youtube.com/feeds/api/videos/". $videoID);
switch($headers[0]) {
case '200':
// video valid
break;
case '403':
// private video
break;
case '404':
// video not found
break;
default:
// nothing above
break;
}
Since most of the comments here are a bit old, here's a quick thing I set up that checks if YouTube links are private or not.
The good thing about this approach is that it doesn't require us to set up API Credentials with Google or anything like that. I will assume that you would be able to follow the same approach with Vimeo or any other video provider that doesn't provide accurate status codes on request.
axios
.get(link)
.then((res) => {
if (StringUtils.isYouTubeLink(link)) {
// The "streamingData" substring should be present on
// all valid video requests. Private or non-existent
// videos won't have it
if (!res.data.includes("streamingData")) {
errorData.reason = "Video unavailable";
brokenLinks.push(errorData);
}
}
})