Shared hosting issue - no root directory access - file upload - php

When I tried uploading to /non_public_html/ the support team from my hosting team said that:
. Unfortunately, I have some bad news. It seems that you will not be able to move that file through a script, because of shared hosting restrictions. In order to have "www-data" permissions you would need to have a VPS package, so you could get root permissions.
So I can't upload to outside of /public_html/ it seems.
However when I try to upload to public_html it still fails, this is my code:
$PICTURE_UPLOAD_DIR = '/public_html/my_uploaded/';
$PICTURE_MIMES = [
'jpg' => 'image/jpeg',
'png' => 'image/png'
];
$image = $_FILES['image'];
$imagepath = $image['tmp_name'];
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (!isset($image['error']) || is_array($image['error'])) {
$ojson['error'] = 'Invalid parameters'; $finish();
}
// Check $image['error'] value.
switch ($image['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
$ojson['error'] = 'No file sent'; $finish();
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$ojson['error'] = 'Exceeded filesize limit.'; $finish();
default:
$ojson['error'] = 'Unknown errors.'; $finish();
}
// You should also check filesize here.
$size = filesize($imagepath);
// $size = $image['size']; // dont trust $_FILES
if ($size > 1000000) {
$ojson['error'] = 'Exceeded filesize limit.'; $finish();
}
// DO NOT TRUST $_FILES['image']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($imagepath);
// if ($ext = array_search($mime, $PICTURE_MIMES) === false) { // this doesnt set $ext
if (false === $ext = array_search($mime, $PICTURE_MIMES)) {
$ojson['error'] = 'Invalid file format.'; $finish();
}
$ojson['$ext'] = $ext;
$ojson['$mime'] = $mime;
// generate random file name
while (true) {
$filename = generateRandomString().'.'.$ext;
$pathtarget = $PICTURE_UPLOAD_DIR.$filename;
if (!file_exists($pathtarget)) break;
}
$ojson['$pathtarget'] = $pathtarget;
$ojson['$imagepath'] = $imagepath;
// $getimg = getimagesize($imagepath);
if(is_uploaded_file($imagepath)){
$ojson['isuploaded'] = true;
} else {
$ojson['NOTUPLOADED'] = true;
}
if(move_uploaded_file($imagepath, $pathtarget)) {
$ojson['ok move'] = 'ok';
} else {
$ojson['failed move'] = error_get_last();
}
move_uploaded_file continually fails, and error_get_last() is always printing:
move_uploaded_file(): Unable to move '/tmp/php7G5KMy' to '/public_html/my_uploaded/Q9BEsUkDre.jpg'
isuploaded is always true. I am so confused, may you please help.

Related

php image validation with zip validation

I am creating PHP image validation and zip file validation scripts my zip file validation script is working but I have added image validation but it's not working I want to add image file type jpeg,png file type I have tried to do that's not working
Here is my code
if($_FILES['fileImage']['tmp_name'][0] != "fileImage/jpg") {
die($_FILES['fileImage']['name'][0] . " is not a valid image file.");
exit;
}
$z = zip_open($_FILES['fileImage']['tmp_name'][4]);
if (!is_resource($z)) {
die($_FILES['fileImage']['name'][4] . " is not a valid ZIP file.");
}
zip_close($z);
I would first check the temp file with mime_content_type. The result does not depend on the file extension, which would be easy to manipulate. Further processing could then complete the validation.
$tmpFile = $_FILES['fileImage']['tmp_name'];
switch ($mimeType = mime_content_type($tmpFile)) {
case 'application/zip':
//... process zip ... zip_open, etc
break;
case 'image/jpeg':
//... process image ... getimagesize etc.
break;
default:
die('Unknown filetype "' . $mimeType . '".');
}
Try the following code.
$tempFile = $_FILES['file']['name'];
// Get the file extension
$fileExt = pathinfo($tempFile, PATHINFO_EXTENSION);
// Allowed extensions
$imageExt = ['jpg', 'png', 'gif'];
$compressExt = ['rar', 'zip'];
// Validation
if ( !in_array($fileExt, $imageExt) ) {
die('Not image format');
} elseif ( !in_array($fileExt, $compressExt) ) {
die('No compression format');
} else {
// proceed
}

file_get_contents doesn't work with tmp file

My problem: I want to INSERT a image into a MySQL table with BLOB. In the same project I has upload a file but just the link in a VARCHAR column, and it works. Now I tried with file_get_contents and fread and both of them returns empty string. What's wrong with my code? Or is something wrong with the configuration of php.ini? The code is:
$imgdata = NULL;
$imgext = NULL;
$file = $_FILES['foto'];
if (!in_array($file['type'], $con->ext)) {
exit('Archivo no permitido');
} else {
if ($file['error'] === FALSE) {
exit('Error ' . $file['error']);
} else {
$attachtmp = $file['tmp_name'];
$imgext = $file['type'];
if (file_exists($attachtmp)) {
if (is_uploaded_file($attachtmp)) {
$fp = fopen($attachtmp, 'r+b');
$imgdata = fread($fp, filesize($attachtmp));
fclose($fp);
//if (empty(file_get_contents($attachtmp))) {
//$imgdata = $con->real_escape_string(file_get_contents($attachtmp));
//}
} else {
exit('<h3>Error interno del servidor<h3>');
}
} else {
exit('<h3>Error error interno del servidor<h3>');
}
}
}
Check your results first:
// Check $_FILES['foto']['error'] value.
switch ($_FILES['foto']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
taken from php manual

how to call a variable value in another php file

I have an upload script which uploads files to hosting and the redirects to success urlcode of upload script is as below. I want to get value from this to success url.
<?php
// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER',$_SERVER['DOCUMENT_ROOT'].'/upload/');
// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE', 0);
// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','http://sap.layyah.info/result.php');
// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array();
// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE', false);
// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '');
####################################################################
END OF SETTINGS. DO NOT CHANGE BELOW
####################################################################
// Allow script to work long enough to upload big files (in seconds, 2 days by default)
#set_time_limit(172800);
// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");
function showUploadForm($message='') {
$max_file_size_tag = '';
if (MAX_FILE_SIZE > 0) {
// convert to bytes
$max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
}
// Load form template
include ('file-upload.html');
}
// errors list
$errors = array();
$message = '';
// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
if (strpos($ini_maxsize, 'M') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024;
elseif (strpos($ini_maxsize, 'K') !== false)
$ini_maxsize = intval($ini_maxsize)*1024;
elseif (strpos($ini_maxsize, 'G') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
$errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}
// show upload form
if (!isset($_POST['submit'])) {
showUploadForm(join('',$errors));
}
// process file upload
else {
while(true) {
// make sure destination folder exists
if (!#file_exists(DESTINATION_FOLDER)) {
$errors[] = "Destination folder does not exist or no permissions to see it.";
break;
}
// check for upload errors
$error_code = $_FILES['filename']['error'];
if ($error_code != UPLOAD_ERR_OK) {
switch($error_code) {
case UPLOAD_ERR_INI_SIZE:
// uploaded file exceeds the upload_max_filesize directive in php.ini
$errors[] = "File is too big (1).";
break;
case UPLOAD_ERR_FORM_SIZE:
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
$errors[] = "File is too big (2).";
break;
case UPLOAD_ERR_PARTIAL:
// uploaded file was only partially uploaded.
$errors[] = "Could not upload file (1).";
break;
case UPLOAD_ERR_NO_FILE:
// No file was uploaded
$errors[] = "Could not upload file (2).";
break;
case UPLOAD_ERR_NO_TMP_DIR:
// Missing a temporary folder
$errors[] = "Could not upload file (3).";
break;
case UPLOAD_ERR_CANT_WRITE:
// Failed to write file to disk
$errors[] = "Could not upload file (4).";
break;
case 8:
// File upload stopped by extension
$errors[] = "Could not upload file (5).";
break;
} // switch
// leave the while loop
break;
}
// get file name (not including path)
$filename = #basename($_FILES['filename']['name']);
// filename of temp uploaded file
$tmp_filename = $_FILES['filename']['tmp_name'];
$file_ext = #strtolower(#strrchr($filename,"."));
if (#strpos($file_ext,'.') === false) { // no dot? strange
$errors[] = "Suspicious file name or could not determine file extension.";
break;
}
$file_ext = #substr($file_ext, 1); // remove dot
// check file type if needed
if (count($exts)) { /// some day maybe check also $_FILES['user_file']['type']
if (!#in_array($file_ext, $exts)) {
$errors[] = "Files of this type are not allowed for upload.";
break;
}
}
// destination filename, rename if set to
$dest_filename = $filename;
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
// append predefined string for safety
$dest_filename = $dest_filename . APPEND_STRING;
// get size
$filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);
// make sure file size is ok
if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
$errors[] = "File is too big (3).";
break;
}
if (!#move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
$errors[] = "Could not upload file (6).";
break;
}
// redirect to upload success url
header('Location: ' . SUCCESS_URL);
die();
break;
} // while(true)
// Errors. Show upload form.
$message = join('',$errors);
showUploadForm($message);
}
?>
I want to show $dest_filename on SUCCESS_URL I have tried include and echo but it is not working
In Success URL I am Using:
<?php
if(isset($_GET['uploaded_file_url'])){
$var_1 = $_GET['uploaded_file_url'];
echo $var_1;
}
echo 'Click here for uploaded file!;
Is this what you're after??
// redirect to upload success url
header('Location: '.SUCCESS_URL."?uploaded_file_url=".DESTINATION_FOLDER."/".$dest_filename);
die();
In your successful url script put this at the top of your page:
if(isset($_GET['uploaded_file_url'])){
$var_1 = $_GET['uploaded_file_url'];
echo $var_1;
}
If you want a hyperlink to the url of that file (for download etc), then just wrap a tags around it like so:
echo 'Click here for uploaded file!;
Try to use POST and GET to pass the string on the URL.

Encrypt name of uploaded file

I have an upload script that I found online and modified a little. I need a way to make sure that every file that is uploaded has a unique name; something short at first and as the number of files increase, the length of the name can increase too. My script I've used is...
<?php
// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER','../uploads/');
// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE', 10240);
// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','my info');
// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array('jpg', 'jpeg', 'png', 'gif');
// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE', true);
// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '');
// Need uploads log? Logs would be saved in the MySql database.
define('DO_LOG', true);
// MySql data (in case you want to save uploads log)
define('DB_HOST','my info'); // host, usually localhost
define('DB_DATABASE','my info'); // database name
define('DB_USERNAME','my info'); // username
define('DB_PASSWORD','my info'); // password
/*CREATE TABLE uploads_log (
log_id int(11) unsigned NOT NULL auto_increment,
log_filename varchar(128) default '',
log_size int(10) default 0,
log_ip varchar(24) default '',
log_date timestamp,
PRIMARY KEY (log_id),
KEY (log_filename)
);*/
####################################################################
### END OF SETTINGS. DO NOT CHANGE BELOW
####################################################################
// Allow script to work long enough to upload big files (in seconds, 2 days by default)
#set_time_limit(172800);
// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");
function showUploadForm($message='') {
$max_file_size_tag = '';
if (MAX_FILE_SIZE > 0) {
// convert to bytes
$max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
}
// Load form template
include ('index.php');
}
// errors list
$errors = array();
$message = '';
// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
if (strpos($ini_maxsize, 'M') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024;
elseif (strpos($ini_maxsize, 'K') !== false)
$ini_maxsize = intval($ini_maxsize)*1024;
elseif (strpos($ini_maxsize, 'G') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
$errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}
// show upload form
if (!isset($_POST['submit'])) {
showUploadForm(join('',$errors));
}
// process file upload
else {
while(true) {
// make sure destination folder exists
if (!#file_exists(DESTINATION_FOLDER)) {
$errors[] = "Destination folder does not exist or no permissions to see it.";
break;
}
// check for upload errors
$error_code = $_FILES['filename']['error'];
if ($error_code != UPLOAD_ERR_OK) {
switch($error_code) {
case UPLOAD_ERR_INI_SIZE:
// uploaded file exceeds the upload_max_filesize directive in php.ini
$errors[] = "File is too big (1).";
break;
case UPLOAD_ERR_FORM_SIZE:
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
$errors[] = "File is too big (2).";
break;
case UPLOAD_ERR_PARTIAL:
// uploaded file was only partially uploaded.
$errors[] = "Could not upload file (1).";
break;
case UPLOAD_ERR_NO_FILE:
// No file was uploaded
$errors[] = "Could not upload file (2).";
break;
case UPLOAD_ERR_NO_TMP_DIR:
// Missing a temporary folder
$errors[] = "Could not upload file (3).";
break;
case UPLOAD_ERR_CANT_WRITE:
// Failed to write file to disk
$errors[] = "Could not upload file (4).";
break;
case 8:
// File upload stopped by extension
$errors[] = "Could not upload file (5).";
break;
} // switch
// leave the while loop
break;
}
// get file name (not including path)
$filename = #basename($_FILES['filename']['name']);
// filename of temp uploaded file
$tmp_filename = $_FILES['filename']['tmp_name'];
$file_ext = #strtolower(#strrchr($filename,"."));
if (#strpos($file_ext,'.') === false) { // no dot? strange
$errors[] = "Suspicious file name or could not determine file extension.";
break;
}
$file_ext = #substr($file_ext, 1); // remove dot
// check file type if needed
if (count($exts)) { /// some day maybe check also $_FILES['user_file']['type']
if (!#in_array($file_ext, $exts)) {
$errors[] = "Files of this type are not allowed for upload.";
break;
}
}
// destination filename, rename if set to
$dest_filename = $filename;
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
// append predefined string for safety
$dest_filename = $dest_filename . APPEND_STRING;
// get size
$filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);
// make sure file size is ok
if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
$errors[] = "File is too big (3).";
break;
}
if (!#move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
$errors[] = "Could not upload file (6).";
break;
}
if (DO_LOG) {
// Establish DB connection
$link = #mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
if (!$link) {
$errors[] = "Could not connect to mysql.";
break;
}
$res = #mysql_select_db(DB_DATABASE, $link);
if (!$res) {
$errors[] = "Could not select database.";
break;
}
/*$m_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$m_size = $filesize;
$m_fname = mysql_real_escape_string($dest_filename);
$sql = "insert into _uploads_log (log_filename,log_size,log_ip) values ('$m_fname','$m_size','$m_ip')";
$res = #mysql_query($sql);
if (!$res) {
$errors[] = "Could not run query.";
break;
}*/
#mysql_free_result($res);
#mysql_close($link);
} // if (DO_LOG)
// redirect to upload success url
header('Location: ' . SUCCESS_URL);
die();
break;
} // while(true)
// Errors. Show upload form.
$message = join('',$errors);
showUploadForm($message);
}
?>
Plus, what other security procedures should I use? If you know any, could you please implement them into my code and re-post them? Thank you!!!
The code you've posted already includes the lines:
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
This is a perfectly good way to generate a random unique file name in PHP. The string returned by md5() will be 32 characters long; you could safely truncate it a bit, but if you go much below 16 characters or so, you start risking collisions.
Of course, if you want to make sure there are no collisions, you could always just check whether the file exist and retry if it does. This would even allow you to use shorter filenames:
if (RENAME_FILE) {
do {
$dest_filename = substr(md5(uniqid(rand(), true)), 0, 8) . ".$file_ext";
} while (file_exists(DESTINATION_FOLDER . $dest_filename . APPEND_STRING));
}
This should give you a unique 8-character (+ extension) filename. Of course, this will start slowing down after about 231 &approx; 2 billion uploaded files, and will fail completely at 232 &approx; 4 billion.

