Check for Valid/Active URLs before download - Laravel 7 - php

I'm trying to check download images and store locally in my assets folder.
Before start downloading, I want to check and make sure the link is still live.
I only want to start my download if the link is live 200 Ok.
Try #1
public function handle()
{
$skills = Skill::all();
if($skills != null){
foreach($skills as $i=>$skill){
if (strpos($skill->img_path, 'http') !== false) {
if(!isset($exception)) {
//update the path in DB
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$uploadSuccess = file_put_contents($path, file_get_contents($skill->img_path));
// dd($uploadSuccess);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
}
}
}
$skill->save();
}
}
}
I seems to get so many issues
One of them is
curl: (6) Could not resolve host: thumbsplus.tutsplus.com
Another one is
file_get_contents(https://assets-cdn.github.com/images/modules/logos_page/Octocat.png): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
What is the cleaner way ? Please suggest, I will try now.
Try #2
public function handle()
{
$skills = Skill::all();
if($skills != null){
foreach($skills as $i=>$skill){
if (strpos($skill->img_path, 'http') !== false) {
$file_headers = #get_headers($skill->img_path);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
if(!isset($exception)) {
//update the path in DB
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$uploadSuccess = file_put_contents($path, file_get_contents($skill->img_path));
// dd($uploadSuccess);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
}
}
}
}
$skill->save();
}
}
}
Try #3
public function handle()
{
$skills = Skill::all();
$failCount = 0;
$successCount = 0;
$failList = [];
if($skills != null){
foreach($skills as $i=>$skill){
if (strpos($skill->img_path, 'http') !== false) {
$file_headers = #get_headers($skill->img_path);
if(!$file_headers || strpos($file_headers[0], '404') !== false) {
$exists = false;
$failCount++;
array_push($failList,$skill->name);
// break;
}
else {
$exists = true;
$successCount++;
//DEBUG
// dd($file_headers[0]);
if(strpos($file_headers[0], '200')) {
//update the path in DB
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$uploadSuccess = file_put_contents($path, file_get_contents($skill->img_path));
// dd($uploadSuccess);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
}
}
}
}
$skill->save();
echo ".";
}
}
echo "\r\n";
$this->info('=========================');
$this->info('Success :'. $successCount);
$this->info('=========================');
$this->info('Fail :'. $failCount);
$this->info('List :'. print_r($failList));
$this->info('=========================');
}
seems to work
but it hang, sometimes more than 1 minute, at a certain dot
⚡️ php artisan skillIcons:download
..............................................................................................................................
=========================
Success :12
=========================
Fail :7
Array
(
[0] => GitHub
[1] => Geolocation API
[2] => Xcode
[3] => Protractor
[4] => Sketch
[5] => Amazon ECR
[6] => WinSCP
)
List :1
=========================
All images seems to be downloaded successfully
⚡️ ls public/assets/fe/img/skill/
AWS Console.png Digital Ocean.png Javascript.png PayPal.png Terminal.png
AWS.png Disqus.png Jest.png Photoshop.png TextMate.png
Alimofire.png Divvy.png Jira.png Pod.png TextWrangler.png
Amazon ECS.png Docker.png Kamar.png PostgreSQL.png Transmit.png
Amazon RDS.png Duet.png LESS.png PyCharm.png Twitter.png
Angular.png EC2.png Laravel Elixir.png Python.png Ubuntu.png
AngularJS.png Evernote .png Laravel.png QuickBooks.png VMWare Fusion .png
Apache.png Express.png Linode.png React Native.png VS Code.png
Atom.png Facebook.png Mac OS X.png Realm.png Vagrant.png
Bash.png Final Cut.png Markdown.png Redis.png Virtual Machine.png
BitBucket.png FusionCharts.png MobaXTerm.png RequireJS.png Virtualbox.png
Bower.png GitLab.png Mocha.png S3.png Webpack.png
CKEditor.png Go Daddy.png MySQL.png SAML 2.0.png Windows.png
CSS.png Google Chart.png NPM.png Salesforce.png Wireshark.png
Camtasia.png Google Map.png Navicat Premium.png Sass.png Word.png
Cent OS.png Google Translation.png Nginx.png Secure Shell.png Yarn.png
Chai.png Gulp.png Node.png Selenium.png iMovie.png
Chat.io.png HTML.png Noteability.png Shopify.png iOS.png
Coda.png Heroku.png OAuth 2.0.png SinonJS.png jQuery.png
CodeBox.png Illustrator.png Open Stack.png Siteground.png
Composer .png Instagram.png OpenID Connect.png Sublime Text.png
Confluence .png J Player.png PHP.png Swagger.png
3 seconds
How do I decrease the wait time to only 3 seconds ?

