PHP File get contents give 404 error but exist - php

In my script I am using a Google YouTube API to receive avatar images from a YouTube channel. Every avatar is received and saved to our own server, except the 'standard' avatars.
This is a screen shot of the standard avatar.
I am trying to save them with file_get_contents, but it gives me an error.
The code:
$filename = './img/avatars/'. $ytname .'.jpg';
if (file_exists($filename)) {
print_r("http://youtube-top.eu/img/avatars/".$ytname.".jpg");
} else {
$url = file_get_contents("https://www.googleapis.com/youtube/v3/channels?part=brandingSettings,snippet&forUsername=".$ytname."&key=#KEYISPRIVATE#");
$json = json_decode($url, true);
$str = $json['items'][0]['snippet']['thumbnails']['default']['url'];
$str = str_replace('https://', 'http://', $str );
$content = file_get_contents($str);
?>
/*
<?php
echo $str;
?>
*/
<?php
file_put_contents('./img/avatars/'. $ytname . '.jpg', $content);
print_r("http://youtube-top.eu/img/avatars/".$ytname.".jpg");
}
}
With channels with a custom avatar, it saved to our server, only not for the standard avatars. This is the error:
file_get_contents(http://i.ytimg.com/i/MJJbPVnNlvRAWSgfVuzxJA/1.jpg):
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
The image link in the error does exist.
Does someone understand this?

Google has some magic in place to block automated requests, hotlinking, etc. If their watchdog algorithms have flagged activity from your IP, they could be blocking you.
You might try using cURL functions and setting the User-Agent string to something reasonable for a modern browser. Otherwise, I'd suggest rethinking your logic for the app.
Source: personal experience; I can't use Google to automatically determine the nature of 2nd-hand office machines for one of our applications.

Google has some magic in place to block automated requests,
hotlinking, etc. If their watchdog algorithms have flagged activity
from your IP, they could be blocking you.
But why dont dont block me for the custom avatars, and only for the standard avatar ?
and when i do:
<img src="http://i.ytimg.com/i/MJJbPVnNlvRAWSgfVuzxJA/1.jpg" />
its show correctly the image. So google is not blocking the ip of my server..

Related

How can I save an image received from a Webhook? (WhatsApp API)

So, I'm starting to understand a bit more of WhatsApp API and all the messages that my number received are sent to my server via Webhook. The text messages are fine, but I'm struggling with the media messages.
When the user sends an image for example, Facebook's Webhook only sends me the mime_type and the sha256 of the image.
Can anyone please guide me the steps of what I need to do?
Do I need to convert it to base64, and then write the file in my server? Do I need to use a specific function? Do I need to use another programming language that's not PHP?
I'm totally lost on this one.
The way to do this, as pointed out by #CBroe is to use the media endpoints.
Assuming message is the message from the Webhook
// Get the image information, including the download link
$image_url_handle = fopen("https://graph.facebook.com/v13.0/" . $message->id);
$image_url = "";
// Read all of the data before parsing
while (!feof($image_url_handle)) {
$image_url .= fread($image_url_handle);
}
// Close the stream
fclose(image_url_handle);
// Get the url from the image information
$image_url = json_decode($image_url)->url;
// Start a request to the download URL.
$image_stream = fopen($image_url);
Note: There is no error handling or frameworks, though this should work most of the time

Make google drive fmt stream map stream links works when load on server

When I attempt to access video links on my google drive via my server, using via fmt map, they are not working on the client side because of ip tracking.
I have researched all stackoverfow similar topics but there is no solution.
you can check this for reference :
https://www.digitalocean.com/community/questions/google-get-video-fmt-stream-map
I know it's all about ip adresse so how some people make this works ?
Regards.
This answer is not the final solution but it can hopefully bring some new info.
I have tried two ways already. One PHP from the site you suggested and one Javascript.
PHP gives me a link that has similar parameters as a working link that I got from browser developer tools so it could work. The problem as you say is IP because through PHP there is IP of the server and the rest is generated upon that. So I have tried to stream it through PHP to use the same IP address by readfile()
/*code follows code from the link*/
$gdrive = new gdrive;
$drive_link = 'https://drive.google.com/open?id=videoID';
$gdrive->getLink($drive_link);
$theFile = json_decode( $gdrive->getSources() , true );
//echo $theFile[0]['src'];
/*header('Content-Type: video/mp4');
header('Accept-Ranges: bytes');
header('Content-Length:'.filesize($theFile[0]['src']));*/
readfile($theFile[0]['src']);
but it doesn't work anyway. I don't know if that is right way or if there is another google security obstacle?
From Javascript, when trying to request docs.google.com/get_video_info or drive.google.com/file/d/videoID/view, it gives me a CORS Cross-Origin error (in Web Console) that I can't resolve.

Facebook Webhook The URL couldn't be validated. Response does not match challenge

I'm setting up comment moderation tool on a client's website, and in order to do that I need to create an app through facebook developer tools and create a webhook in order to be able to moderate comments.
When I try to set up the webhook, this is the error I receive.
The URL couldn't be validated. Response does not match challenge, expected value="716205142", received=""
And here's the code within the fbwebhook.php file:
<?php
$challenge = $_GET['hub_challenge'];
$verify_token = $_GET['hub_verify_token'];
if ($verify_token === 'TpQQFSkEJZbVlXZzCfEx') {
echo $challenge;
}
file_put_contents(
'log.txt',
"\n" . file_get_contents('php://input'),
FILE_APPEND
);
What is really driving me crazy is that this same file works on the staging site, works on other servers, but not on the server where the live site is being hosted.
We are on WPengine,
createwhimsy.staging.wpengine.com == webhook works
createwhimsy.com == webhook doesn't work (error above)
Tried on a digital ocean server == webhook works.
Tried on a different site being hosted on WPengine == webhook doesn't work (same error as above)
If I move the file I get a 404 error, so I know that FB is hitting the file, but it seems like FB isn't sending the right data to be used to verify, or something, not sure. This leads me to believe it's a DNS issue, or something with WPengine's hosting environment.
Any direction or input is much appreciated!
Discovered what is is.
WPengine has a redirect bot in place that will totally mess with facebooks validation post to your site. Just have to request them to disable the bot, and it worked just fine!

803 facebook error

I have an application on facebook that has worked for a month, but now I get the page in the application blank to enter it.
The application using the debugger get the error 803:
"Error":
"Message": "(# 803) Some of the aliases you do not exist Requested: bloggsamigos"
"Type": "OAuthException"
"Code": 803
If acceds directly see the message "the application is blocked because of problems with an external programmer."
What confuses me is that it has worked perfectly and I have not touched anything.
The application shows some pictures coming out of a query to a database hosted on the same domain. It's a blog of images. I have an administrator outside of facebook online application and show these images run from the administrator.
in index.php page, I control the user has the "like" activated to display a page or other. my code is this:
require 'src/facebook.php';
$config = array();
$config['appId'] ="xxxxxxxxxxxxxxx";
$config['secret'] = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$facebook = new Facebook($config);
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$signed_request = json_decode(base64_decode(strtr($payload, '-_', '+/'), true),true);
} else { echo "ERROR"; }
$lied = $signed_request['page']['liked'];
if ($signed_request['page']['liked']) {
include("fan.php");
}
else {
include("nofan.php");
}
configuration data are:
Namespace App --> bloggsamigos
Site URL --> with (http://www) mahesoblogsamigos.com/
Site Domain --> with (http://www) mahesoblogsamigos.com
Work Page --> with (http://) apps.facebook.com/bloggsamigos/
URL of the canvas --> with (https://) ssl15.ovh.net/~mahesobl/
Secure URL Canvas --> with (https://) ssl15.ovh.net/~mahesobl/
Canvas FBML / iframe --> iframe
I'm desperate, I tried many things, I wanted information, I sent emails to facebook, but I can not help. You can help me, please! I'll be very grateful.
Try changing the namespace to something else...
http://graph.facebook.com/bloggsamigos shows: "(#803) Some of the aliases you requested do not exist: bloggsamigos" meaning that facebook is not able to figure out what application that namespace matches with. Chances are something got messed up on Facebook's side.
If you really want that namespace, you may be able to change it to something else and then change it back to that to hopefully get it to record the information correctly.
You can also try filing a bug at http://developers.facebook.com/bugs but don't be surprised if you have to wait for weeks or months for a response.
Going to http://apps.facebook.com/bloggsamigos/ also shows a message saying "The app "Bloggs Amigos" is temporarily unavailable due to an issue with its third-party developer. We are investigating the situation and apologize for any inconvenience." However, that could mean almost anything.

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

Categories