I'm working on a project but when testing the upload pictures function it gives me errors all the way. The site is on a Portal.website.com link (so not www, dunno if that matters)
Anyhow here is the message I get:
Warning: move_uploaded_file(img/uploads/IMG_20160402_244056496.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/xxx/domains/website.com/public_html/portal/artikeltoevoegen.php on line 33
And
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpf277z2' to 'img/uploads/IMG_20160402_244056496.jpg' in /home/xxx/domains/website.com/public_html/portal/artikeltoevoegen.php on line 33
And here is the php part the form itself is pretty standard and works flawlessly
if (isset($_POST['uploadArticle']))
{
$title = $_POST['title'];
$article = $_POST['article'];
$files = $_FILES['files'];
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*1000; //1000 kb
$count = 0;
foreach ((array) $_FILES['files']['name'] as $f => $name)
{
if ($_FILES['files']['error'][$f] == 4)
{
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0)
{
if ($_FILES['files']['size'][$f] > $max_file_size)
{
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) )
{
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else
{
// No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f],"img/uploads/".$name))
{
$count++; // Number of successfully uploaded file
echo $count;
}
}
}
}
}
Okay so it happened to be the server permissions for the folders I was trying to write too. I changed it from 755 to 777 now it works just fine.
Hope someone can use this info
As the error suggests the path you are passing to move_uploaded_file does not exist.
If the img folder is in the same directory as the php file you are calling move_uploaded_file from, try using a relative url:
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f],"./img/uploads/".$name))
by adding ./ in front of img
Related
I am trying to upload either pdf or jpg, jpeg files to a folder and the code is as follows:
//Get the uploaded file information
if(!$_FILES['medreport']['error'])
{
$medreport = basename($_FILES['medreport']['name']);
$medreport_extn = substr($medreport, strrpos($medreport, '.') + 1);//get the file extension of the file
$medreport_size = $_FILES["medreport"]["size"]/1024;//size in KBs
$tmp_path = $_FILES["medreport"]["tmp_name"];
$report_folder = "../reports/";
//Settings
$max_allowed_file_size = 200; // size in KB
$allowed_extensions = array("jpg", "jpeg", "pdf");
//Validations
}
if($medreport_size > $max_allowed_file_size )
{
$error[] = "Size of the report file should be less than $max_allowed_file_size KB";
}
//Validate the file extension
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$medreport_extn) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$error[] = "The uploaded report file is not a supported file type. "."Only pdf, jpg and jpeg report file types are supported. ";
}
//replace filename with unixtime
$unixtime =time();
$medreport = $unixtime.mt_rand(0,9).'.'.$medreport_extn;
$report_path = $report_folder . $medreport;
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$report_path))
{
$error[] = 'Error while copying the uploaded report file';
}
}
while trying to upload files with correct extension and size i am able to upload it.
But if i try to upload an over sized or incorrect format file, it displays my error message, but the file always get uploaded to the folder.
Why is it so ?? Please, What is wrong with my code??
Is the way, i am doing it is secure enough ?? the folder is owned by www-data and permission is 755. I have a .htaccess file too in the file upload folder to prevent executables as follows:
SetHandler none
SetHandler default-handler
Options -ExecCGI
php_flag engine off
The file always uploading is confusing me.
You are not using the errors you just found to check if you need to continue.
This:
if(is_uploaded_file($tmp_path))
Should be something like:
if(count($error) === 0 && is_uploaded_file($tmp_path))
And you should initialize your $error array at the start as an empty array if you are not doing that already.
I am trying to upload multiple photos of a new user to a new directory on the server, assigning a directory name for that person based in their name and ID in the DB. A path to the new directory is added to a field in the DB, so that these photos can be referenced later. All other DB functionality is working except for this.
I haven't worked on this project for a good 6 months, and this feature was working at some stage. I am unsure what I have messed up. At present I get '0 files uploaded successfully', with no new directory or reference being created. DB connection must be fine as other info earlier in the code not included here is adding without an issue.
Please help. I am pulling at what little hair I have left!
$count = 0;
$valid_formats = array("jpg", "png");
$max_file_size = 1024*5000;
$lastID = $mysqli->insert_id;
$path = '../img/gallery/'.$lastID.'_'.$displayName.'/';
$path2 = './img/gallery/'.$lastID.'_'.$displayName.'/';
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
foreach ($_FILES['photoUploader']['name'] as $f => $name) {
if ($_FILES['photoUploader']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['photoUploader']['error'][$f] == 0) {
if ($_FILES['photoUploader']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($displayName, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else { // No error found!
// Create new directory based on unique ID and display name
if (!is_dir($path)) {
mkdir($path, 0777, true);
}
// move temporary files to permanent location
if(move_uploaded_file($_FILES["photoUploader"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
// add image folder url to db for future use
$imageUrlQuery = "UPDATE models SET photoLocation=? WHERE id=$lastID";
$imageUrlstmt = $mysqli->prepare($imageUrlQuery);
$imageUrlstmt->bind_param('s', $path2);
$imageUrlstmt->execute();
}
}
}
echo $count . " file(s) uploaded successfully!";
Set form to:
multipart/form-data
Cluster upload items: photos[ ]
<input type="file" name="photos[]" multiple="multiple" id="multipic"/>
<label for="multipic"><btn> Select 3 Photos </btn></label>
Handle Files
foreach($_FILES['photos']['tmp_name'] as $key => $tmp_name ){
$file_name = $_FILES['photos']['name'][$key];
$file_tmp = $_FILES['photos']['tmp_name'][$key];
$file_size = $_FILES['photos']['size'][$key];
$photo1="dir/where/photos/go/";
$photo1=$photo1 . basename($_FILES['photos']['name'][0]);
$fz1=$_FILES['photos']['size'][0];
if(move_uploaded_file($_FILES['photos']['tmp_name'][0], $photo1)) {
/* do whatever you like here */ }
$photo2 ...
$photo3 ...
}
You can do this for each item: [0] [1] [2], etc.
this is going to seem stupid. It was a simple oversight.....
elseif( ! in_array(pathinfo($displayName, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
$displayName needed changing to $name. That was it. Sigh......
I found this code, to upload multiple files
http://www.w3bees.com/2013/02/multiple-file-upload-with-php.html?showComment=1390161630156#c8075663254636569559
I modified a little bit the code for obtain a upload/subdirectories folder with unique id for each one of the sets uploads ;so the files also gets a unique id.
$dir=substr(uniqid(),-7); // Uniqid for subdirectory
$path = "uploads/$dir/"; // uploads/subdirectory/
mkdir($path, 0700); // Make directory
$valid_formats = array("jpg", "png", "jpeg", "kml");
$max_file_size = 2097152;
$count = 0;
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = substr(uniqid(),-5) . '.' .$ext;
$dest = $path . $uniq_name;
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest);
mysqli_query($dbc, "INSERT INTO files (code, name, path, type) VALUES ('$dir','$uniq_name','$dest','$ext')" );
$count++; //Number of successfully uploaded file
}
}
}
}
This process is carried out correctly.
I want after move_upload_file, get all paths(url) of files uploads.
But I get inserted on the database only path first file selected... the other paths files are upload correctly, but not inserted on the database.
Sorry for my bad english, it's not my first language. I hope you can help me.
Try something as
$sql_error = ''; // add this before you start the loop
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)){
$qry = "INSERT INTO files (code, name, path, type) VALUES ('$dir','$uniq_name','$dest','$ext')" ;
$result = mysqli_query($dbc, $qry);
if ( false===$result ) {
$sql_error .= 'Error in the query '.$qry.' Error Desc :'.mysqli_error($dbc).'<br /><br />' ;
}
}
Finally add
echo $sql_error ;
At the end of the file , so if there is any error it will show you the error in the query.
Also by adding the query inside
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)){}
means you are adding only if the files are getting uploaded.
the htdocs folder in xampp has the 777 permissions, i can copy alter any file manually there but uploading a file into a subfolder gives an error. my code is:
<?php
define ('MAX_FILE_SIZE', 1024 * 50);
if (array_key_exists('submit', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', '/opt/lampp/htdocs/properties/');
// replace any spaces in original filename with underscores
$file = str_replace(' ', '_', $_FILES['image']['name']);
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg','image/png');
// upload if file is OK
if (in_array($_FILES['image']['type'], $permitted)
&& $_FILES['image']['size'] > 0
&& $_FILES['image']['size'] <= MAX_FILE_SIZE) {
switch($_FILES['image']['error']) {
case 0:
// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR . $file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR $file);
} else {
$result = 'A file of the same name already exists.';
}
if ($success) {
$result = "$file uploaded successfully.";
} else {
$result = "Error uploading $file. Please try again.";
}
break;
case 3:
case 6:
case 7:
case 8:
$result = "Error uploading $file. Please try again.";
break;
case 4:
$result = "You didn't select a file to be uploaded.";
}
} else {
$result = "$file is either too big or not an image.";
}
}
?>
the error i get is:
Warning: move_uploaded_file(/opt/lampp/htdocs/properties/Cover.jpg): failed to open stream: Permission denied in /opt/lampp/htdocs/listprop.php on line 82
check is safe_mode is on in your php.ini
If only the xampp folder is writable that doesn't help, you need the sub-folders writable too.
Second, just asking
define('UPLOAD_DIR', '/opt/lampp/htdocs/properties/');
where lampp is shouldn't that be xampp? just asking (that can cause move problems too)
I am trying to create a PHP file to upload images to my website. I have the following code, but it is not working. Can anyone help me fix it so I do not get any errors? Is there any better way to do such a thing? I know it is old fashioned.
$uploaddir = "uploads/images";
$allowed_ext = "jpg, JPG, png, gif";
$max_size = "500000";
$max_height = "4000";
$max_width = "4000";
$extension = pathinfo ($_FILES['file']['name']);
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
for ($i = 0; $i <= count($allowed_paths); $i++){
if ($allowed_paths[$i] == "$extension"){
$ok = "1";
}
}
if ($ok == "1"){
if($_FILES['file']['size'] > $max_size){
print "Your file is too big!";
exit;
}
}
if($max_width && $max_height){
list($width, $height, $type, $w) = getimagesize($_FILES['file']['name']);
if ($width > $max_width || $height > $max_height){
print "Your file width/height are too big!";
exit;
}
}
if (is_uploaded_file($_FILES['file']['tmp_name'])){
move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir.'/'.$_FILES['file']['name']);
print "Your file was uploaded successfully :)";
}
else
print "Wrong extensin";
?>
When I run the script I get the following error:
Warning: getimagesize(1 (8).jpg) [function.getimagesize]: failed to open stream: No such file or directory in D:\Hosting\8923686\html\uploadedimages\upload.php on line 25
Warning: move_uploaded_file(uploads/images/1 (8).jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in D:\Hosting\8923686\html\uploadedimages\upload.php on line 33
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'D:\Temp\php\phpE5F5.tmp' to 'uploads/images/1 (8).jpg' in D:\Hosting\8923686\html\uploadedimages\upload.php on line 33
or
invalid file
Can any one please tell me where is my problem?
As for the first error, change getimagesize($_FILES['file']['name']) to getimagesize($_FILES['file']['tmp_name']).
As for the other two errors, make sure your script has permissions to write files to the folder where you're trying to move the uploaded file to.
Edit: Also try to use a full absolute path in $uploaddir instead of just uploads/images. Since you're using a relative path from a script that isn't located in the document root, it's possible that PHP is looking in the wrong directory.
getimagesize($_FILES['file']['name'] in line 25 is the first culprit: you meant getimagesize($_FILES['file']['tmp_name']
For the othe errors you need to check permissions of uploads/images - they are obviously off limits for the webserver user.