You have to handle error in some way.
You can try
try {
...
} catch () {
...
}
But I prefer doing things this way
public function handle()
{
Skill::get()->map(function($skill){
if(strpos($skill->img_path, 'http')) return;
$img = $this->getImageFromUrl($skill->img_path)
if(!$img == null) return;
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$fp = fopen($path,'x');
fwrite($fp, $img);
fclose($fp);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
$skill->save();
}
});
}
public function getImageFromUrl($url){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); // The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
curl_setopt($ch, CURLOPT_TIMEOUT, 2); // The maximum number of seconds to allow cURL functions to execute
$img = curl_exec($ch);
$err = curl_error($ch);
if($err) {
echo $err;
return null;
}
curl_close($ch);
return $img;
}
I refactored some code and if you prefer this keep it if not get only logic and do it as you prefer
Hope this helps

You may use active_url validation rule to check if the given URL is alive. According to the docs:
The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record.
if (validator([$skill->img_path], ['active_url'])->fails()) {
// URL is not valid/active
}
else {
// URL is valid/active
}

Related

Openssl_pkcs7_sign(): error opening file

it's my first time doing signing of cert using openssl. Keep hitting the above error and tried realpath() and appending file:// but still can't get openssl to sign the profile. I don't understand how this works. Any insights would be appreciated.
Edit1: I'm not sure which file is the problematic one. The error messages wasn't specific enough. Is there a way to tell?
Code and screenshots below:
function signProfile()
{
$filename = "./template.mobileconfig";
$filename = realpath($filename);
$outFilename = $filename . ".tmp";
$pkey = dirname(__FILE__) . "/PteKey.key";
$pkey = realpath($pkey);
$certFile = dirname(__FILE__) . "/CertToSign.crt";
$certFile = realpath($certFile);
// try signing the plain XML profile
if (openssl_pkcs7_sign($filename, $outFilename, 'file://'.$certFile, array('file://'.$pkey, ""), array(), 0, ""))
{
// get the data back from the filesystem
$signedString = file_get_contents($outFilename);
// trim the fat
$trimmedString = preg_replace('/(.+\n)+\n/', '', $signedString, 1);
// convert to binary (DER)
$decodedString = base64_decode($trimmedString);
// write the file back to the filesystem (using the filename originally given)
$fh = fopen($filename, 'w');
fwrite($fh, $decodedString);
fclose($fh);
// delete the temporary file
unlink($outFilename);
return TRUE;
}
else
{
return FALSE;
}
}
Remove unwanted fields if not used in
openssl_pkcs7_sign($mobileConfig, $tmpMobileConfig, $certFile, array($pkey, ""), array());
Make sure file paths are correctly supplied.
require_once('variables.php'); //stores abs path to $tmpMobileConfig/$pteKeyPath/$CertToSignPath
$prepend = "file://";
$mobileConfig = realpath("./template.mobileconfig");
$pkey = $prepend . $pteKeyPath;
$pkey = str_replace('\\', '/', $pkey);
$certFile = $prepend . $CertToSignPath;
$certFile = str_replace('\\', '/', $certFile);
$isSignedCert = openssl_pkcs7_sign($mobileConfig, $tmpMobileConfig, $certFile, array($pkey, ""), array());

edit wordpress plugin to make it front end

