Skip to content

Instantly share code, notes, and snippets.

@camaleaun
Last active June 28, 2019 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camaleaun/8040d7d006cff7a2c5320788355ae65c to your computer and use it in GitHub Desktop.
Save camaleaun/8040d7d006cff7a2c5320788355ae65c to your computer and use it in GitHub Desktop.
Tests file upload in server
<?php
/**
* Uploads tests.
*/
if ( $_POST && isset( $_POST['upload'] ) && ! empty( $_FILES ) ) {
/** Define ABSPATH as this file's directory */
if ( ! defined( 'ABSPATH' ) ) {
define( 'ABSPATH', dirname( __FILE__ ) . '/' );
}
$uploads = array(
'path' => ABSPATH . 'upload',
'subdir' => '',
'basedir' => ABSPATH . 'upload',
);
$file = $_FILES['file'];
$filename = $file['name'];
$number = '';
// Separate the filename into a name and extension.
$ext = pathinfo( $filename, PATHINFO_EXTENSION );
$name = pathinfo( $filename, PATHINFO_BASENAME );
if ( $ext ) {
$ext = '.' . $ext;
}
while ( file_exists( $uploads['path'] . "/$filename" ) ) {
$new_number = (int) $number + 1;
if ( '' == "$number$ext" ) {
$filename = "$filename-" . $new_number;
} else {
$filename = str_replace( array( "-$number$ext", "$number$ext" ), '-' . $new_number . $ext, $filename );
}
$number = $new_number;
}
$new_file = $uploads['path'] . "/$filename";
$move_new_file = @ move_uploaded_file( $file['tmp_name'], $new_file );
if ( false === $move_new_file ) {
if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
$error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
} else {
$error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
}
echo '<pre>';
printf( "The uploaded file could not be moved to %s.\n", $error_path );
echo json_encode( $file, JSON_PRETTY_PRINT );
echo '<pre>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload New Media</title>
</head>
<body>
<h1>Upload New Media</h1>
<form enctype="multipart/form-data" method="post" action="upload.php">
<label for="file">Upload</label>
<input type="file" name="file" id="file">
<input type="submit" name="upload" value="Upload">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment