I'm using PHP code to retrieve the content of .m3u8 with a Signed URL from AWS CloudFront.
I can't be able to play the chunk .ts files inside it since you need also to sign their URL.
So, using PHP code, I re-write the contents of .m3u8
<?php
$resourceKey = 'https://abcdefg.cloudfront.net/abcdef-1234.MOV_1000k*';
$expires = time() + 172800;
$customPolicy = <<<POLICY
{
"Statement": [
{
"Resource": "{$resourceKey}",
"Condition": {
"DateLessThan": {"AWS:EpochTime": {$expires}}
}
}
]
}
POLICY;
$signedUrl = $cloudFrontClient->getSignedUrl([
'url' => $resourceKey,
'policy' => $customPolicy,
'private_key' => public_path().'/pk-ABCDEFGHIJ.pem',
'key_pair_id' => 'ABCDEFGHIJ'
]);
$signedUrl = str_replace('*', '.m3u8', $signedUrl);
// get contents of the file and the query string
$content = file_get_contents($signedUrl);
parse_str(parse_url($signedUrl)['query'], $params);
$qs = "?Policy=".$params['Policy']."&Signature=".$params['Signature']."&Key-Pair-Id=".$params['Key-Pair-Id'];
// rewriting process
$replaceThis = array(".m3u8", ".ts");
$withThisValue = array(".m3u8".$qs, ".ts".$qs);
$content = str_replace($replaceThis, $withThisValue, $content);
?>
I was able to sign the .ts inside the .m3u8 file. But the problem now is that, how can I convert $content to something playable to HTML5 video with VideoJS without downloading the file contents using file_put_contents? I don't want to save it on the directory. Just to convert it on blob data or decode it and play it Something like this. Is this possible?
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<video id='hls-example' class="video-js vjs-default-skin" width="640" height="480" controls>
<source src="<?php echo $content; ?>" type="application/x-mpegURL">
Your browser does not support the video tag.
</video>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>
<script>
var player1 = videojs('hls-example');
</script>
</body>
</html>
PS: I tried AWS Lambda Edge. But, it doesn't work when there are many chunk .ts inside the m3u8 file. It returns an error that exceeds the Viewer Request Quota of 40KB.
Related
The API documentation shows this example:
$fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
$content = $driveService->files->export($fileId,
'application/pdf',
array('alt' => 'media')
);
How do I show the image in my HTML?
(I've already figured out how authorization with the Google API works.)
You can embed the raw image data using base64_encode
Your API call is returning a GuzzleHttp Response object, so you can get the raw data by calling:
$rawData = $response->getBody()->getContents();
// Alternatively, you should be able to cast it to a string (I would try the first method then this alternative if you want)
$rawData = (string) $response->getBody();
To embed that raw data as an html <img /> you can do something like:
// Convert to base64 encoding
$imageData = base64_encode($rawData);
// Get the content-type of the image from the response
$contentType = $response->getHeader("content-type");
// Format the image src: data:{mime};base64,{data}
$src = 'data: '.$contentType.';base64,'.$imageData;
// Echo out a sample image
echo '<img src="'.$src.'" />';
Source
I'm using this to output a pdf document :
$response = new \Symfony\Component\HttpFoundation\Response(file_get_contents($thefile), 200, [
'Content-Description' => 'File transfer',
'Content-Disposition' => 'filename="' . $filename . '"',
'Content-Transfer-Encoding' => 'binary',
'Content-Type' => 'application/pdf',
]);
unlink($thefile);
$response->send();
In the generated page, the header title is the link to the page.
How can I customize the title ?
You have to include the title inside the pdf.
I just have to generate the pdf from a script as src of an iframe !
This way the head title is kept !
<head>
<title>THE TITLE</title>
</head>
<body>
<iframe src="process.php"></iframe>
</body>
</html>
Or I could ajax the php script, and return the result in a container element (eg div)
I developed an API in PHP, hosted at Google App Engine, to use with my Android app.
Basically, when a user wants to change his profile picture, the android app send a request to the server containing the user id, the session key and the picture to upload. I want to upload this picture on the Google Cloud, but since Google App Engine require you to build a public upload URL to upload a file, how can I generate the upload URL and then use this URL to upload the profile picture in my Google Cloud in one request?
I tried to use a basic PHP redirect after generating the upload URL but I get a HTTP 405.
I am really stuck and I honestly don't understand why you NEED to create an URL before uploading a file to Google App Engine...
Source: https://cloud.google.com/appengine/docs/php/googlestorage/user_upload
It seems that the photo that you want to upload on Google Cloud Storage saves as a Blob on GCS that's why they ask you to create a URL. Follow the document [1] it is related to Blobstore API in python but the concept of blob is same for any language so its good to read about blobs. Also find below a sample code which might help you to upload a photo on GCS.
$options = [ 'gs_bucket_name' => 'bucket-name' ];
$upload_url = CloudStorageTools::createUploadUrl('/upload', $options);
<form action="<?php echo $upload_url?>" method="post" enctype="multipart/form-data">
<input type ="file" name="fileupload" id = "fileupload">
<input type="submit" value="Upload" name ="submit">
</form>
Upload Handler:
<?php
use google\appengine\api\cloud_storage\CloudStorageTools;
$gs_name = $_FILES['fileupload'];
$buffer = file_get_contents($gs_name['tmp_name']);
$bucket = CloudStorageTools::getDefaultGoogleStorageBucketName();
$user_pic_url = 'gs://' . $bucket
. (substr($final_file_path,0,1) != '/' ? '/' : '' )
. $final_file_path;
// set file options on Google Could Storage
$options = stream_context_create( ['gs' => ['acl' => 'public-read',
'Content-Type' => 'image/jpg']] );
echo "<br>";
$my_file = fopen($user_pic_url, 'w', false, $options);
fclose($my_file);
[1] BlobStore API: https://cloud.google.com/appengine/docs/python/blobstore/
$pdf->Output('example_025.pdf', 'I');
$DynamicNameofPic = rand(1000,10000)."_Invoice.pdf";
$FileNameDynamic = "gs://#######/".$DynamicNameofPic;
$pdf->Output($FileNameDynamic,'F');
$image_dataURL = "https://storage.googleapis.com/##########/".$DynamicNameofPic;
$image_data = file_get_contents($image_dataURL);$fileName = $DynamicNameofPic;
<?php
$title = urlencode('Nature');
$url = urlencode('http://amazingpics.net/content/Nature/Amazing%20Nature%20698.jpg');
$image = urlencode('http://trainees.ocs.org/training/hariharan/01-09-2014/images/img2.jpg');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sharing Images</title>
<link href="css/share.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="all">
<div class="top">
<div class="nature" align="center">
<p class="nat">I LOVE NATURE</p>
</div>
<p> </p>
<div class="img"><img src="images/img2.jpg" height="250" width="500" /></div>
<div class="share"><a onClick="window.open('http://www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[url]=<?php echo $url; ?>&&p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=600,height=400');" href="javascript: void(0)"><img src="images/share.png" width="200" height="40" /></a></div>
<div class="share"><a onClick="window.open('http://twitter.com/intent/tweet?url=<?php echo $url;?>','sharer','toolbar=0,status=0,width=600,height=400');" href="javascript: void(0)"><img src="images/twitter.png" width="200" height="40" /></a></div>
<p> </p>
</div>
</div>
</body>
</html>
I tried the above code for sharing images on facebook and twitter. it works correctly in facebook, but the image cannot displayed in twitter. the link only displayed. please help me to share images on twitter in php. thanks in advance...
Even the code and examples on twitter API documentation is straight forward but It wasn’t easy to figure out the right code with twitter API for tweet images.
To create twitter application you need to do that from : https://dev.twitter.com/
In twitter dev site, you have to specify the name and decryption of your application plus the URL to your main page and the callback page (more on these two page later). Also you have to make sure you set your twitter application access to “Read and Write” in order to give it authorization to tweet images on user behalf.
After the app is created correctly, twitter will provide you with a “Consumer key” and “Consumer secret”, you need to keep these two string variables because they are required to identify your application while communicating with twitter API to tweet images.
Download twitter code libraryDownload the Required PHP Libraries
For twitter authentication and image uploading to twitter you need tmhOAuth.php and tmhUtilities.php you can download them from https://github.com/opauth/twitter/tree/master/Vendor/tmhOAuth
How the Tweet Images Code Works?
The code for tweet images divided in two files, the first is “start.php” where the code start and a second file “callback.php” where twitter will redirect user back after giving authorization to our app. (the URL to our callback.php file has been updated in App settings in steps above)
How the code works
i)In “start.php” the first thing we have to do is asking for temporary access token from twitter API using the key and secret that we get them when we create the application (this process call get request token).
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => API_KEY,
'consumer_secret' => API_SEC,
'curl_ssl_verifypeer' => false
));
$tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''));
$response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);
ii). After we have the temporary access token we need to save them in cookies for later use after the user authenticate our App and redirected back to
“callback.php”
$temp_token = $response['oauth_token'];
$temp_secret = $response['oauth_token_secret'];
$time = $_SERVER['REQUEST_TIME'];
setcookie("Temp_Token", $temp_token, $time + 3600 * 30, '/twitter_test/');
setcookie("Temp_Secret", $temp_secret, $time + 3600 * 30, '/twitter_test/'); setcookie("Tweet_Txt", $txt, $time + 3600 * 30, '/twitter_test/');
setcookie("Img_Url", $img, $time + 3600 * 30, '/twitter_test/');
iii). Asking user to give authorization to our app requires a redirect to Twitter API page where user will fill his username and password and complete the authorization process.
$url = $tmhOAuth->url("oauth/authorize", "") . '?oauth_token=' . $temp_token;
header("Location:".$ url);
exit();
iv). When authorization is been given to our app, Twitter API will redirect the user to “callback.php” URL specified in App settings.
v). In “callback.php” file the actual code to tweet images exists. First we retrieve the temporary access token from cookies and we exchange them with correct access token.
$token = $_COOKIE['Temp_Token'];
$secret = $_COOKIE['Temp_Secret'];
$img = $_COOKIE['Img_Url'];
$txt = $_COOKIE['Tweet_Txt'];
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => API_KEY,
'consumer_secret' => API_SEC,
'user_token' => $token,
'user_secret' => $secret,
'curl_ssl_verifypeer' => false
));
$tmhOAuth->request("POST", $tmhOAuth->url("oauth/access_token", ""), array(
// pass the oauth_verifier received from Twitter
'oauth_verifier' => $_GET["oauth_verifier"]
));
$response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);
$tmhOAuth->config["user_token"] = $response['oauth_token'];
$tmhOAuth->config["user_secret"] = $response['oauth_token_secret'];
vi). After we get the correct access token, we tweet the image we want.
$img = './'.$img;
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$img}",
'status' => "$txt"
),
true, // use auth
true // multipart
);
vii). The returned code from twitter API will tell us if the operation was done correctly or not.
if ($code == 200){
echo '<h1>Your image tweet has been sent successfully</h1>';
}else{
tmhUtilities::pr($tmhOAuth->response['response']);
}
I have developed a facebook application that contains following files
1) index.php
2) cap3.php
where cap3.php generates an image using GD in PHP.
index.php displays this image using following code
<img src="cap3.php">
now I want this generated image to be posted on user's timeline.
I have tried to do so by using following code:
$facebook->setFileUploadSupport(true);
$img = 'cap3.php';
$args=array( 'source' => '#' .$current , 'message' => 'Photo uploaded via!' );
$photo = $facebook->api('/me/photos', 'POST', $args);
but the image is not posted on user's timeline
please help.
One way to do that is to put your cap3.php file in your remote host to get an URL to it. For example : http://www.example.com/cap3.php. Then, you download that image from your app and send it to facebook.
Let's see an example:
$local_img = 'cap3.png'; // I assume your cap3.php generates a PNG file
$remote_img = 'http://www.example.com/cap3.php';
// sample: check for errors in your production app!
$img_content = file_get_contents($remote_img);
file_put_contents($locale_img, $img_content);
$facebook->setFileUploadSupport(true);
$args=array( 'source' => '#' .$locale_img , 'message' => 'Photo uploaded via!' );
$photo = $facebook->api('/me/photos', 'POST', $args);