move_uploaded_file
move_uploaded_file(string $from, string $to): bool
Moves an HTTP-uploaded temp file to a new location: it embeds the "must be a genuine upload" check (defeats forged tmp_name path attacks) and overwrites an existing destination; in the CLI SAPI there is no upload mechanism, so both this and is_uploaded_file always return false (the example demonstrates exactly that).
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void) {
/* CGI-era PHP ran at this exact layer: hand-parse multipart/form-data,
stream the body to a temp file, THEN move it into place. Nobody
hand-parses multipart anymore — every modern stack uses a framework. */
char tmp[] = "/tmp/mov_c_XXXXXX";
int fd = mkstemp(tmp);
char doc[] = "report contents";
write(fd, doc, strlen(doc));
close(fd);
char dest[64];
snprintf(dest, sizeof dest, "/tmp/mov_stored_%d", getpid());
/* the move_uploaded_file idea: only a file that passed the upload check
may be moved into the public dir; rename(2) is atomic within a filesystem */
rename(tmp, dest);
FILE *f = fopen(dest, "r");
char buf[64] = {0};
fread(buf, 1, sizeof buf - 1, f);
fclose(f);
printf("%s\n", buf);
printf("%d\n", access(tmp, F_OK)); // -1: the temp name is gone
unlink(dest);
return 0;
}
report contents -1
C++ C++26
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
int main() {
/* CGI-era PHP ran at this exact layer: hand-parse multipart/form-data,
stream the body to a temp file, THEN move it into place. Nobody
hand-parses multipart anymore — every modern stack uses a framework. */
char tmp[] = "/tmp/mov_cpp_XXXXXX";
int fd = mkstemp(tmp);
char doc[] = "report contents";
write(fd, doc, strlen(doc));
close(fd);
char dest[64];
snprintf(dest, sizeof dest, "/tmp/mov_stored_cpp_%d", getpid());
/* the move_uploaded_file idea: only a file that passed the upload check
may be moved into the public dir; rename(2) is atomic within a filesystem */
rename(tmp, dest);
FILE *f = fopen(dest, "r");
char buf[64] = {0};
fread(buf, 1, sizeof buf - 1, f);
fclose(f);
std::printf("%s\n", buf);
std::printf("%d\n", access(tmp, F_OK)); // -1: the temp name is gone
unlink(dest);
return 0;
}
report contents -1
C# v11.0.100
using System.IO;
// ASP.NET's IFormFile.SaveTo / CopyTo is the framework equivalent of
// move_uploaded_file; a console shows the underlying primitive:
var tmp = Path.GetTempFileName();
File.WriteAllText(tmp, "report contents"); // body streamed to a temp file
// the check before the move: the framework performs the "was this really
// an upload" part for you; here a content sniff stands in for it
var content = File.ReadAllText(tmp);
if (content.StartsWith("report"))
{
var dest = Path.Combine(Path.GetTempPath(), $"mov_stored_{Environment.ProcessId}.txt");
File.Move(tmp, dest); // atomic within a filesystem
Console.WriteLine(File.ReadAllText(dest));
Console.WriteLine(File.Exists(tmp)); // False: the temp name is gone
File.Delete(dest);
}
report contents False
Go v1.27.4
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// net/http's r.ParseMultipartForm / r.FormFile is the framework layer;
// the primitive underneath is exactly move_uploaded_file's semantics:
// stream the body to a temp file, validate, then move it into place.
tmp := fmt.Sprintf("%s/mov_go_%d", os.TempDir(), os.Getpid())
os.WriteFile(tmp, []byte("report contents"), 0600)
b, _ := os.ReadFile(tmp)
if strings.HasPrefix(string(b), "report") { // the upload check stands in here
dest := tmp + "_stored"
os.Rename(tmp, dest) // atomic within a filesystem
got, _ := os.ReadFile(dest)
fmt.Println(string(got))
_, err := os.Stat(tmp)
fmt.Println(os.IsNotExist(err)) // true: the temp name is gone
os.Remove(dest)
}
}
report contents true
Java v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
// Servlet's @MultipartConfig + Part.write() is the framework layer
// (the move_uploaded_file equivalent); the primitive underneath:
Path tmp = Files.createTempFile("mov", ".tmp");
Files.write(tmp, "report contents".getBytes()); // body streamed to a temp file
String content = Files.readString(tmp);
if (content.startsWith("report")) { // the upload check stands in here
Path dest = tmp.resolveSibling("mov_stored_" + ProcessHandle.current().pid() + ".txt");
Files.move(tmp, dest); // atomic within a filesystem
System.out.println(Files.readString(dest));
System.out.println(Files.exists(tmp)); // false
Files.delete(dest);
}
}
}
report contents false
JavaScript v26.13.1
const fs = require("fs");
const os = require("os");
const path = require("path");
// Express's multer middleware is the framework layer (the
// move_uploaded_file equivalent); the primitive underneath:
const dir = fs.mkdtempSync(os.tmpdir() + "/mov_");
const tmp = path.join(dir, "upload.tmp");
fs.writeFileSync(tmp, "report contents"); // body streamed to a temp file
const content = fs.readFileSync(tmp, "utf8");
if (content.startsWith("report")) { // the upload check stands in here
const dest = path.join(dir, "stored.txt");
fs.renameSync(tmp, dest); // atomic within a filesystem
console.log(fs.readFileSync(dest, "utf8"));
console.log(fs.existsSync(tmp)); // false: the temp name is gone
}
fs.rmSync(dir, { recursive: true, force: true });
report contents false
PHP v8.6.0
// In the CLI SAPI there is no HTTP POST upload mechanism, so both
// is_uploaded_file() and move_uploaded_file() are hard-wired to fail:
$fake = tempnam(sys_get_temp_dir(), 'up_');
file_put_contents($fake, 'not a real upload');
var_dump(is_uploaded_file($fake)); // false
var_dump(move_uploaded_file($fake, $fake . '_stored')); // false: refuses
var_dump(file_exists($fake . '_stored')); // false
// A real handler (web SAPI only). The check this function performs for you:
// move_uploaded_file($_FILES['doc']['tmp_name'],
// $destDir . '/' . basename($_FILES['doc']['name']));
// rename() would skip the "was this really an upload" test — an attacker
// crafting tmp_name=/etc/passwd could move ANY file the PHP user can read.
unlink($fake);
bool(false) bool(false) bool(false)
Python v3.15.2
import os
import tempfile
fd, tmp = tempfile.mkstemp(prefix="mov_")
os.close(fd)
with open(tmp, "w") as f:
f.write("report contents")
# Flask's request.files / FileStorage.save() is the framework layer;
# the primitive underneath:
with open(tmp) as f:
content = f.read()
if content.startswith("report"): # the upload check stands in here
dest = tmp + "_stored"
os.replace(tmp, dest) # atomic within a filesystem
with open(dest) as f:
print(f.read())
print(os.path.exists(tmp)) # False: the temp name is gone
os.unlink(dest)
report contents False
Rust v1.99.1
use std::fs;
fn main() {
// actix-web/axum's Multipart extractor is the framework layer;
// std shows the primitive underneath:
let tmp = std::env::temp_dir().join(format!("mov_rs_{}", std::process::id()));
fs::write(&tmp, b"report contents").unwrap(); // body streamed to a temp file
let content = fs::read_to_string(&tmp).unwrap();
if content.starts_with("report") { // the upload check stands in here
let dest = tmp.with_extension("stored");
fs::rename(&tmp, &dest).unwrap(); // atomic within a filesystem
println!("{}", fs::read_to_string(&dest).unwrap());
println!("{}", tmp.exists()); // false: the temp name is gone
fs::remove_file(&dest).unwrap();
}
}
report contents false
TypeScript v26.13.1
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
// Express's multer middleware is the framework layer (the
// move_uploaded_file equivalent); the primitive underneath:
const dir = fs.mkdtempSync(`${os.tmpdir()}/mov_`);
const tmp = path.join(dir, "upload.tmp");
fs.writeFileSync(tmp, "report contents"); // body streamed to a temp file
const content = fs.readFileSync(tmp, "utf8");
if (content.startsWith("report")) { // the upload check stands in here
const dest = path.join(dir, "stored.txt");
fs.renameSync(tmp, dest); // atomic within a filesystem
console.log(fs.readFileSync(dest, "utf8"));
console.log(fs.existsSync(tmp)); // false: the temp name is gone
}
fs.rmSync(dir, { recursive: true, force: true });
report contents false
Language differences
PHP: the security core — move_uploaded_file embeds the is_uploaded_file check: only files produced by PHP's HTTP POST upload mechanism may be moved, defeating forged tmp_name path attacks (e.g. pointing at /etc/passwd); never substitute rename; an existing destination is overwritten; open_basedir applies only to the to path; in the CLI SAPI there is no upload mechanism, so both functions always return false (the example demonstrates exactly this Web/CLI difference).
C/C++: in the CGI era, HTTP uploads meant hand-parsing multipart/form-data (splitting on the boundary, reading Content-Disposition for the file name) — the example stops at the "body -> temp file -> rename" layer; nobody hand-parses multipart anymore: the boundary string can occur inside file content and the encoding details are treacherous — modern stacks all use a framework.
C#: the framework layer is ASP.NET IFormFile (SaveAs/CopyTo); the base library's System.Net.Http only does client-side multipart.
Go: net/http has r.ParseMultipartForm / r.FormFile built in.
Java: Servlet @MultipartConfig + Part.write().
JavaScript/TypeScript: Node has no built-in multipart — Express uses the multer middleware.
Python: Flask request.files (Werkzeug FileStorage.save()); the stdlib cgi module was removed in 3.13 — do not use it.
Rust: ecosystem crates actix-multipart / the axum Multipart extractor; std has none.
Lineage: PHP builds "upload + safe move" into the language runtime (the $_FILES ecosystem); other languages do it at the framework layer — two ways to slice the same thing.
Practical checklist: basename() the stored file name against path traversal, whitelist extensions/MIME, limit size, and forbid script execution in the upload directory.