Remove file extension on file upload - php

I'm writing the code for a website right now that's uploads images and then displays them gallery style. What I would like to happen is for the file name of the image to be entered into the site's database as the name of the image. However, just using $_FILES['images']['name']; gives me the file name but with the file extension attached at the end. How would I remove the file extension so I can use the file name by itself?

You can use the pathinfo() function (docs).
$example = "my_file.jpeg";
$filename = pathinfo($example, PATHINFO_FILENAME);
echo $filename; // my_file

Just use preg_replace:
$name = preg_replace('/(.+)\.\w+$/U', $_FILES['images']['name'], '$1');

You can use rename to remove the extension:
-> http://www.php.net/manual/en/function.rename.php

As my comment above implies, it depends on what you consider in the filename to be the name and what is the extension.
everything up to the last dot:
$filename = 'some.file.name.zip';
$name = substr($filename, 0, strrpos($filename, '.'));
everything up to the first dot:
$filename = 'some.file.name.zip';
$name = substr($filename, 0, strpos($filename, '.'));
they look the same, but the first one looks for the first dot from the end of the string and the second one from the start of the string.

Related

Search and replace str inside jpg file data by php

I want a way to search and replace strings inside jpg or ttf files by PHP and resave them!
Ttf : change font family name or something
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
for an e.g
Let's say you want to replace the file name having index to ttf
echo str_replace("index","ttf",$file);
You can find and replace according to your needs.

Duplicating an image from a file path, changing name and saving it to a different table in laravel

I have a file path on a table, what I am trying to do is create the image from the file path and then save the 'new' file with a different name.
Because I have only the file path, I do not now how to create the image object so that I can then getClientOriginalExtension(); and save that to the database. I have tried the following:
$img = $var->image_path;
$file = file_get_contents($img);
$filename = time() . '.' . $file->getExtension();
Image::make($file)->resize(300, 300)->save( public_path('/test' . $filename ) );
However the script errors: Call to a member function getExtension() on string what would be the right way with the file path, create the object, change the name of the file, ensure the right extension is set (maybe outside scope of this q) and then save the newly created image to a different folder and save the newly created image path to the database.
I hope that makes sense.
Update: should I use file_put_contents() instead?
Achieved what I wanted using the copy() and iterating over each image and adjusting the image relatively.
$title = $var->name;
$string = str_replace(' ', '-', $title); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
copy($img, public_path('/test' . $string . time()));
http://php.net/manual/en/function.copy.php

How do I rename a filename before uploading with php

I need to upload two files with different ext example :
file_1.txt and file_image.png
when the user sent the two files using upload an form :
file_1.txt and file_image.png
before move_uploaded_file I need to rename the image name to be like the txt. name file :
file_1.txt
file_1.jpeg
I just want to rename the image filename, not the extension
Code is something like this :
switch($_REQUEST['action']) {
case "upload":
$Imagefile_temp = $_FILES['file']['tmp_name'];
$Textfile_temp = $_FILES['file']['tmp_name'];
$Imagefile_name = $_FILES['file']['name'];
$Textfile_name = $_FILES['file']['name'];
$ImageFileType = array('png' ,'jpg');
$TextFileType = array('txt');
$Image_extension = pathinfo($Imagefile_name, PATHINFO_EXTENSION); // holds the file extension of the file
$Text_extension = pathinfo($Textfile_name, PATHINFO_EXTENSION); //holds the file extension of the file
// //Declaring Path for uploaded images
$file_path = "uploads";
//checks for duplicate files
if((!file_exists($file_path."/".$Imagefile_name)) || (!file_exists($file_path."/".$Textfile_name))) {
$j = 0; //Variable for indexing uploaded image
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
if(in_array($Image_extension,$ImageFileType) ) {
$Image_extension = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($Image_extension); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $Image_extension[count($Image_extension) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
$Imagefilestatus = move_uploaded_file($Imagefile_temp,$file_path."/"."image_".$Imagefile_name) ;//if file moved to uploads folder
}
if(in_array($Text_extension,$TextFileType) ) {
$Text_extension = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($Text_extension); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $Text_extension[count($Text_extension) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
$Textfilestatus = move_uploaded_file($Textfile_temp,$file_path."/".$Textfile_name) ;//if file moved to uploads folder
}
}
}
}
$name = 'Whatevernameyouwant.'.pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
pathinfo with parameter PATHINFO_EXTENSION returns the file extension.
You can just explode the text file from the extension and use it as the image file name when moving it :
$text_file_name = $_FILES["text"]["name"]; // give you the text file name
$image_file_name = $_FILES["image"]["name"]; // give you the image file name
$file_expensions = strtolower(end(explode(".", $image_file_name))); // give you the image extension and so you can use it later for saving the file
$n = explode(".", $text_file_name, 1);
$name = $n[0]; // get text file name
$name = $name.".".$file_expensions; // this is new name of the image
move_uploaded_file($file_tmp, "path/$name")
I assume you are aware that the code you've presented here allows anyone with upload privileges to upload and execute PHP code.
(the reason I mention this is that there is scope for a lot of improvement elsewhere - and if the security vulnerability is exploitable then you should really think about start again from scratch with this).
Will your extension always be .jpg or .png ? (what about .jpeg ?)
I need to rename the image name to be like the txt. name file
I presume you mean that you want the filename on the retained image file to match that of the txt file - you can specify the destination name in move_uploaded_file(). Breaking down a process into steps is a good idea for managing complexity but file operations are expensive and here redundant.
So really you want to know how to get the a filename without an extension then add the file extension from a different file.
You already have the extension you want to apply in $Image_extension
While you could just do....
$destination_name=$destination_path
. str_replace('.txt', '.' . $image_extension, $Textfile_name);
However this will not work as expected if $imageFile_name contains more than one instance of '.txt'.
You could use PCREs to specify that you should only apply the change to the end of the string:
$destination_name=preg_replace("/txt$/i", $image_extension, $Textfile_name);
Or take the last 4 characters off $Textfile_name then append the image extension.
$destination_name=substr($Textfile_name, 0, -3) . $image_extension;
Or strrev the text file name, replace 'txt' with strrev($image_extension) with a limit of 1, then strrev the result to ensure only the end of the string is replaced.
If I spent more time thinking about this, there are probably other solutions too - but they will become increasingly esoteric.
In general, allowing users to pick their own names (or even part thereof) for content uploaded inside the document root is a bad idea.

Get $_FILES temp name (of the binary file)

i'm in trouble this is an example of $_FILES['file']['tmp_name']
/Applications/XAMPP/xamppfiles/temp/phpjCag18
i would like to get the temp binary filename so in this case phpjCag18
Is there anyway to get it from the $_FILES[]?
Ho to get it clean from path ?
You can use basename() for this purpose.
$tmp = $_FILES['file']['tmp_name'];
echo basename( $tmp );
Or, if you're trying to get the extension, use pathinfo():
$extension = strtolower( pathinfo($_FILES['file']['tmp_name'], PATHINFO_EXTENSION) );
If I understand you correctly:
basename($_FILES['file']['tmp_name'])

Determine file extension of an image that is missing an extension

I have some images on my system that were saved without a file extension, they appear in the format of "FILENAME." (Note the period)
I am trying to use getimagesize(); but it is erroring out telling me that "Filename cannot be empty"
Here is a sample of the code I am using
$contents = file_get_contents($localFile);
$imageData = getimagesize($contents);
// $imageData[2] will contain the value of one of the constants
$mimeType = image_type_to_mime_type($imageData[2]);
$extension = image_type_to_extension($imageData[2]);
Look at the documentation: http://php.net/getimagesize
getimagesize() is expecting a filename as first parameter, not the contents of the image file.
Try:
$imageData = getimagesize($localFile);
// $imageData[2] will contain the value of one of the constants
$mimeType = image_type_to_mime_type($imageData[2]);
$extension = image_type_to_extension($imageData[2]);
getimagesize expects a file name as the first argument

Categories