I'm trying to copy an image using the path which is stored in my DB. I tried this but it throws "Array To String Conversion" error. I've never dealt with this before. Here's my code.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));
You're attempting to convert an array from explode('.', $img_name); to a string in the final line.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = explode('.', $img_name); // This is an array like ['image_name', 'ext]
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext[count($ext)-1])
); // You'll need to address the last item in the array by its index like this
That said, pathinfo(...) is the safer option here.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
Storage::disk('local')->copy(
public_path($record->image),
public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext
);
I think its a simple problem of using explode as it will return an array of strings based on the dividing parameter.
I'm not too savvy with OOP but I can suggest using str_replace or trim to remove the '.'s in the $img_name variable.
$record = AboutPageIntro::find($id);
$img_name = $record->image;
$ext = str_replace('.',"",$img_name);
Storage::disk('local')->copy(public_path($record->image), public_path('uploads/about_page/intro/' . uniqid() . '.' . $ext));
Related
I have my upload php code where my intent is , obtained file from $_files,
add a random number between 0 and 9999 to the name of image like this:
image sent : image.jpg
before saving : image321.jpg
the image is saved in my upload folder but the filename are like
"php2983204tmp"
if ($file !== null) {
$rand = rand(0000,9999);
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);
any ideas to fix?
The filename in your example is php and your extension is tmp. None of them have the . that you are missing.
You need to add the dot . as a string after the $file_name and $rand, before the $extension like this:
$file->move($path, $file_name.$rand. "." .$extension);
TIME is always unique identity, use it as below (maybe helpful):
if ($file !== null) {
$rand = rand(0000,9999).time();
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);
You need add in the desired chars to the actual string.
$file->move($path, $file_name.$rand.".".$extension);
But I have to say, I am against how you've done this, you don't even check if the "newly" created string already exists in the directory. Its better to hash the time of upload with the original filename, rename the file to the new hash and use a database to point to the file as this way the filename collisions don't occur.
$fn = md5(microtime(true) . $extension . $file_name);
$file->move($path, $fn);
I am slowly working on a image uploader, and wondering why when echoing my renamed files, its giving me a single character instead of the whole thing.
Any reason it would be doing that?
It does tho, successfully upload the image as a phil_546d196082606.jpg with a different number for each image
Here is my code
<?php
if (isset($_POST['addpart'])) {
$image = $_FILES['images']['tmp_name'];
$name = $_POST['username'];
$i = 0;
foreach ($image as $key) {
$fileData = pathinfo(basename($_FILES["images"]["name"][$i]));
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . $fileName);
copy("image/" . $fileName, "image_thumbnail/" . $fileName);
$i++;
}
echo 'Uploaded<br>';
$fileName1 = $fileName[0];
$fileName2 = $fileName[1];
$fileName3 = $fileName[2];
echo 'Main Image - '.$fileName1.'<br>';
echo 'Extra Image 1 - '.$fileName2.'<br>';
echo 'Extra Image 2 - '.$fileName3.'<br>';
echo '<hr>';
}
?>
$filename is a string and strings in php are arrays where each letter has an index $filename[o] is the first letter and so on.Use
$filename[]=$name .'_'. uniqid() . '.' . $fileData['extension'];
Try the below block of code
$fileName[] = $name .'_'. uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . end($fileName));
copy("image/" . end($fileName), "image_thumbnail/" . end($fileName));
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
Filename is the string. It is : $name . number.
Like philip12345.
So if we have:
philip
012345
$fileName[0] = p
$fileName[1] = h
Also you overwrite filename in each loop. Try to save it to an array and print it, here is some code:
$fileNames = array();
foreach ($image as $key)
{
$fileName = $name .'_'. uniqid() . '.' . $fileData['extension'];
fileNames[$i] = $fileName;
}
echo $fileNames[0];
echo $fileNames[1];
echo $fileNames[2];
You could also use a foreach loop to go over the array with the filenames and print each element, this is cool because it will works with any number of images, not just 3:
foreach ($fileNames AS $key2)
{
echo ($key2);
}
I'm trying to rename the input file to be a .jpg after conversion, but for some reason I'm getting a file.png.jpg when I'm really looking for file.jpg
Here is my code:
$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";
Use pathinfo():
$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$path_parts = pathinfo( $_FILES['t1']['name'] );
$destination = $path . $_POST['username']. "-" . $path_parts['filename'] . ".jpg";
Let's say that the variable $filename contains your image name with the png extension.
In order to change the extension to jpg , simply run it through this function :
function replace_extension($filename) {
return preg_replace('/\..+$/', '.' . '.jpg', $filename);
}
The basename() function includes the original files extension
Use the pathinfo() function to return an array of informatino about the file and use the filename with out the extension
Replace
$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";
with
$info = pathinfo($_FILES['t1']['name']);
$destination = $path . $_POST['username']. "-" . $info['filename'] . ".jpg";
You can either use the second parameter to basename to kill the suffix
$filename = basename($_FILES['t1']['name'], ".png");
or you could do some string manipulation
$filename = substr($_FILES['t1']['name],0, strrpos($_FILES['t1']['name'], ".") -1);
basename returns you the whole filename, including the file type suffix (i.e. ".jpg"). If you want to strip the suffix, you can call the function with a second parameter: basename($_FILES['t1']['name'], 'png').
But if you want to convert a png to a jpg, you can't just change the filename, you have to convert the file using special functions, see "Use PHP to convert PNG to JPG with compression?".
<?php
require '../config.php';
// Edit upload location here
$result = 0;
$name = mysql_real_escape_string($_FILES['myfile']['name']);
$path = csv;
$ext = 'csv';
$md5 = md5($name);
$target_path = $path . '\\' . $md5 . '.' . $ext;
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
It won't upload any files such as with the file names that contain brackets, etc.
Don't do:
$name = mysql_real_escape_string($_FILES['myfile']['name']);
Do:
$name = $_FILES['myfile']['name'];
you are getting the MD5 of $name so no reason to clean it as it will produce a 32-char hex string which will not contain any special characters regardless. If a filename contains special chars and you escape using the above the MD5 will completely change.
The error is likely here:
$path = csv;
Here PHP is looking for a constant with name csv unless you have defined that, it is going to return null, so your $target_path is not being built correctly.
Just one more thing to try is use the pre defined DIRECTORY_SEPERATOR constant while building your $target path so...
$target_path = $path . DIRECTORY_SEPERATOR . $md5 . '.' . $ext;
Say the image is called:gecko.jpg
Can I first remove ".jpg" and add "-100x100" after "gecko", and then put the extension back, so it would be "gecko-100x100.jpg"?
use pathinfo
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
$new = $path_parts['filename'] . '-100x100.' .$path_parts['extension'];
Yes, quite simply with PHP's string functions in conjunction with basename()
$base = basename($filename, ".jpg");
echo $base . "-100x100" . ".jpg";
Or to do it with any filetype using strrpos() to locate the extension by finding the last .
// Use strrpos() & substr() to get the file extension
$ext = substr($filename, strrpos($filename, "."));
// Then stitch it together with the new string and file's basename
$newfilename = basename($filename, $ext) . "-100x100" . $ext;
--
// Some examples in action...
$filename = "somefile.jpg";
$ext = substr($filename, strrpos($filename, "."));
$newfilename = basename($filename, $ext) . "-100x100" . $ext;
echo $newfilename;
// outputs somefile-100x100.jpg
// Same thing with a .gif
$filename = "somefile.gif";
// outputs somefile-100x100.gif