Jump to content

Upload file overwrite


Ramin2097

Recommended Posts

Hi every body.I'm new to php and this site.this code I've written is for uploading file and I want it to don't overwrite files with the same name.I thought I told it to with file exists.but doesn't work.can't figure out where the problem is.Sorry for my English and Thanks!

 

<?php
    function upload($file,$dest){
        $a=explode('.', $file['name']);
        $filename=$a[0];
        $ext=$a[1];
        $add=microtime();
        if (file_exists($file['name'])) {
                $filename=$add.$filename.$ext;
            }
        if(move_uploaded_file($file['tmp_name'],$dest.$file['name'])){
            echo 'File Uploaded';
        }    
        print_r($file['name']);
    }
    /*
    Array
(
    [picture] => Array
        (
            [name] => Chrysanthemum.jpg
            [type] => image/jpeg
            [tmp_name] => C:\Users\NOVINP~1\AppData\Local\Temp\php\upload\phpFA89.tmp
            [error] => 0
            => 879394
        )
    */
?>
<html>
<head>
<title>File Upload</title>
</head>
<body>
    <?php
        if($_FILES['picture']['name']){
            upload($_FILES['picture'],'upload/');
        }
    ?>
    <form action="" method="post" enctype="multipart/form-data">
        <table width="500" align="center">
            <tr>
                <td><input type="file" name="picture"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Upload" name="submit"></td>
            </tr>
            <tr>
                <td><input type="hidden" name="form" value="1"></td>
            </tr>
        </table>
    </form>
</body>
</html>

Link to comment
Share on other sites

Do not adopt the user-provided filename at all. This may be interesting meta information to be stored in the database, but it's not suitable for the actual file on your server.

 

Instead, generate a purely random filename or use a reliable number sequence (e. g. an AUTO_INCREMENT column). For example, I usually read 16 bytes from the random number generator of the operating system and encode them as 32 hexadecimal bytes. This gives me unique filenames and eliminates the problem of file collisions.

<?php

function random_bytes($number_of_bytes)
{
    if (!$number_of_bytes)
    {
        trigger_error('Invalid number of bytes.', E_USER_WARNING);
        return false;
    }

    $random_bytes = null;
    if (function_exists('mcrypt_create_iv'))
    {
        $random_bytes = mcrypt_create_iv($number_of_bytes, MCRYPT_DEV_URANDOM);
    }
    elseif (function_exists('openssl_random_pseudo_bytes'))
    {
        $random_bytes = openssl_random_pseudo_bytes($number_of_bytes);
    }
    else
    {
        $random_bytes = @file_get_contents('/dev/urandom', false, null, 0, $number_of_bytes);
    }

    if ($random_bytes)
    {
        return $random_bytes;
    }
    else
    {
        trigger_error('Failed to generate random bytes.', E_USER_WARNING);
        return false;
    }
}

function random_hex_bytes($number_of_bytes)
{
    return bin2hex(random_bytes($number_of_bytes));
}

echo random_hex_bytes(16);

You also need to start thinking about security. Right now, you let anybody upload any file to your server. This is a very bad idea. What if the file is a malicious PHP script? What if it's an HTML document which contains malicious JavaScript code?

 

Since you appearently want people to upload images, create a list of acceptable file extensions (“.jpg”, “.png” etc.) and only allow uploads with a correct extension.

Link to comment
Share on other sites

Do not adopt the user-provided filename at all. This may be interesting meta information to be stored in the database, but it's not suitable for the actual file on your server.

 

Instead, generate a purely random filename or use a reliable number sequence (e. g. an AUTO_INCREMENT column). For example, I usually read 16 bytes from the random number generator of the operating system and encode them as 32 hexadecimal bytes. This gives me unique filenames and eliminates the problem of file collisions.

<?php

function random_bytes($number_of_bytes)
{
    if (!$number_of_bytes)
    {
        trigger_error('Invalid number of bytes.', E_USER_WARNING);
        return false;
    }

    $random_bytes = null;
    if (function_exists('mcrypt_create_iv'))
    {
        $random_bytes = mcrypt_create_iv($number_of_bytes, MCRYPT_DEV_URANDOM);
    }
    elseif (function_exists('openssl_random_pseudo_bytes'))
    {
        $random_bytes = openssl_random_pseudo_bytes($number_of_bytes);
    }
    else
    {
        $random_bytes = @file_get_contents('/dev/urandom', false, null, 0, $number_of_bytes);
    }

    if ($random_bytes)
    {
        return $random_bytes;
    }
    else
    {
        trigger_error('Failed to generate random bytes.', E_USER_WARNING);
        return false;
    }
}

function random_hex_bytes($number_of_bytes)
{
    return bin2hex(random_bytes($number_of_bytes));
}

echo random_hex_bytes(16);

You also need to start thinking about security. Right now, you let anybody upload any file to your server. This is a very bad idea. What if the file is a malicious PHP script? What if it's an HTML document which contains malicious JavaScript code?

 

Since you appearently want people to upload images, create a list of acceptable file extensions (“.jpg”, “.png” etc.) and only allow uploads with a correct extension.

LOL.buddy I'm new and it's just start for me!I'm doing it step by step and the first step is to prevent overwriting.If I do them all at the same time(for start cuz it's the first time I'm making a form)I will get confused so I want to do it step by step then make a complete form.So...I didn't get anything from your code/:D Can U say it a bit more newbie friendly?

And Thank U very much buddy.

Link to comment
Share on other sites

If you have a question, then ask. I'll try to clarify. But if you reject the entire reply and expect me to repeat everything in a more newbie-friendly way (whatever that means), it looks like you just want to avoid any effort on your part.

 

You asked how to prevent files from being overwritten. I suggested random filenames and gave you a function to generate those names. So step 1 is to use this function in your code.

Link to comment
Share on other sites

If you have a question, then ask. I'll try to clarify. But if you reject the entire reply and expect me to repeat everything in a more newbie-friendly way (whatever that means), it looks like you just want to avoid any effort on your part.

 

You asked how to prevent files from being overwritten. I suggested random filenames and gave you a function to generate those names. So step 1 is to use this function in your code.

All right.U see my code at first post.

1-Should I delete the php part I've written my self and replace yours or simply add it under my first function?

2-and is dev/urandom the output folder?if it is and I want to change it to images file for example I should just change the '/dev/urandom' to '/images'?no other changes in codes?

I'm trying to figure out what U did exactly.but kinda confused.I'm checking every function in your code to understand.but still a bit confusing.U have any resources or tutorials teaching your code step by step?as you mentioned you can't repeat everything so I'm asking for a tutorial or resource.and again thank you very much

BTW maybe it's not the right place to ask this but don know where else to...

I'm also interested in app development for android and I discovered that it can be done with php too.so if I learn php can I do that?how much knowledge on php do I need?would it confuse me or on the contrary help learn and understand php better?

Edited by Ramin2097
Link to comment
Share on other sites

You don't have to change anything about the functions. As the names already say, they generate random strings. How this is implemented is irrelevant for now. All you have to do is call random_hex_bytes(16) to get a random filename consisting of 32 hexadecimal characters. Then you build the complete target path of the uploaded file and move it to that location.

 

It should be fairly simple to put this into your code. You just have to change the part where you set the filename.

Link to comment
Share on other sites

You don't have to change anything about the functions. As the names already say, they generate random strings. How this is implemented is irrelevant for now. All you have to do is call random_hex_bytes(16) to get a random filename consisting of 32 hexadecimal characters. Then you build the complete target path of the uploaded file and move it to that location.

 

It should be fairly simple to put this into your code. You just have to change the part where you set the filename.

all right.I updated my code.Still doesn't work!sorry I probably have made a stupid mistake or forgot something but can't understand what!:|

<?php

    function random_bytes($number_of_bytes)

{

    if (!$number_of_bytes)

    {

        trigger_error('Invalid number of bytes.', E_USER_WARNING);

        return false;

    }

 

    $random_bytes = null;

    if (function_exists('mcrypt_create_iv'))

    {

        $random_bytes = mcrypt_create_iv($number_of_bytes, MCRYPT_DEV_URANDOM);

    }

    elseif (function_exists('openssl_random_pseudo_bytes'))

    {

        $random_bytes = openssl_random_pseudo_bytes($number_of_bytes);

    }

    else

    {

        $random_bytes = @file_get_contents('/dev/urandom', false, null, 0, $number_of_bytes);

    }

 

    if ($random_bytes)

    {

        return $random_bytes;

    }

    else

    {

        trigger_error('Failed to generate random bytes.', E_USER_WARNING);

        return false;

    }

}

 

