简体   繁体   中英

PHP file upload -> replace special chars didn't work

I'm now searching for a solution for two hours, but nothing I found online helped...

I have a webservice with an upload form, which both work fine. I'm more into JS, my whole service is built in HTML5, CSS3 and JS... but my Upload Form is PHP. I found a script online and it worked, so I was fine. Now I realized, that there is a problem with my service, when I want to upload files with chars like ä,ö,ü and ß. Unfortunately here in Germany these are common chars in our language, so I have to replace them with other chars.

I had a look here and there and at the moment my code looks like this:

$files = $_FILES['fileselect'];

foreach ($files['error'] as $id => $err) {
    if ($err == UPLOAD_ERR_OK) {

        $fn = $files['name'][$id];

        $search_array  = array ('ä', 'ö', 'ü', 'ß');
        $replace_array = array ('ae', 'oe', 'ue', 'ss');

        $gfn = str_replace($search_array, $replace_array, $fn);

        move_uploaded_file(
            $files['tmp_name'][$id],
            'bildtransfer/' . $gfn
        );

        echo "<p>Die Datei $gfn wurde hochgeladen.</p>";
    }
}

The upload itself still works with files as long as they don't have those special chars. My file still has all special chars and it seems like there haven't been any replacement?

Do I need preg_replace instead of str_replace? I tried it, but it didn't work either...

I hope you can help me? Would be very pleased!!! :)

It looks like you're using the $_FILES array incorrectly. Any error will be stored in $_FILES['fileselect']['error'] - there's no need for the foreach statement.

The original name of the file is stored in $_FILES['fileselect']['name'] , so try using that in the str_replace() call:

$file = $_FILES['fileselect'];
if($file['error'] == UPLOAD_ERR_OK) {
    $fn = $file['name'];

    $search_array  = array ('ä', 'ö', 'ü', 'ß');
    $replace_array = array ('ae', 'oe', 'ue', 'ss');

    $gfn = str_replace($search_array, $replace_array, $fn);

    move_uploaded_file(
        $file['tmp_name'],
        'bildtransfer/' . $gfn
    );

    echo "<p>Die Datei $gfn wurde hochgeladen.</p>";
}

To be honest I'm not sure why it works at the moment! Have a read through the PHP documentation on Handling file uploads .

To fix the problem so you don't have to bother replacing characters, try telling the browser you're using UTF-8 when you send them, as suggested by @aaron:

header('Content-Type: text/html; charset=utf-8');

It could be an encoding issue. Try changing the encoding type to UTF-8 in the headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM