Issue with copy() - php

I'm not much of a PHPer, but I'm looking at a clients very old site as he's getting some errors.
It's an ancient, bespoke CMS, going back to Feb 2007.
When trying to upload an image the error:
Warning: copy() [function.copy]: Unable to access in blah/blah/blah
This is the part of the code in question:
$path= "images/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "<h1>uploading...</h1>";
$img_name = $_POST['name'];
mysql_query("UPDATE properties SET img_main='$Xnew_file_name_small',img_main_name='$img_name' WHERE ref='$ref'");
$small_image=imagecreatefromjpeg('images/'.$new_file_name);
imagejpeg($small_image, 'images/'.$new_file_name_small, 50);
unlink('images/'.$new_file_name);
echo("<meta http-equiv='refresh' content='0;URL=upload_scipt_main_2.php?ref=". $ref."&img=".$new_file_name_small." '/>");
}
else
{
echo "Error";
}
}
What I'd like to know is if that means that the copy function doesn't have write access to the path it's trying to write to.
Also, as the site is so old, could this error be caused by the PHP version being upgraded?
It's on 5.3.14 now.
I realise that this is probably a shot in the dark and there could be a ton of reasons why it doesn't work and the bit of code posted isn't much of a help but any guidance at all would be really useful.

As the error-message included in your question is rather cryptic, i.e. blah/blah/blah, I can't tell if it's applying to the uploaded file or the destination. If the error is regarding the destination, that means that the images/ directory isn't writable by your web-server (such as Apache). Updating the folder's permissions to be writable may be enough to solve the issue.
On the other hand, if the error is regarding the uploaded file, I will have to agree with your statement that the error could be caused by the PHP version being upgraded.
According to the documentation, $HTTP_POST_FILES has been deprecated for some time in favor of the new(ish) $_FILES.
On the same topic, it appears that you're using this code to basically "upload a file". With that in mind, you won't want to use copy() but move_uploaded_file().
So, instead of a line like this:
copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)
You'll want to try:
move_uploaded_file($_FILES['ufile']['tmp_name'], $path)
Though you may have it elsewhere, you should also verify whether or not the file has been uploaded; you can achieve this with is_uploaded_file(). In combination with the above, and your sample-code, the following should be what you're aiming for:
if(is_uploaded_file($_FILES['ufile']['tmp_name'])) {
$path= "images/".$new_file_name;
if(move_uploaded_file($_FILES['ufile']['tmp_name'], $path)) {
echo "<h1>uploading...</h1>";
$img_name = $_POST['name'];
mysql_query("UPDATE properties SET img_main='$Xnew_file_name_small',img_main_name='$img_name' WHERE ref='$ref'");
$small_image=imagecreatefromjpeg('images/'.$new_file_name);
imagejpeg($small_image, 'images/'.$new_file_name_small, 50);
unlink('images/'.$new_file_name);
echo("<meta http-equiv='refresh' content='0;URL=upload_scipt_main_2.php?ref=". $ref."&img=".$new_file_name_small." '/>");
} else {
echo "Error: The file could not be moved.";
}
} else {
echo "Error: The file could not be uploaded.";
}

Related

Images are not uploaded to specifically created folder in WordPress

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?)

PHP File Upload Error Line 17