function random_hex_bytes($number_of_bytes)

{

    return bin2hex(random_bytes($number_of_bytes));

}

 

    function upload($file,$dest){

        $a=explode('.', $file['name']);

        $filename=$a[0];

        $ext=$a[1];

        $add=microtime();

        if (file_exists($file['name'])) {

                random_hex_bytes(16);

            }

        if(move_uploaded_file($file['tmp_name'],$dest.random_hex_bytes(16))){

            echo 'File Uploaded';

        }    

        print_r($file['name']);

    }

 

echo random_hex_bytes(16);

?>

<html>

<head>

<title>File Upload</title>

</head>

<body>

    <?php

        if($_FILES['picture']['name']){

            upload($_FILES['picture'],'upload/');

        }

    ?>

    <form action="" method="post" enctype="multipart/form-data">

        <table width="500" align="center">

            <tr>

                <td><input type="file" name="picture"></td>

            </tr>

            <tr>

                <td><input type="submit" value="Upload" name="submit"></td>

            </tr>

            <tr>

                <td><input type="hidden" name="form" value="1"></td>

            </tr>

        </table>

    </form>

</body>

</html>

Edited by Ramin2097
Link to comment
Share on other sites

“Doesn't work”? What does that mean? You'll have to be more specific.

 

Do you get no result file at all, or are you simply not happy with the file? Are you getting any PHP errors either on the screen or in the error log?

 

Since I have zero information, I'll simply make a guess: You don't get any file at all. Replace the relative upload path (relative to what?) with an absolute path and make sure that PHP actually has write permissions to that folder.

Link to comment
Share on other sites

“Doesn't work”? What does that mean? You'll have to be more specific.

 

Do you get no result file at all, or are you simply not happy with the file? Are you getting any PHP errors either on the screen or in the error log?

 

Since I have zero information, I'll simply make a guess: You don't get any file at all. Replace the relative upload path (relative to what?) with an absolute path and make sure that PHP actually has write permissions to that folder.

OOPS!LOL.strange.It didn't work when I posted this now it does!:D

Thank U very much for your help.I really appreciate that.

Just one more question.I posted the topic but no answer till now.

Can I really develop android apps with php?and if yes how?I googled that and the answer was yes but didn't find resources about how to do it.

Link to comment
Share on other sites

Android is a Java based platform.

You will need to download and install Google SDK and Eclispe to start.

You will need to practice a lot.

 

I did the same and fell back to PHP coding... because i got myself seriously confused with what I wanted to do.

 

Set a goal for yourself and chase it like crazy... dont  mix yourself with new languaue unless you really want to do it

Link to comment
Share on other sites

Android is a Java based platform.

You will need to download and install Google SDK and Eclispe to start.

You will need to practice a lot.

 

I did the same and fell back to PHP coding... because i got myself seriously confused with what I wanted to do.

 

Set a goal for yourself and chase it like crazy... dont  mix yourself with new languaue unless you really want to do it

First of all thanks for your reply.I know that but:

http://venturebeat.com/2012/10/23/huge-news-php-developers-can-now-design-build-and-publish-mobile-apps-right-in-zend-studio/

according to this link we can write android apps with php...just don't know how to

Link to comment
Share on other sites

Thanks for the link.

 

I think they will launch some conversion module or something, i dont know yet and they havent disclosed it yet... but if it came into application, that will be a breakthrough :)

Anytime Buddy.;)

I guess they already did.the link belongs to 2012!it means by now it should be done...

and in the link is a video that someone makes an app with the zend editor!but of course he was expert and I'm not.I didn't find out any resource or tutorial.I hope I can find some here.

I started new topic at this link:

http://forums.phpfreaks.com/topic/290624-android-php-based-applications/

14 people viewed no answer yet...

:(

Edited by Ramin2097
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.