0

Consider the following snippet of code:

if (!copy($productdetails['img'][0], "../tempimages/".basename($product['img'][0]))) 
{
    //error and exit or whatever
}

An example of a filename that fails is "proView.MHL H.jpg".

The file is being copied from one website to another (Linux servers). Both inputs have to variables, i.e. I cannot hard code any filenames. Solution cannot use any shell commands either.

How can I still get the file to copy if it contains invalid characters such as spaces, and even the odd slash, Assuming it's possible of course?

The awful practice of putting spaces and full stops in a filename is out of my hands in this case.

Thank you.

EDIT Sorry about forgetting the error message, which is as follows

Warning: copy(http://www.private.co.za/proView.MHL H.jpg): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\websites\schosting\copytest.php on line 4

Gavin Simpson
  • 2,766
  • 3
  • 30
  • 39
  • maybe a str_replace of invalid char before writing the file can help, i suppose you can read the file even with strange name, eventually you can try putting %cod (maybe it's %20) instead of spaces – Marco Mura Dec 10 '14 at 15:55
  • Elaborate on the actual input filename. Are you selling of an URL as filename perhaps and forgot to mention it? Spaces are not an issue per se for file functions. So what's the actual error message? – mario Dec 10 '14 at 15:57
  • Looks very similar to http://stackoverflow.com/questions/3925761/php-copy-command-failing-when-spaces Which recommends url_encode to make sure spaces are actually characters? – Tessmore Dec 10 '14 at 15:57
  • Thanks guys... let me try a few things mentioned here and report back shortly. – Gavin Simpson Dec 10 '14 at 16:07
  • I could have sworn I tried the %20, so feel rather stupid yet again. Thanks for the help. – Gavin Simpson Dec 10 '14 at 16:14
  • @mario, I see where you are coming from with the 'duplicate', but I was talking about using 'copy', not curl. Thanks – Gavin Simpson Dec 10 '14 at 16:25
  • @GavinSimpson I can see where you are coming from with disputing the reference. The solution is still the same. There are also sufficient duplicates for PHPs file functions / http stream; but I just couldn't be bothered with the search either. – mario Dec 10 '14 at 16:29

1 Answers1

0

GET /proView.MHL H.jpg HTTP/1.0 is not a valid request line, which is what your PHP is generating, and is why you're getting a 400 Bad Request error.

The solution is to appropriately encode the file, although the simplest way may just be to handle the case of spaces (str_replace(' ','%20',$productdetails['img'][0])) as this is the only real problem-causer.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592