Skip to content

Instantly share code, notes, and snippets.

@travisfont
Created July 14, 2015 16:45
Show Gist options
  • Select an option

  • Save travisfont/3e0b1083786ac5902a20 to your computer and use it in GitHub Desktop.

Select an option

Save travisfont/3e0b1083786ac5902a20 to your computer and use it in GitHub Desktop.
PHP File Upload
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
define('UPLOAD_DIRECTORY', 'uploads/'); // directory path for the uploads
define('UPLOAD_HASH', md5(time()));
if (isset($_FILES['file']['name']))
{
if ($_FILES['file']['error'] == UPLOAD_ERR_OK)
{
// Processes your file here
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/'.UPLOAD_DIRECTORY;
if (is_dir($upload_dir) && is_writable($upload_dir))
{
// upload logic
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.UPLOAD_HASH.'-'.$_FILES['file']['name']))
{
echo json_encode(array
(
'success' => true,
'file' => array('short'=> $_FILES['file']['name'], 'full' => UPLOAD_HASH.'-'.$_FILES['file']['name'])
));
}
else
{
echo json_encode(array
(
'error' => true,
'message' => 'Error moving temporary file to upload directory.'
));
}
// die("Cannot write to destination file");
}
else
{
echo json_encode(array
(
'error' => true,
'message' => 'Upload directory is not writable, or does not exist.'
));
}
}
else
{
switch ($_FILES['file']['error'])
{
case UPLOAD_ERR_INI_SIZE:
$message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'File upload stopped by a PHP extension';
break;
default: $message = 'Unknown upload error.';
break;
}
echo json_encode(array
(
'error' => true,
'message' => $message
));
}
}
else
{
echo json_encode(array
(
'error' => true,
'message' => 'No file was uploaded'
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment