While loading the photo using the code
if (file_exists($DocRoot. $_FILES["file"]["name"]))
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source
path of the file in a variable
$image_name = $_SESSION['d'];
$targetPath = $DocRoot.$image_name; // Target path where
file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
}else{
$sourcePath = $_FILES['file']['tmp_name'];
$image_name = $_SESSION['d'];
// Storing source path of the file in a variable
$targetPath = $DocRoot.$image_name; // Target path where
file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded
file
the following error occurs:
Array ( [type] => 2 [message] => move_uploaded_file(): Unable to move '/tmp/phpihV9Ar' to '/var/www/html/test963853/q1/cas/upload/4442910001.jpg' [file] => /var/www/html/test963853/q1/cas/stage1_1.php [line] => 1960 ) /var/www/html/test963853/q1/cas/upload/4442910001.jpg
Experts state that there would be some problem with httpd.conf. What modification must be carried out in httpd.conf? Please suggest. Thank you in advance.
Related
I am using code below to upload image via drag an drop system. Everything is ok, JS part is working well. But PHP part of code shows me error:
PHP Warning: move_uploaded_file(assets/img/photos/1657614494809.jpg): failed to open stream: No such file or directory in /www_root/_inc/upload.php on line 29, referer: https://smartobchod.sk/bazar/add.php
[Sat Jul 23 12:56:18 2022] [error] [client 78.99.32.1] PHP Warning: move_uploaded_file(): Unable to move '/home/gm016900/tmp/phpKaBL6m' to 'assets/img/photos/1657614494809.jpg' in /www_root/_inc/upload.php on line 29, referer: https://smartobchod.sk/bazar/add.php
EDITED 25.07.2022 (added some security checks)
My PHP code in upload.php is:
<?php
// Get reference to uploaded image
$image_file = $_FILES["file"];
// Get image name
$image_name = $_FILES["file"]["name"];
// Get file size
$image_size = $_FILES["file"]["size"];
// Exit if no file uploaded or image name contains unvalid characters /, \\
if ( ( !strpos($image_name, '/') || !strpos($image_name, '\\') ) && isset($image_file) ) {
$errors = array();
$maxsize = 10485760;
$acceptable = array(
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
} else {
die('No image uploaded.');
}
// Exit if image file is zero bytes or if image size is more then 10 MB
if (getimagesize($image_file["tmp_name"]) <= 0) {
die('Uploaded file has no contents.');
} elseif ($image_size >= $maxsize) {
die('Image is too large. Image must be less than 10 megabytes.');
}
// Exit if is not a valid image file or image has not supported type
$image_type = exif_imagetype($image_file["tmp_name"]);
if (!$image_type) {
die('Uploaded file is not an image.');
} elseif ( !in_array($image_file["type"], $acceptable) ) {
die('Image has not supported type JPG, PNG, GIF.');
} else {
$src = "default.png";
}
// Get file extension based on file type, to prepend a dot we pass true as the second parameter
$image_extension = image_type_to_extension($image_type, true);
// Create a unique image name
$image_name = bin2hex(random_bytes(16)) . $image_extension;
// Location
$relative_location = "/bazar/assets/img/photos/".$image_name;
$absolute_location = dirname(__DIR__, 2).$relative_location;
$return_arr = array();
// transfer file created in tmp folder to location of pictures with name saved in address of $location
// in $image_file is stored $_FILES["file"]["tmp_name"]
if (move_uploaded_file($image_file["tmp_name"], $absolute_location)) {
$src = $relative_location;
$return_arr = array("name" => $image_name,"size" => $image_size, "src"=> $src);
}
echo json_encode($return_arr);
This is sent in header to upload.php:
Content-Disposition: form-data; name="file"; filename="1657614494809.jpg"
Content-Type: image/jpeg
Can you advice me what can be problem?
Here I think your tmp/ folder permission is not proper so it is not able to read that folder or write just check /home/gm016900/tmp permission is should be gm016900 or it may not be created.
Based on your comments, you just need to keep track of relative vs absolute paths.
I wasn't able to test this code, but hopefully you should get the general gist if it fails. Instead of a single $location variable, I'm using two variables $relativeLocation and $absoluteLocation. The latter isn't actually needed, but it makes debugging much easier.
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Getting File size */
$filesize = $_FILES['file']['size'];
/* Location */
$relativeLocation = "assets/img/photos/".$filename;
$absoluteLocation = __DIR__.'/'.$relativeLocation;
$return_arr = array();
/* Upload file */
if (move_uploaded_file($_FILES['file']['tmp_name'], $absoluteLocation)) {
$src = "default.png";
// checking file is image or not
if (is_array(getimagesize($absoluteLocation))) {
$src = $relativeLocation;
}
$return_arr = array("name" => $filename, "size" => $filesize, "src" => $src);
}
echo json_encode($return_arr);
Depending on where your function lives relative to the storage, you might need to go update a directory or two, or possibly go up and then back down:
// Up one directory
$absoluteLocation = dirname(__DIR__).'/'.$relativeLocation;
// Up two directories
$absoluteLocation = dirname(__DIR__, 2).'/'.$relativeLocation;
// Up one directory then over to a sibling directory
$absoluteLocation = dirname(__DIR__).'/files/'.$relativeLocation;
As a personal preference, I always have a constant (or equivalent) in my projects that represents a known location on disk, and if I'm using a router script I define it there. That way, no matter how deep I get in nesting I can build my paths relative to that constant.
I also go one step further and use this library (merged into Symfony here) to avoid string concatenation, not worry about whether something ends with a slash or not, and to be more cross platform. So my actual code looks like:
$absoluteLocation = Path::join(PROJECT_ROOT, 'files', $relativeLocation);
Some people might think that's overkill, but once again it is just a personal preference.
I'm trying to create a thumbnail for the image that will be uploaded to my server. Refer to https://www.codeigniter.com/userguide3/libraries/image_lib.html#processing-an-image . After the creation, I want to save the thumbnail to another folder since both the original image and the thumbnail will be saved in the same location.
So, I try using move_uploaded_file() function but it unable to move the file. I'm not really sure if my code is correctly done. Check it out.
Belwo is the my code :
if($_FILES['file_name']['size'] != 0){
$config['upload_path'] = FCPATH.MEDIA_LIB_URI.'facts';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 0;
$newFileName = removeExt($_FILES['file_name']['name']).'-'.uniqueId(); // renaming the file name without the ext
$new_name = $newFileName.getExt($_FILES['file_name']['name']); // new file name with the ext
$config['file_name'] = $new_name;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('file_name')){
$uploadData = $this->upload->data();
$file_name = $uploadData['file_name'];
$this->load->library('image_lib');
$configer = array(
'image_library' => 'gd2',
'source_image' => $uploadData['full_path'],
'create_thumb' => TRUE,
'maintain_ratio' => TRUE,
'width' => 950,
'height' => 950,
);
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
$thumbName = $newFileName.'_thumb'.getExt($_FILES['file_name']['name']); // getting the exact thumbnail name that been created by codeigniter
move_uploaded_file($thumbName, FCPATH.MEDIA_LIB_URI.'facts/thumbnail/'.$new_name);
return $file_name;
} else {
return $this->upload->display_errors();
}
}
Hope this will help you :
Use new_image in your $configer to change the folder path : $config['new_image'] = '/path/to/new_image.jpg';
Note :
If only the new image name is specified it will be placed in the same folder as the original
If only the path is specified, the new image will be placed in the destination with the same name as the original.
If both the path and image name are specified it will placed in its own destination and given the new name.
Your code should be like this :
if($this->upload->do_upload('file_name'))
{
$uploadData = $this->upload->data();
$file_name = $uploadData['file_name'];
$this->load->library('image_lib');
$configer = array(
'image_library' => 'gd2',
'source_image' => $uploadData['full_path'],
'create_thumb' => TRUE,
'maintain_ratio' => TRUE,
'width' => 950,
'height' => 950,
'new_image' => FCPATH.MEDIA_LIB_URI.'facts/thumbnail/'
);
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
return $file_name;
}
else
{
return $this->upload->display_errors();
}
For more : https://www.codeigniter.com/user_guide/libraries/image_lib.html#CI_Image_lib::resize
You found the right solution using rename or copy.
The reason it is not working with move_uploaded_file is because this function will only move the uploaded file which temporary name equals "tmp_name" in the $_FILES array.
The reason for this behavior is explained in the PHP manual: "This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system."
As per PHP manual for POST method uploads:
$_FILES['userfile']['name'] = The original name of the file on the client machine.
$_FILES['userfile']['tmp_name'] = The temporary filename of the file in which the uploaded file was stored on the server.
End quote
"tmp_name" is a unique server generated key so there is no filename duplication in the files system.
In your code, the $thumbnail string you built does not match "tmp_name" from the $_FILES array.
The reason you got no error message is because, again from PHP manual but for move_uploaded_file this time: "If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE."
Therefore, if you capture the result of move_uploaded_file in your code like $moveResult = move_uploaded_file(… you will end up with $moveResult === false. It is always a good idea to check the result of such an operation in order to react if something goes wrong.
I am attempting to upload a image file via php and it is not working:
<?php
$target_dir = "/home/NAME/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
print_r($_FILES);
?>
This is what is returned, but no file actually uploads. Anyone know what is going on? Thanks
Array ( [fileToUpload] => Array ( [name] => followers.png [type] => image/png [tmp_name] => /tmp/phpKsuz1B [error] => 0 [size] => 127008 ) )
Change:
move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir);
To:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
Change move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir); to move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_dir);
move_uploaded_file needs the temporary file name in order for it to upload, not the original name of the file, since it needs a resource to move.
The uploaded file is actually $_FILES['fileToUpload']['tmp_name'], this is the file you need to move.
A good way to go about this is:
$tempFile = $_FILES['fileToUpload']['tmp_name'];
$destFile = '/dest/directory/' . $_FILES['fileToUpload']['name'];
// You'll now have your temp file in destination directory, with the original image's name
move_uploaded_file($tempFile, $destFile);
A good practice is to keep your file names unique, because you never know when different images may be named image01.jpg (more often than one would hope).
$tempFile = $_FILES['fileToUpload']['tmp_name'];
$destDir = '/dest/directory/';
$destName = uniqid() . '_' . $_FILES['fileToUpload']['name'];
$destFile = $destDir . $destName;
// Temp file is now in destination directory, with a unique filename
move_uploaded_file($tempFile, $destFile);
i am getting an error in uploading image into folder. there is an error occured during uploading that image.
my Controller Code is (cakeplus is my root folder ex: htpp://localhost/cakeplus) :
$directory = "http://".$_SERVER['HTTP_HOST'].'/cakeplus/pics';
if(!is_dir($directory)) {
mkdir($directory,0777);
}
$files_array = $this->data['Photo']['path'];
//pr($files_array); die;
if(isset($files_array['name']) && $files_array['name']!='') {
$filetype = $files_array['type'];
$filesize = $files_array['size'];
$filename = $files_array['name'];
$filetmpname = $files_array['tmp_name'];
$file_type = explode('.',$filename);
$ext_name = array_reverse($file_type);
$final_file_title = $ext_name[1];
$file_name = Inflector::slug( str_replace( ".".$ext_name[0], "" , $filename ). '_' .time() ,'-' );
$newFileName = $file_name.'.'.$ext_name[0];
move_uploaded_file($filetmpname, $directory.'/'.$newFileName);
$requirementuploadData['Photo']['path'] = $file_name;
$this->Photo->create();
$this->Photo->save($requirementuploadData,false);
}
Error(s)(Warnings) :
Warning (2): move_uploaded_file(http://localhost/cakeplus/pics/wallpaper-1433586197.png): failed to open stream: HTTP wrapper does not support writeable connections [APP\Controller\PhotosController.php, line 31]
Warning (2): move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\xampp\tmp\phpA80D.tmp' to 'http://localhost/cakeplus/pics/wallpaper-1433586197.png' [APP\Controller\Photos
Look into the CakePHP Upload plugin - it will abstract away much of the work that goes into dealing with file and image uploads.
The error you are seeing is because you cannot use move_uploaded_file() to transfer from a file path (C:\xampp\tmp\phpA80D.tmp) to an HTTP URL (http://localhost/cakeplus/pics/wallpaper-1433586197.png).
If you don't want to use the Upload plugin, and would prefer to keep working with what you already have, I would start by changing the $directory path. Something like this might be more appropriate:
$directory = WWW_ROOT . 'pics';
This will contain the path to your ./yourapp/webroot/pics directory, which is also the location of http://yourapp.com/pics.
Check out the documentation for more predefined paths.
may be folder dont have permission to write an image.
you should to use cakephp upload component.
$this->Upload->upload($file,$destination,$name);
I get the following error when trying to upload a .JPG file.
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in H:\Programs\webserver\root\media\images\upload.php on line 43
The following is part of the upload.php file:
if(isset($_FILES['files']))
{
$cat = $_POST['cat'];
$title = $_POST['title'];
$album = $_POST['album'];
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
// get dimensions of uploaded images
echo $temp = $_FILES['files']['tmp_name'][$key]; //location of file
echo $type = $_FILES['files']['type'][$key]; //image type
echo $size = $_FILES['files']['size'][$key]; // image size
>> line 43 >>**echo $size2 = getimagesize($temp); //function to get info of file and put into array**
echo $width = $size2[0]; // first part of the array is the image width
echo $height = $size2[1]; // second part fo the array is the image width
if($type == 'image/jpeg')
{
$filetype = '.jpeg';
}else{
$filetype = str_replace('image/','',$type);
}
$random_name = rand(1000,9999).rand(1000,9999).rand(1000,9999).rand(1000,9999);
$path = 'img/'.$random_name . $_FILES['files']['name'][$key];
$thumb_path = 'img/thumb_/'.$random_name .$_FILES['files']['name'][$key];
I have another .jpg image file that I have been uploading to test which uploads fine, also .png and .gif files also upload fine.
Just to add that I tried a couple more image files of a similar size and received the same error.
The first Image file was 4.2MB the second was 5MB. Why would the file size stop it uploading?
Also when using $_FILES['files']['error'][$key]; - it returns 1.
This is what i get when using print_r:
Array ( [files] => Array ( [name] => Array ( [0] => DSCN0354.JPG ) [type] => Array ( [0] => ) [tmp_name] => Array ( [0] => ) [error] => Array ( [0] => 1 ) [size] => Array ( [0] => 0 ) ) )
Lets look at the knowns:
You can upload .jpg, .gif, .png no problem
You are having problem uploading a specific .jpg image
These knowns lead me to believe that the problem image is too big for the current allowed upload_max_filesize in your php.ini settings:
$ -> php -i | fgrep -i size
upload_max_filesize => 2M => 2M
Try increasing the size to 6M or 8M and your bigger image should work.
If you add some error handling, you can easily see what the problem is using the error code:
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
if ($_FILES['files']['error'][$key] == UPLOAD_ERR_OK)
{
// good
}
else
{
// not good, see messages on http://www.php.net/manual/en/features.file-upload.errors.php
}
}
You have to check for $_FILES['error'][$key] before accessing tmp_name - the file was not uploaded, either because it is too big or some other reason (you will find out by the value of 'error' field)
Also when using $_FILES['files']['error'][$key]; - it returns 1.
Error 1: The uploaded file exceeds the upload_max_filesize directive in php.ini.
(see http://www.php.net/manual/en/features.file-upload.errors.php)
The error message states that the filename supplied is empty.
You are using:
$size2 = getimagesize($temp);
Where do you get $temp from? Is it the foreach() and if it is, you should use $tmp_name instead.