For example I have function named test in which I do some stuff with image. I want to be able detect if in it was passed the image or only the path to it. For example:
function test($image) {
// here I need to detec if $image is path or loaded image
}
test('/home/name/image.jpg');
test(file_get_contents('/home/name/image.jpg'));
Assuming you have these sanitized:
if (file_exists($image)) {
// path
} else {
// image
}
Probably you’ll want to check whether an image is the proper image using some image handling library in the else clause.
Use getimagesize($image);. If it has a width and height, it's an image.See http://php.net/manual/en/function.getimagesize.php for full info.
$image_size = getimagesize($image);
$image_size[0] > 0 ? /*It's an image*/ : /*It's not*/;
Try this
function test($image) {
if($image=='')
{
return false;
}
if(file_exists($image))
{
echo "file exists";
}
else
{
echo "path is passed to the function";
}
}
test('/home/name/image.jpg');
test(file_get_contents('/home/name/image.jpg'));
you can use is_file for this
Tells whether the given file is a regular file.
Related
I'm facing a problem.
I have actually this code:
// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';
if(file_exists($src)) {
$src = $src;
}
else {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';
This code check for an image existence.
But each time I have the fallback image default.jpg whereas I should have 007.jpg.
I check my path and it works. My 007.jpg image is into the same directory as my default.jpg image.
I already test with if(#getimagesize($src)) { ... }. The same.
Why ?
Even that your file is placed at some directory, doesn't mean that the current path of the PHP process is the same. Use the absolute path instead:
// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';
if(!file_exists(__DIR__.'/'.$src)) {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';
I think you are over doing it make it simpler might solve your issue Try This:
<?php
$src = '../assets/app/images/hotel-logos/007.jpg';
if (!file_exists($src)) {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';
?>
Ok, I get it working by using:
$_SERVER['DOCUMENT_ROOT']
// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';
if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/assets/app/images/hotel-logos/007.jpg')) {
$src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';
I'm trying to make a upload class with PHP. so this is my first PHP class:
//Create Class
class Upload{
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
if(copy($Content, '/test/sdfsdfd.jpg')){
return "UPLOADED";
}else{
return "ERROR";
}
}
}
and usage:
$Upload = new Upload();
echo $Upload->Remote('https://www.gstatic.com/webp/gallery/4.sm.jpg');
problem is, this class is not working. where is the problem? I'm new with PHP classes and trying to learn it.
thank you.
copy expects filesystem paths, e.g.
copy('/path/to/source', '/path/to/destination');
You're passing in the literal image you fetched, so it's going to be
copy('massive pile of binary garbage that will be treated as a filename', '/path/to/destination');
You want
file_put_contents('/test/sdfsdfg.jpg', $Content);
instead.
PHP's copy() function is used for copying files that you have permission to copy.
Since you're getting the contents of the file first, you could use fwrite().
<?php
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
// Create the file
if (!$fp = fopen('img.png', 'w')) {
echo "Failed to create image file.";
}
// Add the contents
if (fwrite($fp, $Content) === false) {
echo "Failed to write image file contents.";
}
fclose($fp);
}
Since you want to download a image, you could also use the imagejpeg-method of php to ensure you do not end up with any corrupted file format afterwards (http://de2.php.net/manual/en/function.imagejpeg.php):
download the target as "String"
create a image resource out of it.
save it as jpeg, using the proper method:
inside your method:
$content = file_get_contents($Image);
$img = imagecreatefromstring($content);
return imagejpeg($img, "Path/to/targetFile");
In order to have file_get_contents working correctly you need to ensure that allow_url_fopen is set to 1 in your php ini: http://php.net/manual/en/filesystem.configuration.php
Most managed hosters disable this by default. Either contact the support therefore or if they will not enable allow_url_fopen, you need to use another attempt, for example using cURL for file download. http://php.net/manual/en/book.curl.php
U can use the following snippet to check whether its enabled or not:
if ( ini_get('allow_url_fopen') ) {
echo "Enabled";
} else{
echo "Disabled";
}
What you describe is more download (to the server) then upload. stream_copy_to_stream.
class Remote
{
public static function download($in, $out)
{
$src = fopen($in, "r");
if (!$src) {
return 0;
}
$dest = fopen($out, "w");
if (!$dest) {
return 0;
}
$bytes = stream_copy_to_stream($src, $dest);
fclose($src); fclose($dest);
return $bytes;
}
}
$remote = 'https://www.gstatic.com/webp/gallery/4.sm.jpg';
$local = __DIR__ . '/test/sdfsdfd.jpg';
echo (Remote::download($remote, $local) > 0 ? "OK" : "ERROR");
I have this code which uploads an image from admin and it works well.
add_action('admin_init', 'register_and_build_fields');
function register_and_build_fields() {
register_setting('theme_options', 'theme_options', 'validate_setting', 'delete_file');
}
function validate_setting($theme_options) {
$keys = array_keys($_FILES); $i = 0; foreach ( $_FILES as $image ) {
// if a files was upload
if ($image['size']) {
// if it is an image
if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) { $override = array('test_form' => false);
$options = get_option('theme_options'); echo "<img src='{$options['logo']}' />";
// save the file, and store an array, containing its location in $file
$file = wp_handle_upload( $image, $override ); $theme_options[$keys[$i]] = $file['url']; } else {
// Not an image.
$options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$logo];
// Die and let the user know that they made a mistake.
wp_die('No image was uploaded or invalid format.<br>Supported formats: jpg, jpeg, png, gif.<br> Go <button onclick="history.back()">Back</button> and try again.'); } } // Else, the user didn't upload a file.
// Retain the image that's already on file.
else { $options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$keys[$i]]; } $i++; }
return $theme_options;
}
and now I want the function to delete the current image.
function delete_file($theme_options) {
if (array_key_exists('delete_file', $_FILES)) {
$image = $_FILES['delete_file'];
if (file_exists($image)) {
unlink($image);
echo 'File '.$image.' has been deleted';
} else {
echo 'Could not delete '.$image.', file does not exist';
}
}
}
I added the button in admin but is doing.. nothing.
I'm building a TemplateOptions in WordPress and now I'm trying to make the logo function to be uploaded and deleted from admin. Like I said, uploading the logo works and now I want to make the field "delete" to work.
I found out that you don't need to insert the record in the DB as you only have a single image and whose name and path are also constant . So you simply need to unlink the image from the directory and it will be deleted, nothing else.
say your logo.png is in your themes's img folder then you should unlink it like this. default is your theme name
$path = ABSPATH.'wp-content/themes/default/img/logo.png';
if(file_exists($path))
{
unlink( $path );
}
Note: Remember that you have to pass the absolute path to the unlink() and not the url having http , because it will give you an error , you can't use http with unlink.
I could of course check mime types through the exif_imagetype or getimagesize and check mime types one by one... But I just want ANY image - I dont care what type... So I was wondering - can I do something like this: ?
// PHP manual says: Determine the type of an image
// and that Imagetype Constants are 1-17 so :
$tmp_imagetype = exif_imagetype('image.gif');
if ( ($tmp_imagetype>=1) && ($tmp_imagetype<=17) ) {
echo "It is an image!";
} else{
echo "It isn't an image.";
}
Can I rely on that?
What happens when the file is not an image? Will it just return non-image constant value or will it throw a warning or error
Thanks
You really don't need all that you just need the following as exif_imagetype returns false if its not an image
if($imagetype = exif_imagetype('image.gif')){
// its an image
} else {
// its not an image
}
You could check if the function returns (exactly) FALSE:
$file="SOMEFILE";
if(exif_imagetype($file)===FALSE){
print("NOT IMAGE");
}else{
print("IMAGE");
}
Why don't you just put all types of images in an array and then check it with this code:
if(in_array($value, $array)) {
//it's an image! Hooray!
}else {
//it's not.
}
I want to copy some images from one folder to another, I do not want to copy them all.
Here is my code but it give me an issue failed to open stream
$image = "a.jpg";
$srcfile='uploads/listings/my_from/'.$image;
$dstfile='uploads/listings/my_to/images/';
copy($srcfile, $dstfile);
What am I missing? Can I do anyhting else so that I can copy selected images to destination without deleting it?
Note: both of these folders are on the same server and same project. Should I do it by curl?
It might pay to do some error checking as well, but you just need to add the full image path to your $dstfile variable:
<?php
$image = "a.jpg";
$srcfile='uploads/listings/my_from/'.$image;
$dstfile='uploads/listings/my_to/images/'.$image;
echo 'Attempting to copy "'.$srcfile.'" to "'.$dstfile.'"<br />';
if(file_exists($srcfile)) {
if(file_exists($dstfile)) {
echo 'Cannot copy file, destination file already exists';
} else {
if(is_writable(dirname($dstfile))) {
if(copy($srcfile,$dstfile)) {
echo 'File successfully copied';
} else {
echo 'File could not be copied';
}
} else {
echo 'Destination is not writable';
}
}
} else {
echo 'Cannot copy file, source file doesnt exist';
}
?>
if you are sure that file a.jpg exists, then this should work
$srcfile='uploads/listings/my_from/'.$image;
$dstfile='uploads/listings/my_to/images/'.$image;
copy($srcfile, $dstfile);
note: destination file name must be specified.
You should check it exists really.
try:
$image = "a.jpg";
$srcfile='uploads/listings/my_from/'. $image;
$dstfile='uploads/listings/my_to/images/' . $image;
if(!file_exists($srcfile) {
throw new \Exception("File does not exist!");
}
copy($srcfile, $dstfile);