PHP File Type Validation

I wrote the following php function to upload files but I'm having a hard time with the array of allowed file types. If I assign just one file type i.e. image/png, it works fine. If I assign more than one, its not working. I use the in_array() function to determine the allowed file types but I can't figure out how to use it properly.
Thank you!
function mcSingleFileUpload($mcUpFileName, $mcAllowedFileTypes, $mcFileSizeMax){
if(!empty($mcUpFileName)){
$mcIsValidUpload = true;
// upload directory
$mcUploadDir = UPLOAD_DIRECTORY;
// current file properties
$mcFileName = $_FILES[$mcUpFileName]['name'];
$mcFileType = $_FILES[$mcUpFileName]['type'];
$mcFileSize = $_FILES[$mcUpFileName]['size'];
$mcTempFileName = $_FILES[$mcUpFileName]['tmp_name'];
$mcFileError = $_FILES[$mcUpFileName]['error'];
// file size limit
$mcFileSizeLimit = $mcFileSizeMax;
// convert bytes to kilobytes
$mcBytesInKb = 1024;
$mcFileSizeKb = round($mcFileSize / $mcBytesInKb, 2);
// create array for allowed file types
$mcAllowedFTypes = array($mcAllowedFileTypes);
// create unique file name
$mcUniqueFileName = date('m-d-Y').'-'.time().'-'.$mcFileName;
// if file error
if($mcFileError > 0)
{
$mcIsValidUpload = false;
mcResponseMessage(true, 'File error!');
}
// if no file error
if($mcFileError == 0)
{
// check file type
if( !in_array($mcFileType, $mcAllowedFTypes) ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'Invalid file type!');
}
// check file size
if( $mcFileSize > $mcFileSizeLimit ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'File exceeds maximum limit of '.$mcFileSizeKb.'kB');
}
// move uploaded file to assigned directory
if($mcIsValidUpload == true){
if(move_uploaded_file($mcTempFileName, $mcUploadDir.$mcUniqueFileName)){
mcResponseMessage(false, 'File uploaded successfully!');
}
else{
mcResponseMessage(true, 'File could not be uploaded!');
}
}
}
}
}
//mcRequiredFile('mcFileUpSingle','please select a file to upload!');
mcSingleFileUpload('mcFileUpSingle', 'image/png,image/jpg', 2097152);
Change this line:
$mcAllowedFTypes = array($mcAllowedFileTypes);
To this:
$mcAllowedFTypes = explode(',',$mcAllowedFileTypes);
Don't rely on the clent file type from $_FILES which is unsafe, get it from the file content.
Then define your allowed file types, check if the upload file type in your white list.
if(in_array(mime_type($file_path),$allowed_mime_types)){
// save the file
}
$allowed_mime_types = array(
'image/jpeg',
'image/jpg',
'image/png',
'image/gif',
'video/mp4'
);
/*
For PHP>=5.3.0, you can use php's `finfo_file`([finfo_file](https://www.php.net/manual/en/function.finfo-file.php)) function to get the file infomation about the file.
For PHP<5.3.0, you can use your's system's `file` command to get the file information.
*/
function mime_type($file_path)
{
if (function_exists('finfo_open')) {
$finfo = new finfo(FILEINFO_MIME_TYPE, null);
$mime_type = $finfo->file($file_path);
}
if (!$mime_type && function_exists('passthru') && function_exists('escapeshellarg')) {
ob_start();
passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($file_path)), $return);
if ($return > 0) {
ob_end_clean();
$mime_type = null;
}
$type = trim(ob_get_clean());
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
$mime_type = null;
}
$mime_type = $match[1];
}
return $mime_type;
}

Categories