Images are not uploaded to specifically created folder in WordPress - php

I tried to create a folder to store all my images but it will not upload on its specific upload folder inside my installed theme.
Here is my code:
if(isset($_FILES['file']['tmp_name']))
{
$num_files = count($_FILES['file']['tmp_name']);//count file upload
for($i=0; $i<$num_files; $i++)
{
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
echo "no file upload!!";
}else
{
if(#copy($_FILES['file']['tmp_name'][$i], "/upload/".$_FILES['file']['name'][$i]))
{
$path = "upload/".$_FILES['file']['name'][$i];
//$sql = "insert into tblImage value ('".$path."')";
}else
{
echo "cant upload";
}
}
}
}

It's difficult to figure out exactly what went wrong because I don't know your setup, but try these things:
It's inadvisable to use #copy in this case, especially while you're trying to figure out what's going wrong. Copy will return false on failures and show other error messages in exceptional situations, unless you prefix it with #. If your disk is full, for example, it'll fail silently. Just copy is likely more useful for this.
Your file naming is, at the very least, difficult to decipher. Specifically, what paths are you using? PHP file operations like copy require precise path information. Your path, /upload/, which is upload/ later, refers to something relative from some arbitrary place, that may change. To solve this, figure out a good absolute path. If you're uploading to WP uploads, start with wp_upload_dir and build from there.
Unless you absolutely need a copy of the file from the original location later, move it instead of copying it. Remember that you'd be moving it to the uploads folder, so it'd still be available later, just somewhere else. This also avails you to move_uploaded_file().
There are some great comments (like from #kabiir) about how to debug what you've got. It's hard to figure out exactly what's going wrong without some debugging information.
Try:
if(isset($_FILES['file']['tmp_name'])) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
$file = $_FILE['file']['tmp_name'][$i];
error_log('source: ' . $file);
if (is_uploaded_file($file) && isset($_FILE['file']['name'][$i])) {
$name = $_FILE['file']['name'][$i];
error_log('uploaded name: ' . $name);
$destination = trailingslashit(wp_upload_dir()) . $name;
error_log('destination: ' . $destination);
if (!move_uploaded_file($source, $destination)) {
echo 'failed to move file.';
continue;
}
// Now $destination contains where the file was moved to.
}
}
}
This code will output to your log (or wherever else you have error logging pointed to) the source file+path, the uploaded file name and destination file+path, per file.
Unless there's something very special you're doing, wp_handle_upload() should take care of all your needs without rewriting this. When it's done, it calls the wp_handle_upload filter. Hook to the end of that filter's chain to do your SQL or whatever else. There are also many plugins that do what you're trying to do and save you from having to code it yourself.
As a side note, you ought not create SQL entirely by hand in WP. Use the wpdb class, with the $wpdb->prepare() function. This also allows you to use $wpdb->prefix, which is the prefix for your table. (You've prefixed your table and created it according to WP standards, right?)

Related

How to echo error message if include can't find the file

I use a php script to include another php file. When someone goes to the index.php with the wrong string, I want it to show on the screen an error message.
How do I make it show a custom error message like "You have used the wrong link. Please try again."?
Here is what I am doing now...
Someone comes to the URL like this...
http://example.com/?p=14
That would take them to the index.php file and it would pick up p. In the index.php script it then uses include ('p'.$p.'/index.php'); which finds the directory p14 and includes the index.php file in that directory.
I am finding people, for what ever reason, are changing the p= and making it something that is not a directory. I want to fight against that and just show an error if they put anything else in there. I have too many directories and will be adding more so I can't just us a simple if ($p != '14'){echo "error";} I would have to make about 45 of those.
So what is a simple way for me to say.... "If include does not work then echo "error";"?
$filename = 'p'.$p.'/index.php';
Solution1:
if(!#include($filename)) throw new Exception("Failed to include ".$filename);
Solution2: Use file_exists - this checks whether a file or directory exists, so u can just check for directory as well
if (!file_exists($filename)) {
echo "The file $filename does not exist";
}
You should never use this include solution, because it can be vulnerable to code injection.
Even using file_exists is not a good solution, because the attacker can try some files in your server that was not properly secured and gain access to them.
You should use a white list: a dictionary containing the files that the user can include referenced by an alias, like this:
$whiteList = array(
"page1" => "/dir1/file1.php",
"page2" => "/dirabc/filexyz.php"
)
if (array_key_exists($p, $whiteList)) {
include_once($whiteList[$p]);
} else {
die("wrong file");
}
In this way you do no expose the server files structure to the web and guarantee that only a file allowed by you can be included.
You must sanitize the $p before using it:
$p = filter_input(INPUT_GET, "p", FILTER_SANITIZE_STRING);
But depending on the keys that you use in the dictionary, other filters should be used... look at the reference.
if(!file_exists('p'.$p.'/index.php')) die('error');
require_once('p'.$p.'/index.php');

Clarifcation - Delete files which are not in a mySQL TABLE

Delete files which are not in a mySQL TABLE
The link above is to a Stack Overflow question with an answer that is (I believe) pretty close to what I'm looking for. I'm actually just seeking further clarification on the answer given.
The Question
I'm trying to delete files (picture files) in a folder only if they're
not present in a specific database table.
Just like a check of filenames and if they're present in the table
it's ok but if not delete them.
Any ideas how to do that?
The accepted answer
$result = mysql_query("SELECT filename FROM no_delete");
while($row = mysql_fetch_assoc($result)) {
$do_not_delete[] = $row['filename']; }
foreach(glob("*") as $filename) {
if (!in_array($filename, $do_not_delete)) {
//delete them
}
}
I'm not too savvy with PHP, but I don't believe they are specifying a folder path on the server here, are they? I'd like to be able to look inside a specific folder and check whether any images in that folder are within any database tables. If not, delete that image.
Before calling glob("*") just add a line chdir(""). Then you can search whichever directory you want to look at. I just went one level higher in the call below. You may specify whichever directory you want. Before doing a delete, just add an echo statement to $filename to verify if the correct files are being deleted.
chdir("../");
foreach(glob("*") as $filename) {
if (!in_array($filename, $do_not_delete)) {
//delete them
}
As described in this answer the first parameter, i.e. pattern, can contain the path to a directory relative to the current working directory of the script (which can be changed with chdir()) or an absolute path.
Consider this example from this tutorial page:
$dir = "/etc/php5/*";
// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file)
{
echo "filename: $file : filetype: " . filetype($file) . "<br />";
}

PHP rename() cannot always find source file (code 2) in Windows environment

My environment is: Windows, MsSQL and PHP 5.4.
My scenario:
I'm doing a small shell script that creates a full backup from my wanted database to a temp folder and then moves it to a new location.
The backup goes fine and the file is created to my temp folder. Then I rename it to the 2nd folder and sometimes it goes ok, sometimes it cannot find the source file.
Of course at this point I know that I could skip the temporary location alltogether, but the actual problem with not finding the file bothers me. Why is it so random and might it also affect other file functions I've written before this one... Also i need to be able to control how and when the files move to the destination.
The base code is simple as it should be (although this is a simplified version of my actual code, since I doubt anyone would be interested in my error handling/logging conditions):
$query = "use test; backup database test to disk '//server01/temp/backups/file.bak', COMPRESSION;";
if($SQLClass->query($query)) {
$source="////server01//temp//backups//file.bak";
$destination="////server02//storage//backups//file.bak";
if(!rename($source , $destination)) {
//handleError is just a class function of mine that logs and outputs errors.
$this->handleError("Moving {$source} to {$destination} failed.");
}
}
else {
die('backup failed');
}
What I have tried is:
I added a file_exists before it and it can't find the source file either, when rename can't.
As the file can't be found, copy() and unlink() will not work either
Tried clearstatcache()
Tried sleep(10) after the sql backup completes
None of these didn't help at all. I and google seem to be out of ideas on what to do or try next. Of course I could some shell_execing, but that wouldn't remove my worries about my earlier products.
I only noticed this problem when I tried to run the command multiple times in a row. Is there some sort of cache for filenames that clearstatcache() won't touch ? It seems to be related to some sort of ghost file phenomena, where php is late to refresh the file system contents or such.
I would appreciate any ideas on what to try next and if you read this far thank you :).
You may try calling system's copy command.
I had once problem like yours (on Linux box) when i had to copy files between two NFS shares. It just failed from time to time with no visible reasons. After i switched to cp (analog of Windows copy) problem has gone.
Surely it is not perfect, but it worked for me.
It might be cache-related, or the mysql process has not yet released the file.
mysql will dump the file into another temp file, first and finally moves it to your temp folder.
While the file is beeing moved, it might be inaccessible by other processes.
First I would try to glob() all the files inside temp dir, when the error appears. Maybe you notice, its still not finished.
Also have you tried to implemente something like 10 retry iterations, with some delay?
$notMoved = 0;
while($notMoved < 10){
$source="////server01//temp//backups//file.bak";
$destination="////server02//storage//backups//file.bak";
if(!rename($source , $destination)) {
//handleError is just a class function of mine that logs and outputs errors.
if ($notMoved++ < 10){
sleep(20);
} else {
$this->handleError("Moving {$source} to {$destination} failed.");
break;
}
}else{
break;
}
}
To bypass the issue:
Don't dump and move
Move then dump :-)
(ofc. your backup store would be one behind then)
$source="////server01//temp//backups//file.bak";
$destination="////server02//storage//backups//file.bak";
if(!rename($source , $destination)) {
//handleError is just a class function of mine that logs and outputs errors.
$this->handleError("Moving {$source} to {$destination} failed.");
}
$query = "use test; backup database test to disk '//server01/temp/backups/file.bak', COMPRESSION;";
if($SQLClass->query($query)) {
//done :-)
}
else {
die('backup failed');
}
Try
$source = "\\server01\temp\backups\file.bak";
$destination = "\\server02\storage\backups\file.bak";
$content = file_get_content($source);
file_put_contents($destination, $content);

How to modify file name if the file exists in PHP?

I have a file hosting website and everything works except one thing. I cannot upload two files with the same name. I want to be able to overright the name of a new file with a format like file_2.ext i believe this can be done with the file_exists() function but I am having trouble getting it to work. I will post the system I use to get files to upload below.
System:
if (move_uploaded_file($tmp_location, $location . $name)) {
echo'<br>Upload was successful';
}
I tried doing:
if (isset($_POST['submit_file']) &&!file_exists($name)) {
move_uploaded_file($tmp_location, $location . $name)
echo'<br>Upload was successful';
} else if (isset($_POST['submit_file']) &&file_exists($name)) {
!move_uploaded_file($tmp_location, $location . $name);
echo 'File exists';
}
The method above did not post the error message.
Try something like this. You will need to find a unique filename. You don't want to let it go indefinitely though, so add a limit to it.
function get_unique_filename($filename) {
if (!file_exists($filename)) return $filename;
$limit = 200;
$path = dirname($filename).DIRECTORY_SEPARATOR;
$basename = basename($filename);
$parts = explode('.', $basename);
$ext = array_pop($parts);
$base = implode('.', $parts);
for ($i=2; $i<$limit+2; $i++)
if (!file_exists($path.$base.'_'.$i.'.'.$ext))
return $path.$base.'_'.$i.'.'.$ext;
return false;
}
if (isset($_POST['submit_file'])) {
$new_path = get_unique_filename($location.$name);
if ($new_path && !move_uploaded_file($tmp_location, $new_path))
echo 'Could not upload file.'
else
echo '<br/>Upload was successful';
}
The way you're tackling it is wrong in my opinion , even if you need the user to have the "original" filename, you can't show them "file2.ext" if they uploaded "file.ext", that's just confusing and feels so wrong, take this example
Your server has files named file.ext, file2.ext and file4.ext and
your user uploads a file named file.ext, how would you handle that ? will you iterate over the pattern file*.ext and then add one to the biggest number ? or look for holes
and name it file3.ext ?, or will you append a random number to the file ? how will you handle collisions ? keep looping till it works ? it's just too much pain and might end up making your server really busy if you handle lots of uploads !
What I would do, is use uniqid for filenames on your filesystem, then have a DB that links original filenames to the UUIDs.
This way, all your users are able to upload an file named "file.ext", also it's cleaner to handle files since everything will be unique and their names will have the same length, and no need to worry about filenames in who knows what encoding, etc..
It'll also give you a bonus of being able to change UUIDs and show the same filenames to the user without worrying what they see, this way you're having a layer between the actual files on your FS and what the user perceives files.

PHP file uploading trouble

I'm having an extremely weird problem with a PHP script of mine.
I'm uploading a couple of files and having PHP put them all in one folder.
I've have trouble with random files being sent and random ones not being sent. So I debugged it and I got a very weird result from the $_FILES[] array.
I tried it with 3 files.
$_FILES["addFile"]["name"] Holds the names of the 3 files.
You'd expect $_FILES["addFile"]["tmp_name"] to hold the 3 temporary names that PHP uses to copy the files, but it doesn't. It holds just one name. The other 2 are empty strings, which generate an error whilst uploading(which I supress from being displayed)
This is very odd. I've tried mulitple situations and it just keeps on happening.
This must be something in my settings or perhaps even my code.
Here's my code:
$i = 0;
if (!empty($_FILES['addFile'])) {
foreach($_FILES['addFile'] as $addFile) {
$fileToCopy = $_FILES["addFile"]["tmp_name"][$i];
$fileName = $_FILES["addFile"]["name"][$i];
$i++;
if(!empty($fileToCopy)){
$copyTo = $baseDir."/".$fileName;
#copy($fileToCopy, $copyTo) or die("cannot copy ".$fileToCopy." to ".$copyTo);
}
}
exit(0);
}
Since the tmp_name is empty, the if-value will be false so it's gonna skip the die() function.
Does anybody know what might be causing this?
further info: I'm using Windows XP, running WAMP server. Never had this problem before and I can acces all maps from which I've tried to upload. Security settings of windows can't be the issue I think.
I'm sorry but it seams to me that you are trying to upload all 3 files with the same variable name? Is this right?
But this will not work because they will overwrite each other.
I think the better an cleaner way it would be to use something like
$i = 0;
foreach($_FILES['addFile'.$i] as $addFile) {
if(!empty($addFiles) {
move_uploaded_file($addFile['temp_name'], 'YOUR DIRECTORY');
}
$i++;
}
Relevent, but probably not going to help: but move_uploaded_file is a (slightly) better way to handle uploaded files than copy.
Are any of the files large? PHP has limits on the filesize and the time it can take to upload them ...
Better to send you here than attempt to write up what it says:
http://uk3.php.net/manual/en/features.file-upload.common-pitfalls.php
Your loop logic is incorrect. You are using a foreach loop on the file input name directly, which stores several properties that are of no interest to you ('type','size', etc).
You should get the file count from the first file and use it as the loop length:
if (!empty($_FILES['addFile']) && is_array($_FILES['addFile']['name'])) {
$length = count($_FILES['addFile']['name']);
for($i = 0; $i < $length; $i++) {
$result = move_uploaded_file($_FILES['addFile']['tmp_name'][$i],$baseDir."/" . $_FILES['addFile']['name'][$i]);
if($result === false) {
echo 'File upload failed. The following error has occurred: ' . $_FILES['addFile']['error'][$i];
}
}
}
Check the error code if you are still having problems, it should provide all the information you need to debug it.

Categories