I'm stuck and I was hoping somebody here could help me.
I want to create a link to a file in a php script (the file is actually an image, a .tif image). I have Google d this relentlessly, to no avail.
The firewall is blocking external connections but I am running this query on a machine that mimics an internal connection. I currently use this machine to allow external user to run queries that hit the internal database so I know this works…
For instance this part works just fine:
$result = pg_query($conn, $query);
while($row=pg_fetch_assoc($result))
{
echo "<p>image details:<br />image: <u>" . $row['field'] . "</u> image date: <u>" . $row['field'] . "</u> image path: <u>" . $row['filename'] . "</u></p>";
The part of the query that I want to turn into a link is the $row[‘filename’], which is returned as
//host\path\path\path\path\path\path\path.TIF
… but now I want access to certain files associated with those queries. I want to turn this filename into a url that, when put into a link, goes to this file and opens it:
$imageURL = $row['filename'];
echo "<p>Using imageURL: <a href='$imageURL' border='0' target='_blank'>Click Here</a></p>";
Maybe this isn't possible.
I just can't seem to figure out how to fetch the image.
I do not have imagemagick or imagick and I don't want to go that route. Thanks in advance for any help.
EDIT
The machine I am running the query on is http://webapps.example.com
The machine I am querying (where the image resides) is not - the image path I am trying to return (as a link) is //hostipaddress\path\path\path\path\path\path\filename.TIF
You can use a proxy page which you can link to normally which does the job of rendering the image.
Let's call the proxy page readimage.php and it takes the filename or path as an argument.
Your link would look something like this:
<?php
$imageURL = $row['filename'];
echo "<p>Using imageURL: <a href='readimage.php?image=$imageURL' border='0' target='_blank'>Click Here</a></p>";
?>
readimage.php
<?php
$img = isset( $_GET['image'] ) ? $_GET['image'] : null;
if ( !$img )
return;
// Build internal file path
//$filepath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'myimages' . DIRECTORY_SEPARATOR . $img;
$filepath = $img;
//==========================
// VERY IMPORTANT TO WHITELIST THE PATH OR RESULT to make sure you're not showing unintended data
//==========================
if ( file_exists( $filepath ) ) {
// Find mime type
$mime = '';
// Try using the fileinfo functions. Requires PHP >= 5.3 and PECL 1.0
if ( function_exists( 'finfo' ) ) {
$finfo = new finfo( FILEINFO_MIME ); // return mime type ala mimetype extension
/* get mime-type for a specific file */
$mime = $finfo->file( $filepath );
}
// No mime yet? Try to use the deprecated mime_content_type() function
if ( !$mime && function_exists( 'mime_content_type' ) ) {
$mime = mime_content_type( $filepath );
}
// Not yet? Fallback to extensions :(
if ( !$mime ) {
$ext = pathinfo( $filepath, PATHINFO_EXTENSION );
switch ( $ext ) {
case "jpg" :
case "jpeg" :
case "jpe" :
$mime = "image/jpg";
break;
case "png" :
case "gif" :
case "bmp" :
case "tiff" :
$mime = "image/" . strtolower( $ext );
break;
}
}
if ( $mime ) {
header( 'Content-type: ' . $mime );
readfile( $filepath );
}
}
?>
If you can have a proxy address that would allow you to send request outside, you could do it using curl.
** update 2
Image from curl
Save image from url with curl PHP
Curl behind a proxy:
curl_setopt($ch, CURLOPT_PROXY, "http://to.the.proxy.address");
curl_setopt($ch, CURLOPT_PROXYPORT, 8080);
curl_setopt ($ch, CURLOPT_PROXYUSERPWD, "your password");
Related
I need assistance to more understand the concept so I can become a better developer. I want to learn how to refactor the code and erase all duplications.
What's the best practices for image uploads? Renaming them correctly?
I have a block of code that handles two attachments:
if( $request->hasFile('LFImage') ) {
$destination = public_path('app/lostFound/lostItems' . $lostFound->LFImage);
if( File::exists($destination) )
{
File::delete($destination);
}
$file = $request->file('LFImage');
$extension = $file->getClientOriginalExtension();
$filename = $lostFound->LFNumber . '-' . $lostFound->lostItem . '.' . $extension;
$file->move('app/lostFound/lostItems', $filename);
$lostFound->LFImage = $filename;
}
if( $request->hasFile('handoverStatement') ) {
$destination = public_path('app/lostFound/handoverStatements' . $lostFound->handoverStatement);
if( File::exists($destination) )
{
File::delete($destination);
}
$file = $request->file('handoverStatement');
$extension = $file->getClientOriginalExtension();
$filename = $lostFound->lostItem . '-' . $lostFound->LFNumber . '.' . $extension;
$file->move('app/lostFound/handoverStatements', $filename);
$lostFound->handoverStatement = $filename;
}
They're exactly the same except with the upload directory.
How can I make it as a one code block across the entire application with changeable file name and location depending on the form?
Some file names require random strings, how can I "Edit" the random string to the file that was uploaded?
Best practice when uploading and storing files in Laravel is using Storage.
It has all needed methods to work with files, you can save the file like this:
use Illuminate\Support\Facades\Storage;
Storage::put('images/', $request->file('LFImage'));
In the documentation provided above, you can find other examples like renaming and moving files
In order to access these files from web as well, you can use the command php artisan storage:link, which creates a symbolic link to storage folder in your public folder. After you create the symbolic link, you can generate URL to the file like this:
asset('storage/test.txt')
To avoid duplications, you can create a function in your controller to create a file. You will then just call this function with different files to keep the file creation code in one place.
you can simply write this
if ($request->hasFile('logo')) {
deleteImageFromDirectory(setting('logo'), "Settings");
$data['logo'] = uploadImageToDirectory( $request->logo , "Settings");
}
and define uploadImageToDirectory function in your helper functions or create a trait
function uploadImageToDirectory($imageFile, $directory = '' ){
$imageName = $imageFile->getClientOriginalName(); // Set Image name
$imageFile->storeAs("/Images/$directory", $imageName, 'public');
return $imageName;
}
I try to send Mail in a Magento CE 1.8.0.0,
I can send pictures et text files, but when i try to send pdf, it's always fail, my attachment size is 0 Ko and i can't open it ...
This is how i work :
if($filename != '')
{
$mailTemplate
->getMail()
->createAttachment(
file_get_contents(Mage::getBaseDir('tmp').'/pjcontact/'.$filename),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename($filename)
);
}
On server, the pdf file is correct.
With this code, only PDF fails ... I'm on it since this morning and i find nothing, someone had an idea ?
My suspicion is that file_get_contents returns false. Try debugging it with:
if ( $filename != '' )
{
$path = Mage::getBaseDir( 'tmp' ) . '/pjcontact/' . $filename;
Mage::log("File found in {$path}? ".(file_exists($path)?"Yes":"No").". Is it readable? ".(is_readable($path)?"Yes":"No"));
$mailTemplate
->getMail()
->createAttachment(
file_get_contents( $path ),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename( $filename )
);
}
I have an array of file paths that I need ImageMagick to run through.
But some of the files are files that are not supported by ImageMagick, aborts the loop and gives me "Uncaught exception" errors. I'd like to just skip those files and move on to the next one, but I can't find any information on this.
This is my loop:
// I'd like this section to be inclosed in a function that decides
// if Imagemagick should skip the file or do the thumbnail process
$imagick = new Imagick();
$imagick->readImage($wpdm_uploads_folder . $file);
$filename = ABSPATH.'wp-content/uploads/thumbs/';
if ( ! is_wp_error( $imagick ) ) {
if($new_file['extension'] == "psd"){
$imagick->setIteratorIndex(0);
}
$imagick->thumbnailImage(200, 0);
$imagick->writeImage($filename . $new_file['filename'] . '.png');
}
$imagick->clear();
$imagick->destroy();
Imagick::pingImage is your friend for getting information about a possible image. Ping image just looks at the image's header and meta-info, and doesn't load any actual image-data. Checkout article "to Ping, or not to Ping."
<?php
$images = array(
'built-in' => 'rose:',
'valid' => '/tmp/image.png',
'invalid' => '/tmp/server.sock',
);
$wand = new Imagick();
foreach( $images as $type => $path ) {
try {
$okay = $wand->pingImage($path);
} catch (ImagickException $error) {
$okay = FALSE;
}
if($okay) {
print $path . ' is an image' . PHP_EOL;
print $path . ' has a format of ' . $wand->getImageFormat() . PHP_EOL;
} else {
print $path . ' is NOT an image' . PHP_EOL;
}
}
outputs ...
rose: is an image
rose: has a format of PPM
/tmp/out.png is an image
/tmp/out.png has a format of PNG
/tmp/server.sock is NOT an image
Edit
If you want to know the supported image formats of the system's ImageMagick library before working with files. Imagick::queryFormats can generate a list built-in, formats, and types.
For a command line approach, my first proposal would be to use
identify -ping -format "%m\n" filename
and then check return value and output on <stdout> for the magic file type. (This is probably the very same approach #emcconville used with PHP).
However, I've not tested this on a wide range of different file formats (yet).
I'm trying to get a thumbnail to link to a PDF of the same name if the PDF exists, but to not link to anything if the PDF doesn't exist. Here's the code I have:
<?php
if ( function_exists('has_post_thumbnail') && has_post_thumbnail() ) {
$full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full') ;
$pdf = substr_replace($full_image_url , 'pdf', strrpos($full_image_url[0] , '.') +1);
$filename = $pdf[0];
if (file_exists($filename)) {
echo '<a href="' . $pdf[0] . '" title="' . the_title_attribute('echo=0') . '" . target="_blank" >';
the_post_thumbnail('Full Size');
echo '</a>';
}
else {
echo "The file $filename exists";
}
}
?>
Currently, the else statement is just to prove whether or not it's finding the file. Which it seems to, as it displays The file http://localhost/AWAD/wp-content/uploads/2012/03/+D.pdf exists. And if I get rid of the conditional, the post thumbnail displays with a link to the PDF. I just can't get the conditional to work.
Can anyone spot why it's not working?
You should pass a path on your FS to file_exists, you are passing an URL now
I'm pretty sure file_exists wants a full file path, not a URL. So, you'll probably want to use the WordPress wp_uploads_dir function to get the base path to your uploads directory and then append the rest of the path to the end of that and then pass that string to file_exists. Hopefully that makes sense.
I am making a member's management database. I want to put all the members pictures above the site root so that they wont be able to be accessed via a url but I want to show the picture of the member on the member profile. I am using php. How can I do that?! Thanks!
You could create a php file that reads the file based on some input parameters, and at the same time decide on some conditions whether the visitor is allowed to view the file.
Something like this (simplified example):
<?php
// presuming this file is in the root of your site
// define some directory where the actual images are
$dir = realpath( dirname( __FILE__ ) . '/../profile-images' );
// presuming this file is called with something like
// image.php?profileImage=fireeyedboy.jpg
if( isset( $_GET[ 'profileImage' ] ) )
{
// strip all possible redundant paths
// you should probably sanitize even more (check valid extensions etc.)
$profileImage = basename( $_GET[ 'profileImage' ] );
if( $someConditionsThatVisitorIsAllowedToViewThisImageAreMet )
{
// presuming mime type jpeg for now
header( 'Content-Type: image/jpeg' );
readfile( $dir . '/' . $profileImage );
exit();
}
else
{
// conditions are not met, dish out HTTP/1.1 403 Forbidden header
header( 'HTTP/1.1 403 Forbidden', true );
exit();
}
}