I was fiddling with my code, trying to write some code that will take data(including pictures) uploaded from a form via POST which will then create a directory complete with its associated subdirectories to store the image.
While writing the code, i kept getting the error
Warning: mkdir(): No such file or directory in C:\Users\Admin\Desktop\UniServer\www\AddItem.php on line 94
HOWEVER, when i set mkdir's resursion to true, mkdir suddenly works and the directory is created without any problems.
My Code:
if(isset($_FILES['upload']['tmp_name']))
{
$numfile=count($_FILES['upload']['tmp_name']);
{
for($i=0;$i<$numfile;$i++)
{
if(is_uploaded_file($_FILES['upload']['tmp_name'][$i]))
{
//Conditionals for uploaded file
$foldername=$_SESSION['UserId'];
$cat=$_POST['category'];
$sub=$_POST['subcat'];
$itemname=$_POST['itemname'];
$allowed_filetypes=array('.jpg','.gif','.bmp','.png');
$max_filesize = 2097152; // Maximum filesize in BYTES (currently 2.0MB).
$upload_path = 'C:\Users\Admin\Desktop\UniServer\www\images\\'.$foldername.'\\'.$cat.'\\'.$sub.'\\'.$itemname.'\\'; // The place the files will be uploaded to.
//Checks if Folder for User exists
//If not, A folder for the user is created to store the user's images
if(!file_exists($upload_path))
{
$upload_path=mkdir($upload_path,0644,true);<-- This is the line
}
$filename = $_FILES['upload']['name'][$i]; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
{
die('The file you attempted to upload is not allowed.');
}
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['upload']['tmp_name'][$i]) > $max_filesize)
{
die('The file you attempted to upload is too large.');
}
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
{
$errormsg="Image Upload Failed.";
}
if(!move_uploaded_file($_FILES['upload']['tmp_name'][$i],"$upload_path" . $filename))
{
$errormsg= 'Your file upload was successful, view the file here'; // It worked.
}
}
}
}
}
else{echo"Upload failed";}
While my code is working now that i've set recursion to true, i still DON't understand exactly WHY it is working, so i would really appreciate it if someone could explain why exactly my code is working.
The closest i've come is with Why mkdir fails with recursive option set true?
Though i couldnt understand any of what was said in the link.
Thanks!
The mkdir() needs the recursive set to true since you ask it to create nested directories that do not exist, i.e.:
$upload_path = 'C:\Users\Admin\Desktop\UniServer\www\images\\'.$foldername.'\\'.$cat.'\\'.$sub.'\\'.$itemname.'\\';
So since the variable $foldername gets its value from the user session, if the user session change it changes. The same goes for the rest of the $upload_path parts, if something of them changes you have to create the whole path. Only the last part of the path ($itemname) can change without using the recursive option.
It fails because it parses the path provided as argument and "changes" path to parent of new directory.
Try this (in a folder test with a subfolder s):
mkdir s/s2/s3 <- will fail because s2 does not exist in s
mkdir s/s2 <- ok
mkdir s/s2/s3 <- ok
When calling with recursive set to TRUE, it does something different: splits the path as usual, but checks existence of each prefix.
Again in folder test:
mkdir -p s/s1/s2/s3/s4 will yield the following prefixes:
s
s/s1
s/s1
s/s1/s2
s/s1/s2/s3
s/s1/s2/s3/s4
Note: I've used mkdir under linux and p argument tells it to create parent directories if they do not exist (same as recursive).
Related
I have some encrypted responses that I convert to a Zip file in my Laravel application. The function below downloads the API response, saves it as a Zip file, and then extracts it while I read the folder's contents. In my local environment, it works well. However, the Zip file is not getting saved to the storage folder on the live server. No error is being shown, only an empty JSON response. Please, what could be the cause?
public function downloadZipAndExtract($publication_id, $client_id)
{
/* We need to make the API call first */
$url = $this->lp_store."clients/$client_id/publications/$publication_id/file";
$file = makeSecureAPICall($url, 'raw');
// Get file path. If file already exist, just return
$path = public_path('storage/'.$publication_id);
if (!File::isDirectory($path)) {
Storage::put($publication_id.'.zip', $file);
// Zip the content
$localArchivePath = storage_path('app/'.$publication_id.'.zip');
$zip = new ZipArchive();
if (!$zip->open($localArchivePath)) {
abort(500, 'Problems experienced while reading file.');
}
// make directory with the publication_id
// then extract everything to the directory
Storage::makeDirectory($publication_id);
$zip->extractTo(storage_path('app/public/'.$publication_id));
// Delete the zip file after extracting
Storage::delete($publication_id.'.zip');
}
return;
}
First thing I'd check is if the storage file is created and if it isn't created, create it. Then I'd look at your file permissions and make sure that the the groups and users permissions are correct and that you aren't persisting file permissions on creation. I've had many instances where the process that's creating files(or trying) is not in the proper group and there is a sticky permission on the file structure.
hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).
I am attempting to write a PHP script that organizes uploaded files into directories according to the date they were uploaded. The script needs to detect whether or not the appropriate directories exists before it executes the upload. First, it checks if the folder 'attachments/2014' exists. If it doesn't, it's created. Next, it checks if the folder 'attachments/2014/October" exists. If it doesnt, create it. Finally, it checks if the folder 'attachments/2014/October/29' exists. If it doesnt, it's created. Then the file is uploaded to the last folder.
For some reason, my script always tries to create the directory, even if it already exists. It only works if the directory doesn't exist. Not really sure why about the former. This is CodeIgniter PHP.
$dtree = array(
date('Y'),
date('Y').'/'.date('F'),
date('Y').'/'.date('F').'/'.date('d')
);
$this->load->library('ftp');
$this->ftp->connect();
foreach($dtree as $dir) {
if($this->ftp->list_files('attachments/'.$dir)) === FALSE) {
$this->ftp->mkdir('attachments/'.$dir);
}
}
If the directory exists, I get the CI error saying "Unable to create the directory you have specified."
I have a very basic, very straightforward function that takes a file (after checking it to make sure its a zip among other things) and uploads it, unpacks it and such:
public function theme(array $file){
global $wp_filesystem;
if(is_dir($wp_filesystem->wp_content_dir() . "/themes/Aisis-Framework/custom/theme/")){
$target_path = $wp_filesystem->wp_content_dir() . "/themes/Aisis-Framework/custom/theme/";
if(move_uploaded_file($file['tmp_name'], $target_path . '/' . $file['name'])) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo($target_path); // change this to the correct site path
$zip->close();
//unlink($target_path);
}
$this->success('We have uplaoded your new theme! Activate it bellow!');
} else {
$this->error('Oops!', 'Either your zip is corrupted, could not be unpacked or failed to be uploaded.
Please try again.');
}
}else{
$this->error('Missing Directory', 'The Directory theme under custom in Aisis Theme does not exist.');
}
if(count(self::$_errors) > 0){
update_option('show_errors', 'true');
}
if(count(self::$_messages) > 0){
update_option('show_success', 'true');
}
}
Extremely basic, yes I have used my target path as both the path to upload too and unpack (should I use a different path, by default it seems to use /tmp/tmp_name)
Note: $file is the array of $_FILES['some_file'];
My question is I get:
Warning: move_uploaded_file(/var/www/wordpress/wp-content//themes/Aisis-Framework/custom/theme//newtheme.zip): failed to open stream: Permission denied in /var/www/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/FileHandling/Upload/Upload.php on line 82
Warning: move_uploaded_file(): Unable to move '/tmp/phpfwechz' to '/var/www/wordpress/wp-content//themes/Aisis-Framework/custom/theme//newtheme.zip' in /var/www/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/FileHandling/Upload/Upload.php on line 82
Which basically means that "oh the folder your trying to move from is owned by root, no you cannot do that." the folder I am moving too is owned by apache, www-data. - I have full read/write/execute (it's localhost).
So question time:
Should my upload to and move to folder be different?
How, in a live environment, because this is a WordPress theme, will users who have the ability to upload files be able to get around this "you dont have permission"?
You should try to do it the wordpress way. Uploading all user content to wp-content/uploads, and doing it with the native functions.
As you mention, uploading to a custom directory, may be an issue to non tech savvy users. /uploads already have the special permissions.
Check out wp_handle_upload. You just have to limit the mime type of the file.
The path you are trying to upload is some where wrong here
wp-content//themes
try removing one slash
I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);