I wrote a script that would allow me to upload images and files to my servers, and now that I've switched domains, everything seems a bit messed up.
I've changed the urls and directories, and I've got my chmod set at 777 for the directories needed (cdn and img)
Script:
$folder = "/cdn/img";
$HTTP_POST_FILES = "";
if(isset($_FILES['filename']['tmp_name'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
$ext = strtolower(end(explode('.', $_FILES['filename']['name'])));
$fileCode = fileCode($ext);
if(move_uploaded_file($_FILES['filename']['tmp_name'], $folder . $fileCode)) {
echo 'Your file has been uploaded! View and share your file here';
} else {
echo "THERE'S A GLITCH IN THE MATRIX! YOUR FILE COULDN'T BE UPLOADED!";
}
} else {
Echo "Failed. Try again.";
}
And I'm getting this error:
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpZ1TbaL' to 'http://codyleek.me/cdn/img/e6fmd6.png' in /home/codyleek/public_html/cdn/upload.php on line 17
Sorry that my formatting sucks. I'm new here aha.
But um, could any of you help me? I've tried redoing the URLs, resetting permissions, everything I can think of.
My PHP knowledge is limited.
Thanks in advance.
You should move it to a path on your disk (for example /srv/www/mydomain.com/img/test.png) and not to another website like you're doing now (http://...). By using http://x you are saying: 'use the HTTP-protocol, on domain x to ....'

PHP move_uploaded_file not working into public server

I am trying to upload my php project into public server.
I made the image upload file when I create product or edit product.
It works in localhost, but when I move to public server, it is not working.
I think move_uploaded_file part does not working.
How can I change the link? or do I have to change anything?
When I see Filzilla, I can see remote site that it is '/www/eshopProject/inventory_images'.
And index file is '/www/eshopProject/storeAdmin'.
Do I have to change link like this?
I don't know how can I change the link.
Could you help me? uploading the image into public server is not working..
Is it any security issue? or something?
Please help me. Thanks.
--index.php--
$pid = mysql_insert_id();
//Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file($_FILES['fileField']['tmp_name'], "../inventory_images/product_$newname");
First of all check the permissions of the directory as mentioned in come of the comments.
If you have shell access "chmod 777 target_dir" or "chmod 707 target_dir" should be sufficient.
Second try to debug it using if's and the file_exists function(http://php.net/manual/en/function.file-exists.php).
Something like this.
$uploadedFile = $_FILES['fileField']['tmp_name'];
$destination = "../inventory_images/product_$newname";
if(file_exists($uploadedFile))
{
echo "file uploaded to temp dir";
}
else
{
echo "file upload failed";
exit();
}
if(move_uploaded_file($uploadedFile, $destination))
{
echo "upload complete";
}
else
{
echo "move_uploaded_file failed";
exit();
}
You can also check your current working directory by using the FILE or DIR constants(http://php.net/manual/en/language.constants.predefined.php).
Try this.
echo __FILE__;
echo dirname(__FILE__);
echo __DIR__;
Use the copy() method. For me it worked.
copy($tmp_file, Destination) or
copy($tmp_image, IMAGE_DIRECTORY . SAM . $product_image);
Make sure you have write file permissions set to the folder you are trying to upload too.
I recommend setting the folders to "755" permissions and retry. This would make the permissions a little tighter.
This question is a bit old but i recently faced a similar issue where even with permission 777 on the upload folder it wouldn't work.
The issue was that the SELinux (https://wiki.centos.org/HowTos/SELinux) was on enforcing mode so i had to change it to permissive mode and then the upload works perfectly.
I hope this can help someone facing this issue.

Error with $_FILES["file"]["type"] for flv files

i am having trouble checking the file type of flv files with php. Here's my code
if($_FILES["file"]["type"] == "video/x-flv")
{ echo "true"; }
else{ echo "false"; }
But my problem is that its getting into the else statements when i upload a flv... I'm unable to figure out the problem.. Please help..
EDITED->
Having the same problem for
($_FILES["file"]["type"] == "application/x-shockwave-flash")
as well.. while it works fine for images..
Use finfo_file();
Try
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if (finfo_file($finfo, $filename) == "video/x-flv" ){}
Probably the file itself is not a valid FLV file.
Edited.
1st: Are you sure $_FILES["file"]["error"] is zero? If not, check Error Messages Explained. Usually the most common error is not to have enctype="multipart/form-data" on the form tag of your upload page.
2nd: Never trust $_FILES["file"]["type"]. This is given by the browser. You might want to check the filename extension.
if (strtoupper(substr($_FILES["file"]["name"], -4)) == ".FLV") {
...
}
Testing the filename extension is just as insecure as trusting $_FILES["file"]["type"] - they are BOTH set at the client side. The only reliable solution is to use fileinfo.
You can use gettype() or finfo functions to get the type of the files.

PHP - Failed to open stream: no such file or directory - for existing file

I'm writing a PHP application and in my code i want to create create and return images to the browser. However, sometimes i'm getting some weird results where the image cannot be created since the file does not seem to exist.
Here is a sample error message I get and the code in a nutshell. I do know that the image exists, but still the method sometimes fails, and sometimes it succeeds, even for the same file.
The error:
Warning: imagecreatefrompng(path/to/image.png) [function.imagecreatefrompng]: failed to open stream: No such file or directory in file test.php on line 301
The code:
if (file_exists($filename)) {
$image = imagecreatefrompng($filename);
}
I would greatly appreciate any hints or tips of what might be wrong and how I can improve the code to be more stabile.
I suggest you use is_readable
if (is_readable($filename)) {
$image = imagecreatefrompng($filename);
}
The file may "exist" but is the file accessible? what does file_exists actually do?
if it opens the file and then closes it make sure that the file is actualy closed and not locked before imagecreatedfrompng fires.
it would be a good idea to try catching the error in a loop and make 4 or 5 attempts before handing back a controlled error.
maybe try is_readable() or is_writable() instead?
Have you considered checking for the correct permissions? If the file cannot be read, but the directory can, you would get file_exists(...) = true, but would not be able to open a handle to the file.
Use is_readable() to check whatever you have permission to access that file.
You can try GD :
IF($img = #GETIMAGESIZE("testimage.gif")){
ECHO "image exists";
}ELSE{
ECHO "image does not exist";
}
bro check for white spaces in your filepath. I recently had this issue while i was tring to include a file from a module i was creating for an app. Other modules included well when called but one didnt. It turned out that there was a white space in the filepath. I suggest u try php trim() function. If this works holla.

Categories