i am using a plugin for drawing on wordpress called drawblog which embed a drawing canvas at the bottom of the post page "wp-admin/post-new.php"
i am tring to find a front end solution for the drawing part to enable my users to draw without the dashboard i tried this tutorial to make a front end posting page,it worked but it only makes a form for posting and the drawing canvas does not appear.
another thing i tried was to edit the drawing plugin and make a short code to use it in a page on the website
"add_shortcode("draw-form3", "drawblog_post_form");"
and it made the canvas appear but without the ability of drawing.
following is the file of the plugin "drawblog/drawblog.php" which i tried to edit
<?php
/*
Plugin Name: DrawBlog
Plugin URI: http://drawblog.com/
Description: A WordPress plugin that allows commenters to draw a picture.
Version: 0.90
Author: Randy Tayler
Author URI: http://randytayler.com
License: GPL
*/
global $drawblog_db_version;
global $drawblog_form_complete;
global $drawblog_post_form_complete;
$drawblog_db_version = "0.63";
/* Runs when plugin is activated */
register_activation_hook(__FILE__,'drawblog_install');
// add_filter('comment_text', 'drawblog_add_image_to_comment');
// add_action('comment_form', 'drawblog_comment_form');
add_action('comment_post', 'drawblog_save_image');
add_filter('the_content', 'drawblog_add_image_to_post');
add_action('save_post', 'drawblog_save_post_image' );
add_action('edit_form_advanced', 'drawblog_post_form' );
/////tarek////
add_shortcode("draw-form3", "drawblog_post_form");
///////////
function drawblog_install() {
global $drawblog_db_version;
add_option("drawblog_db_version", $drawblog_db_version);
if (!is_dir(WP_CONTENT_DIR . '/drawblog/images')){
wp_mkdir_p(WP_CONTENT_DIR . '/drawblog/images', 755);
}
if (!get_option("drawblog_canvas_title")) add_option("drawblog_canvas_title", __('Click here to draw a picture to include in your comment.'));
if (!get_option("drawblog_hint_text1")) add_option("drawblog_hint_text1", __('Click on one of the images above to draw on it, or start from a blank canvas.'));
if (!get_option("drawblog_hint_text2")) add_option("drawblog_hint_text2", __('Include this picture with my comment.'));
if (!get_option("drawblog_warning1")) add_option("drawblog_warning1", __("This will copy over what you've already drawn. Are you sure?"));
if (!get_option("drawblog_warning2")) add_option("drawblog_warning2", __('Are you sure you want to clear your drawing?'));
if (!get_option("drawblog_canvas_width")) add_option("drawblog_canvas_width", 400);
if (!get_option("drawblog_canvas_height")) add_option("drawblog_canvas_height", 300);
if (!get_option("drawblog_post_classname")) add_option("drawblog_post_classname", drawblog_determine_classname());
if (!get_option("drawblog_show_canvas")) add_option("drawblog_show_canvas", true);
if (!get_option("drawblog_default_bg")) add_option("drawblog_default_bg", '');
}
function drawblog_add_image_to_comment($comment_text){
global $comment;
$drawblog_image = drawblog_get_image($comment->comment_ID);
if (($drawblog_image) &&
(is_file( WP_CONTENT_DIR . '/drawblog/images/' . $drawblog_image)) &&
(getimagesize( WP_CONTENT_DIR . '/drawblog/images/' . $drawblog_image) !== false)){
$comment_text = "<img src=\"". content_url(). '/drawblog/images/'.$drawblog_image."\" class=\"drawblogimage\"><br>".$comment_text;
}
return $comment_text;
}
function drawblog_add_image_to_post($post_text){
global $post;
$drawblog_image = drawblog_get_post_image($post->ID);
if (($drawblog_image) &&
(is_file( WP_CONTENT_DIR . '/drawblog/images/' . $drawblog_image)) &&
(getimagesize( WP_CONTENT_DIR . '/drawblog/images/' . $drawblog_image) !== false)){
$post_text = "<img src=\"". content_url(). '/drawblog/images/'.$drawblog_image."\" class=\"drawblogimage\"><br>".$post_text;
}
return $post_text;
}
function drawblog_get_image($comment_id){
global $wpdb;
$meta = get_comment_meta($comment_id, 'drawblog_image');
return $meta[0];
}
function drawblog_get_post_image($post_id){
global $wpdb;
$meta = get_post_meta($post_id, 'drawblog_image');
return $meta[0];
}
function drawblog_comment_form(){
global $drawblog_form_complete;
if (!$drawblog_form_complete){
echo drawblog_add_canvas();
$drawblog_form_complete = true;
}
}
function drawblog_post_form(){
global $drawblog_post_form_complete;
global $post;
global $image_exists;
$drawblog_image = drawblog_get_post_image($post->ID);
if (($drawblog_image) &&
(is_file( WP_CONTENT_DIR . '/drawblog/images/' . $drawblog_image)) &&
(getimagesize( WP_CONTENT_DIR . '/drawblog/images/' . $drawblog_image) !== false)){
$image_exists = 'true';
} else {
$image_exists = 'false';
}
if (!$drawblog_post_form_complete){
echo drawblog_add_post_canvas();
$drawblog_post_form_complete = true;
}
}
function drawblog_save_image($comment_id){
global $wpdb;
if ($_POST['drawblog_include_pic'] == true){
$data = $_POST['drawblog_picture'];
$raw_data = str_replace(' ','+',$data);
$filtered_data=substr($raw_data, strpos($raw_data, ",")+1);
$data = base64_decode($filtered_data);
$new_image = uniqid($comment_id.'_').'.png';
$fp = fopen(WP_CONTENT_DIR . '/drawblog/images/'.$new_image, 'wb' );
fwrite( $fp, $data);
fclose( $fp );
if (is_file(WP_PLUGIN_DIR . "/drawblog/icons/dbwm.png")){
$im = imagecreatefrompng(WP_CONTENT_DIR . '/drawblog/images/'.$new_image);
$src = imagecreatefrompng(WP_PLUGIN_DIR . "/drawblog/icons/dbwm.png");
list($wm_width, $wm_height) = getimagesize(WP_PLUGIN_DIR . "/drawblog/icons/dbwm.png");
imagecopy($im, $src, get_option('drawblog_canvas_width')-$wm_width, get_option('drawblog_canvas_height') - $wm_height, 0, 0, $wm_width, $wm_height);
imagepng($im, WP_CONTENT_DIR . '/drawblog/images/'.$new_image);
}
add_comment_meta($comment_id, 'drawblog_image', $new_image);
}
}
function drawblog_save_post_image($post_id){
global $wpdb;
if ($_POST['drawblog_include_pic'] == true){
$data = $_POST['drawblog_picture'];
$raw_data = str_replace(' ','+',$data);
$filtered_data=substr($raw_data, strpos($raw_data, ",")+1);
$data = base64_decode($filtered_data);
$new_image = uniqid('p'.$post_id.'_').'.png';
$fp = fopen(WP_CONTENT_DIR . '/drawblog/images/'.$new_image, 'wb' );
fwrite( $fp, $data);
fclose( $fp );
if (is_file(WP_PLUGIN_DIR . "/drawblog/icons/dbwm.png")){
$im = imagecreatefrompng(WP_CONTENT_DIR . '/drawblog/images/'.$new_image);
$src = imagecreatefrompng(WP_PLUGIN_DIR . "/drawblog/icons/dbwm.png");
list($wm_width, $wm_height) = getimagesize(WP_PLUGIN_DIR . "/drawblog/icons/dbwm.png");
imagecopy($im, $src, get_option('drawblog_canvas_width')-$wm_width, get_option('drawblog_canvas_height') - $wm_height, 0, 0, $wm_width, $wm_height);
imagepng($im, WP_CONTENT_DIR . '/drawblog/images/'.$new_image);
}
delete_post_meta($post_id, 'drawblog_image');
add_post_meta($post_id, 'drawblog_image', $new_image);
} else {
delete_post_meta($post_id, 'drawblog_image');
}
}
function drawblog_check_options(){
//new options pose a little trouble on upgrade. This'll force them to update if the installation trick didn't work
if (!get_option("drawblog_hint_text1")) add_option("drawblog_hint_text1", __('Click on one of the images above to draw on it, or start from a blank canvas.'));
if (!get_option("drawblog_hint_text2")) add_option("drawblog_hint_text2", __('Include this picture with my comment.'));
if (!get_option("drawblog_warning1")) add_option("drawblog_warning1", __("This will copy over what you've already drawn. Are you sure?"));
if (!get_option("drawblog_warning2")) add_option("drawblog_warning2", __('Are you sure you want to clear your drawing?'));
if (get_option("drawblog_hint_text1")=='') update_option("drawblog_hint_text1", __('Click on one of the images above to draw on it, or start from a blank canvas.'));
if (get_option("drawblog_hint_text2")=='') update_option("drawblog_hint_text2", __('Include this picture with my comment.'));
if (get_option("drawblog_warning1")=='') update_option("drawblog_warning1", __("This will copy over what you've already drawn. Are you sure?"));
if (get_option("drawblog_warning2")=='') update_option("drawblog_warning2", __('Are you sure you want to clear your drawing?'));
}
function drawblog_add_canvas(){
drawblog_check_options();
global $post;
if (get_option('drawblog_api_key')!=''){
$ch = curl_init('http://drawblog2.com/auth.php');
curl_setopt($ch, CURLOPT_POST, true);
$postfields = 'apikey='.get_option('drawblog_api_key').'&domain='.$_SERVER['HTTP_HOST'];
$postfields .='&theme='.get_stylesheet(); // if you're using the api, I need your theme
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($ch);
curl_close($ch);
}
$width = get_option('drawblog_canvas_width');
$height = get_option('drawblog_canvas_height');
include "drawblog_canvas.php";
}
function drawblog_add_post_canvas(){
drawblog_check_options();
if (get_option('drawblog_api_key')!=''){
$ch = curl_init('http://drawblog.com/auth.php');
curl_setopt($ch, CURLOPT_POST, true);
$postfields = 'apikey='.get_option('drawblog_api_key').'&domain='.$_SERVER['HTTP_HOST'];
$postfields .='&theme='.get_stylesheet(); // if you're using the api, I need your theme
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($ch);
curl_close($ch);
}
$width = get_option('drawblog_canvas_width');
$height = get_option('drawblog_canvas_height');
include "drawblog_post_canvas.php";
}
function drawblog_determine_classname(){
$themedir = get_stylesheet_directory();
$theme = get_stylesheet(); // I wish this function was called get_theme(), but whatever
switch ($theme){
case 'custom-community':
$postclass = 'post-content';
break;
case 'inferno-mf':
$postclass = 'post';
break;
case 'easel':
case 'eclipse':
case 'ifeature':
$postclass = 'entry';
break;
case 'responsive':
$postclass = "post-entry";
break;
case 'mantra':
case 'pagelines':
case 'pinboard':
case 'twentyeleven':
case 'twentyten':
case 'twentytwelve':
default:
$postclass = "entry-content";
break;
}
return $postclass;
}
function get_image_data($img){
$domain_bits = parse_url($img);
$domain = $domain_bits['host'];
$filename = $domain_bits['path'];
if ($domain == $_SERVER['SERVER_NAME']) {
$file = $img;
} else {
$file = plugins_url().'/drawblog/drawblog_safeimage.php?img='.urlencode($img);
}
$img_info = getimagesize($img);
if ($img_info !== false){
echo json_encode(array($file,$img_info[0], $img_info[1]));
} else echo '';
}
if ( is_admin() ){
add_action('admin_menu', 'drawblog_admin_menu');
function drawblog_admin_menu() {
add_options_page('DrawBlog', 'DrawBlog', 'administrator', 'drawblog', 'drawblog_settings_page');
}
function drawblog_check_api_key($apikey){
$ch = curl_init('http://drawblog.com/validate.php');
curl_setopt($ch, CURLOPT_POST, true);
$postfields = 'apikey='.$apikey.'&domain='.$_SERVER['HTTP_HOST'];
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retval = curl_exec($ch);
curl_close($ch);
return $retval;
}
function drawblog_update_options($values){
$title = $values['drawblog_canvas_title'];
$hint1 = $values['drawblog_hint_text1'];
$hint2 = $values['drawblog_hint_text2'];
$warning1 = $values['drawblog_warning1'];
$warning2 = $values['drawblog_warning2'];
$width = intval($values['drawblog_canvas_width']);
$height = intval($values['drawblog_canvas_height']);
$show_canvas = $values['drawblog_show_canvas'];
if ($values['drawblog_default_bg']) $default_bg = $values['drawblog_default_bg'];
if ($width<=0) return __('Canvas width'); //returns other than 'success', below, indicate a field with an error. Canvases cannot be negative or zero values.
if ($height<=0) return __('Canvas height');
if (($values['drawblog_api_key']!='') && (!(drawblog_check_api_key($values['drawblog_api_key']) == 1))) return __('API key is invalid or expired. Visit DrawBlog.com to purchase or renew an API key.');
update_option('drawblog_api_key', $values['drawblog_api_key']);
update_option('drawblog_canvas_width', $width);
update_option('drawblog_canvas_height', $height);
update_option('drawblog_canvas_title', $title);
update_option('drawblog_hint_text1', $hint1);
update_option('drawblog_hint_text2', $hint2);
update_option('drawblog_warning1', $warning1);
update_option('drawblog_warning2', $warning2);
update_option('drawblog_post_classname', $values['post_class_name']);
update_option('drawblog_show_canvas', $show_canvas);
update_option('drawblog_default_bg', $default_bg);
return 'success';
}
function drawblog_settings_page() {
include "drawblog_admin.php";
}
}
?>
now what is the best solution to get drawblog plugin to work on new page ?
There are some plugins allowing posting from the frontend: https://premium.wpmudev.org/blog/wordpress-post-frontend-plugins/
It might work with your drawing thing.
Hope it helps,
Ondrej

