I now there are lots of same questions here, but I didn't find my answer.
I want to upload an image using move_uploaded_file() function in PHP. Here is my logic?
//check if file uploaded
if (!isset($_POST) || !isset($_FILES)) {
return back();
}
// allowed extensions
$extensions = ['jpg', 'jpeg', 'gif', 'png'];
$fileName = pathinfo($_FILES['profile-image']['name'], PATHINFO_FILENAME);
// save file extension into a variable for later use
$parts = explode('.',$_FILES['profile-image']['name']);
$extension = strtolower(end($parts));
$fileSize = $_FILES['profile-image']['size'];
// check the extension
if (!in_array($extension, $extensions)) {
return back()->withErrors(['File Extension is not valid']);
}
// check if file size is less than 2MB
if ($fileSize >= 2e+6) {
return back()->withErrors(['File Size is too large.']);
}
//check if there is other errors
if ($_FILES['profile-image']['error']) {
return back()->withErrors(['You have anonymus error']);
}
// generate a unique file name
$profile_image = Hash::make($fileName) . '-' . time() . '.' . $extension;
// make a directory if there isn't one
if (!is_dir('public/img')) {
mkdir('public/img');
}
// if current user has an image then delete it
$user = App::get('database')->find('users', compact('id'));
if ($user->profile_image) {
unlink('public/img/' . $user->profile_image);
}
// move image into directory and final check for errors
if( ! move_uploaded_file($_FILES['profile-image']['tmp_name'], 'public/img/' . $profile_image) ) {
return back()->withErrors(['Your file doesn\'t uploaded']);
}
// Insert Uploaded Image into DB.
App::get('database')->update('users', compact('id'), compact('profile_image'));
return redirect('dashboard')->withMessage('Thank for uploading the file.');
I try this code, everything works properly but just sometimes. I don't know why sometimes my uploaded file doesn't move to the directory and sometimes it does. I tried for the same image, sometimes it uploaded and sometimes it failed. This is interesting, because when I upload an image and it fails, can't catch any errors at all.
Did you check max_file_uploads and post_max_size in your php.ini file ?
Maybe the file is bigger than the maximum size allowed.
Regards.
OK, I find the problem. When I hash the image name and save it to DB, sometimes it includes / inside file name, then when I use the file name in image src attribute, it considers the part before the / as another directory.
It might have trouble with,
Your Destination Directory have some writing permission issue.
Try this for manage file permission,
if (!is_writable($url)) {
try {
chmod($url, 0644);
} catch (Exception $e) {
die($e->getMessage() . ' | File : ' . $url . ' | Needs write permission [0644] to process !');
}
}
All the Best !
Related
I am having some trouble uploading images to my blog, every time I try summiting the form it returns 'Failed to upload image :'. I can’t figure out the problem
if (!empty($_FILES['image']['name'])) {
$image_name = time() . '_' . $_FILES['image']['name'];
$destination = ROOT_PATH . "/assets/images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result) {
$_POST['image'] = $image_name;
}else {
array_push($errors, 'Failed to upload image :');
}
}else {
array_push($errors, 'Image is required!');
}
If move_uploaded_file $_FILES['image']['tmp_name'] is not a valid upload file, then no action will occur, and move_uploaded_file() will return false.
If $_FILES['image']['tmp_name'] is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return false. Additionally, a warning will be issued.
Make sure that the file is not empty.
Second: make sure the file name in English characters, numbers and (_-.) symbols, For more protection.
Third: Maybe the file is too big. Check the file size and also check php.ini for max_upload_size. Also check $_FILES["image"]["error"] to see what is the real error.
Thanks for the feedback
When using mac insure that the destination folder has read and writing permissions for other users.
I have a function which checks if image files exist. It works for all images, except when a period is inside the filename. The filenames are user uploaded, and many already exist that are not sanitized. Here is an example:
$img = 'nice_name.jpg'; // detects
$img = 'bad_name.7.jpg'; // doesn't detect
if (is_file($path . $img)) {
return $path . $prefix . $img;
}
I'm not sure how to escape this or make it work. I have doubled checked and the file does exist at that path. The function works for other image names in the same folder.
edit: This was marked a duplicate and linked to a question about uploading files. I am using is_file() to check if a file already exists. There is no uploading occurring, and the file already has the extra "." in its name on the server, so this is a different issue.
You can use basename() to get the file name, and then do something with it, like rename it if it contains a period.
$testfile = "test.7.img";
$extension = ".img";
$filename = basename($testfile, $extension);
if(strpos($filename,".") > 0) {
$newname = str_replace(".","",$filename) . $extension ;
rename($testfile,$newname);
}
//... then continue on with your code
after uploading prestashop from my localhost to the server , a problem showed up
when trying to upload product image i got this error "Server file size is different from local file size"
after searching in prestashop files i found that is uploader class is responsible for the upload process.
public function upload($file, $dest = null)
{
if ($this->validate($file))
{
if (isset($dest) && is_dir($dest))
$file_path = $dest;
else
$file_path = $this->getFilePath(isset($dest) ? $dest : $file['name']);
if ($file['tmp_name'] && is_uploaded_file($file['tmp_name'] ))
move_uploaded_file($file['tmp_name'] , $file_path);
else
// Non-multipart uploads (PUT method support)
file_put_contents($file_path, fopen('php://input', 'r'));
$file_size = $this->_getFileSize($file_path, true);
if ($file_size === $file['size'])
{
$file['save_path'] = $file_path;
}
else
{
$file['size'] = $file_size;
unlink($file_path);
$file['error'] = Tools::displayError('Server file size is different from local file size');
}
}
return $file;
}
when commenting if statement witch responsible of comparing file size and tring to upload an image i got this error
"An error occurred while copying image, the file does not exist anymore."
i changed img folder permissions to 777 still same problem ?
Its a permission issue. I resolved it by giving complete access (777) to cache and theme folders.
If that doesn't help then try giving complete access to all the files. Be sure to change back the permission to 755 for folders and 644 for files for security reasons.
please change " if ($file_size === $file['size']) " to " if ($file_size = $file['size']) "
This method worked for me.
Hey i have a system were in uploading a file. I have a script I've found online and it seems to work well.
Here is the PHP code:
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
{
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000))
{
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname))
{
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
echo "It's done! The file has been saved as: ".$newname;
}
else
{
echo "Error: A problem occurred during file upload!";
}
}
else
{
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
}
else
{
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
}
else
{
echo "Error: No file uploaded";
}
No this works fine if i want to upload a jpg file. But i want to be able to put the file into another directory. because at the moment the upload page is for admin users, they are on a subdomain called admin.mysite.com but the location i want the file to go to is in the members section which is mysite.com/members/video/
Now there are a few bits of code that im not 100% with like "dirname(FILE)" what does this do? I guessed it would get the current locations, but i've changed the whole line where so it looks like this:
$newname = '../mysite.com/members/video/'.$filename;
and
$newname = 'http://www.mysite.com/members/video/'.$filename;
But nothing. Anyone know how i can change this code so i can copy the file to a new directory?
Thanks for the help.
Change $newname to whatever location you want!
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
dirname(_ FILE _) returns the current directory of the file, in this case, file_upload.php
So, in this script, the $newname will save the uploaded file to /upload/name_of_new_file_uploaded.ext.
You should try to use realpath() instead dirname. Like this:
$newname = realpath("../../members/video/") . $filename;
depending on you file structure, add/remove the dots.
PS: Remember to change folder permissions, so the php can write on a folder.
For security, you should
Put the file in a location that is not accessible by the general web. /home/uploadedfiles/
Change the name of the file. Store the name of that file in a database and don't let the end users see that actual name.
I'm using the Uploadify jQuery plugin for PHP to upload a file. One thing I am stuck on is that I need to be able to rename the file being uploaded so that I can post that information to my script that inserts data into the mysql database. Can anyone please advise on how to do this?
Thanks,
Jake
Firstly rename the filename as you want in your uploadify.php
Then you just need to return $targetPath from your uploadify.php file, like this --
echo $targetPath
no need to use echo '1'
And now you have to get the renamed file name. You can get this in onUploadSuccess function.
onUploadSuccess() takes three parameters (file, data, response),
where file gives you the actual name of file you browsed through your computer, and data gives you the renamed file name which you generated through your uploadify.php code as per your requirement.
So you can try the below code --
'onUploadSuccess' : function(file, data, response) {
alert('Renamed file name is - ' + data);
}
I hope this will help out. One of my friend told me this, and I got my work done then :)
you can do like this :-
$targetFolder = FCPATH.'/resources/images/users/temp/'; // Relative to the root
if (!empty($image))
{
$time=strtotime("now");
$image['Filedata']['name']=$time.'.jpg';
$tempFile = $image['Filedata']['tmp_name'];
$targetPath = $targetFolder.$image['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($image['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes))
{
move_uploaded_file($tempFile,$targetPath);
echo '1';
}
else
{
echo 'Invalid file type.';
}
}
If you use uploadify.php just go right before the function move_uploaded_files and change the target name.
Anyways you do it this should work. Post the code you have if you want a more detailed answer.
This will put file in new folder with same file name as source file
$source = $_FILES['Filedata']['tmp_name'];
$filename = $_FILES['Filedata']['name'];
$newPath = $folder.'/'.$filename;
rename($source, $newPath);
/*----------------------*/
to have a new filename
function getExtension($path)
{
$result = substr(strtolower(strrchr($path, '.')), 1);
$result = preg_replace('/^([a-zA-Z]+)[^a-zA-Z].*/', '$1', $result);
if ($result === 'jpeg' || empty($result) === true) {
$result = 'jpg';
}
return $result;
}
$source = $_FILES['Filedata']['tmp_name'];
$filename = $_FILES['Filedata']['name'];
$newfileName=$folder."/"."abc".getExtension($filename);
rename($source, $newfileName);