I cant seem to upload a file in php to my server from just anywhere, it will only upload correctly if the file is in the same folder as my upload script which is a serious problem if i want the user to be able to upload from just anywhere.

here is my full code:

require ('dbconnect.php'); // connect to database

// initial database stuff
    set_time_limit(0);
    ini_set('memory_limit', '1024M');

    $file = $_FILES["file"]["name"];
    $file_handle = fopen($file, "r");

    $count= 1;
    mysql_query("TRUNCATE TABLE numdata") or die("MySQL Error: " . mysql_error()); //Delete the existing rows

    while (($data = fgetcsv($file_handle, 0, ",")) !== FALSE)
    {
        foreach($data as $row)
        {
            if($count % 2)
            {
                $complete = $row;
            }
            else{
                $complete .= $row;
                $insertArray[] = $complete;
            }
        $count++;
        $query="INSERT INTO numdata(numb) values($complete)";
        }
        mysql_query($query) or die(mysql_error());
    }

fclose($file_handle);

how do i change the code to enable uploads from any location, or is there a setting i need to change for my server? Any help is greatly appreciated!

Thanks for your time and wisdom.

Dani AI

Generated

A few clarifying notes and a safe, maintainable pattern for this kind of CSV upload and processing. The root issue in the original post was treating the client-side filename as if it were a server path: the browser sends the file data to PHP and the server exposes it as $_FILES['file']['tmp_name'], not $_FILES['file']['name']. was correct to suggest moving the uploaded file to a known server directory; the example below shows a complete, safer flow (validation, move, process, cleanup) and uses PDO prepared statements instead of the deprecated mysql_* functions.

// basic upload handling (replace DB placeholders)
if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    throw new RuntimeException('Upload error.');
}
$tmp = $_FILES['file']['tmp_name'];
$orig = basename($_FILES['file']['name']);

// simple MIME check
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($tmp);
$allowed = ['text/plain','text/csv','application/vnd.ms-excel'];
if (!in_array($mime, $allowed, true)) throw new RuntimeException('Bad file type.');

// move to an uploads directory
$dir = __DIR__ . '/uploads';
if (!is_dir($dir)) mkdir($dir, 0755, true);
$dest = $dir . '/' . time() . '_' . preg_replace('/[^A-Za-z0-9._-]/','_',$orig);
if (!move_uploaded_file($tmp, $dest)) throw new RuntimeException('Move failed.');

// process CSV line-by-line and insert with PDO
$pdo = new PDO('mysql:host=DBHOST;dbname=DBNAME;charset=utf8mb4','DBUSER','DBPASS', [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$insert = $pdo->prepare('INSERT INTO numdata (numb) VALUES (:numb)');
if (($h = fopen($dest, 'r')) !== false) {
    while (($row = fgetcsv($h, 0, ',')) !== false) {
        foreach ($row as $cell) $insert->execute([':numb' => trim($cell)]);
    }
    fclose($h);
}
unlink($dest);

Troubleshooting checklist: confirm file_uploads = On and that upload_max_filesize / post_max_size in php.ini are large enough; check $_FILES['file']['error'] values for INI-related failures; ensure the uploads directory is writable by the webserver user (owner/permissions or SELinux context if applicable); watch memory/time limits for very large files and process line-by-line to avoid high memory use; sanitize and validate CSV contents before DB insert to avoid injection or bad data.

Summary: pointed to the correct approach and the sample above demonstrates a complete, secure flow that addresses the original failure mode seen in 's code and includes cleanup and safer DB handling.

Recommended Answers

All 3 Replies

How are you posting to the script? You need to upload the file and move the file to upload dir or temp dir.. The add the path and file name to fgetcsv.

fgetcsv('path/filename.csv')

is there an example i can use for uploading the file then saving it to a location an dusing it from that location? and also deleteing it for storage purposes

i got it figured out

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.