Force download on GCS via App Engine using Signed URL

I get my file via:
require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';
use google\appengine\api\cloud_storage\CloudStorageTools;
$public_link = CloudStorageTools::getPublicUrl("gs://bucket/file.pdf", false);
If I go to $public_link in the browser, it shows the PDF inside the browser. I am trying to figure out how I can force the download of this file.
Google App Engine only has a 60 second timeout so I'm afraid the serve function wont work via GAE. Does anyone have any suggestions?
--
EDIT
Andrei Volga's previous answer in this post suggests I use a Signed URL with a response-content-distribution header.
So far, I am able to create a signed URL that successfully shows the file but I am not able to generate a signed url that has any sort of header at all aka create a signed URL that will force the download instead of just showing it.
This is what I have so far, most of which is courtesy of mloureiro.
function googleBuildConfigurationString($method, $expiration, $file, array $options = [])
{
$allowedMethods = ['GET', 'HEAD', 'PUT', 'DELETE'];
// initialize
$method = strtoupper($method);
$contentType = $options['Content_Type'];
$contentMd5 = $options['Content_MD5'] ? base64_encode($options['Content_MD5']) : '';
$headers = $options['Canonicalized_Extension_Headers'] ? $options['Canonicalized_Extension_Headers'] . PHP_EOL : '';
$file = $file ? $file : $options['Canonicalized_Resource'];
// validate
if(array_search($method, $allowedMethods) === false)
{
throw new RuntimeException("Method '{$method}' is not allowed");
}
if(!$expiration)
{
throw new RuntimeException("An expiration date should be provided.");
}
return <<<TXT
{$method}
{$contentMd5}
{$contentType}
{$expiration}
{$headers}{$file}
TXT;
}
function googleSignString($p12FilePath, $string)
{
$certs = [];
if (!openssl_pkcs12_read(file_get_contents($p12FilePath), $certs, 'notasecret'))
{
echo "Unable to parse the p12 file. OpenSSL error: " . openssl_error_string(); exit();
}
$RSAPrivateKey = openssl_pkey_get_private($certs["pkey"]);
$signed = '';
if(!openssl_sign( $string, $signed, $RSAPrivateKey, 'sha256' ))
{
error_log( 'openssl_sign failed!' );
$signed = 'failed';
}
else $signed = base64_encode($signed);
return $signed;
}
function googleBuildSignedUrl($serviceEmail, $file, $expiration, $signature)
{
return "http://storage.googleapis.com{$file}" . "?GoogleAccessId={$serviceEmail}" . "&Expires={$expiration}" . "&Signature=" . urlencode($signature);
}
$serviceEmail = '<EMAIL>';
$p12FilePath = '../../path/to/cert.p12';
$expiration = (new DateTime())->modify('+3hours')->getTimestamp();
$bucket = 'bucket';
$fileToGet = 'picture.jpg';
$file = "/{$bucket}/{$fileToGet}";
$string = googleBuildConfigurationString('GET', $expiration, $file, array("Canonicalized_Extension_Headers" => ''));
$signedString = googleSignString($p12FilePath, $string);
$signedUrl = googleBuildSignedUrl($serviceEmail, $file, $expiration, $signedString);
echo $signedUrl;
For small files you can use serve option instead of public URL with save-as option set to true. See documentation.
For large files you can use a Signed URL with response-content-disposition parameter.
You can add and additional query string only.
https://cloud.google.com/storage/docs/xml-api/reference-headers#responsecontentdisposition
response-content-disposition
A query string parameter that allows content-disposition to be overridden for authenticated GET requests.
Valid Values URL-encoded header to return instead of the content-disposition of the underlying object.
Example
?response-content-disposition=attachment%3B%20filename%3D%22foo%22

PHP, file_get_contents() returning null for PDF files

I would like to get content of a pdf file into a variable. I tried to do this using
file_get_contents("file.pdf")
but it's returning NULL. If I do the same with .jpg file for example it's working. Any idea how to overcome this problem? Is there another way? Thanks in advance!
Edit:
Service code:
<?php
function sendAttachment($msg){
$responsePayloadString = <<<XML
<payload:receiveReport xmlns:payload="http://wso2.org/wsfphp/samples/mtom">
<payload:reports>
<payload:report>
<payload:content xmlmime:contentType="application/pdf" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
<xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:report1"></xop:Include>
</payload:content>
</payload:report>
</payload:reports>
</payload:receiveReport>
XML;
$report1 = file_get_contents("samplePDF.pdf");
$responseMessage = new WSMessage($responsePayloadString,
array("attachments" => array("report1" => $report1),
"useWSA" => TRUE));
return $responseMessage;
}
$operations = array("receiveReport" => "sendAttachment");
$service = new WSService(array("operations" => $operations,
"requestXOP" => TRUE,
"useMTOM" => TRUE));
$service->reply();
?>
Client Code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
/******* FirePHP Debug *******/
require_once('../FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
/******* FirePHP Debug *******/
$requestPayloadString = <<<XML
<receiveReport></receiveReport>
XML;
try {
$client = new WSClient(
array( "to" => "http://localhost/ReportDL/ReportService.php",
"useMTOM" => TRUE,
"responseXOP" => TRUE,
"useWSA" => TRUE));
$requestMessage = new WSMessage($requestPayloadString);
$responseMessage = $client->request($requestMessage);
$cid2stringMap = $responseMessage->attachments;
$cid2contentMap = $responseMessage->cid2contentType;
if($cid2stringMap && $cid2contentMap){
foreach($cid2stringMap as $i=>$value){
$f = $cid2stringMap[$i];
$contentType = $cid2contentMap[$i];
$firephp->log($f, "pdf"); //DEBUG
}
}else{
printf("attachments not received ");
}
} catch (Exception $e) {
if ($e instanceof WSFault) {
printf("Soap Fault: %s\n", $e->Reason);
} else {
printf("Message = %s\n",$e->getMessage());
}
}
?>
Edit2:
string '%PDF-1.5
%âãÏÓ
2 0 obj
<</Length 285/Filter/FlateDecode>>stream
xœ’_KÃ0Åßó)Ä{“4i|S¨‚ÓÀžµKiçÚ­0¿½i;ëýƒ#ÐÐÃýœž¦dwŽI
&ÒàV,qlÁJfŒ�%hCåÙ’­;YǪÕrÿÎÿêeã|}O#\Æ0,‹<ÌXäE¯6OW°‹‡z
ñÑ
Z¸}¼t]®æ$ä’Õð³ToGÞ!5¾í»R ›4Ù<)¤:•&ž#©ù¸v’4®ƒžB®gÁ6è49X»P‚c#uÌíPñîÝÃҿ“ß|V;Hö/Å&÷Ðw?f I.MHq²Mö>­w~5k$‘8Šq£ç:õÛmVçù?òi©ý'Ó-Í^$eNðÿ\¥sá6ø(¼`ßè¿Á÷
endstream
endobj
6 0 obj
<</Type/Catalog/PageMode/UseNone/Pages 3 0 R>>
endobj
7 0 obj
<</Creator(BIRT Report Engine 2.6.0 using iText version unknown.)/Producer('... (length=1231)
file_get_contents() should return FALSEif a file is unreadable - otherwise it return a string containing the files content.
The problem must lie elsewhere - start debugging your code in a procedural way with var_dump() to find out where your data is lost.
You need to add the following code at the top of your PHP page.
header("Content-type:application/pdf");
In case anyone else comes here for this, my issue was the file Permissions weren't correct for www-data. Once permissions were changed, the web server could read it and functioned as expected.
I know it's a "duh" thing, but it wasn't obvious to me at first.
if ($file_ext == 'pdf') { $content_type = "application/pdf"; }
elseif($file_ext == 'ppt') { $content_type = "application/vnd.ms-powerpoint"; }
elseif($file_ext == 'pptx') { $content_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; }
elseif($file_ext == 'xls') { $content_type = "application/vnd.ms-excel"; }
elseif($file_ext == 'xlsx') { $content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
elseif($file_ext == 'doc') { $content_type = "application/vnd.ms-word"; }
elseif($file_ext == 'docx') { $content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; }
else { $content_type = "application/octet-stream"; }
$document_contents = file_get_contents("/Server/location/to/$file");
header("Content-type: $content_type");
echo $document_contents;
die();

Transfer File us NuSOAP

I am having a problem transferring files using NuSOAP. I understand that you can read a file and transfer it as a string, but it's not working. Here is an example:
Client:
require('libraries/nusoap/nusoap.php');
$url = "http://www.example.com";
$client = new nusoap_client($url);
args = array('file_name' => 'myfile.zip');
$return = $client->call('getFile', array($args));
if(empty($return){
echo "WHY IN THE WORLD IS THIS EMPTY!!!!!";
}
Server:
require('libraries/nusoap/nusoap.php');
$server = new nusoap_server;
$server->configureWSDL('server', 'urn:server');
$server->wsdl->schemaTargetNamespace = 'urn:server';
$server->register('getFile',
array('value' => 'xsd:string'),
array('return' => 'xsd:string'),
'urn:server',
'urn:server#getFile');
function getFile($value){
$returnData= "";
$filePath=$value['file_path'];
$mode="r";
if (floatval(phpversion()) >= 4.3) {
$returnData= file_get_contents($filePath);
} else {
if (!file_exists($filePath)){
return -3;
}
$handler = fopen($filePath, $mode);
if (!$handler){
return -2;
}
$returnData= "";
while(!feof($handler)){
$returnData.= fread($handler, filesize($filePath));
}//end while
fclose($handler);
}//end else
return $returnData;
}
Here is the really strange part. If I return the file name or file size or something like that, it will work. It will just not return the file itself. Help please.
In the server side getFile function you should return base64_encode($returnData);

Categories