Image fields are uploading php and other files to upload folder - php

My script is not working properly. If i upload a php file instead of jpg file then it should not upload php files to upload folder, i want to allow only image files. Please correct my script.
Here is my code Thanks !
<?php
include "inc.php";
ob_start();
if(!isset($_SESSION['ocer']) && trim($_SESSION['ocer'])!=''){
header("Location: admin.php?l=1");
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$title=addslashes(mysql_real_escape_string($_REQUEST['title']));
$des=addslashes(mysql_real_escape_string($_REQUEST['des']));
$location=addslashes(mysql_real_escape_string($_REQUEST['location']));
$state=addslashes(mysql_real_escape_string($_REQUEST['state']));
$status=mysql_real_escape_string($_REQUEST['status']);
$userid=mysql_real_escape_string($_REQUEST['userid']);
$date1=mysql_real_escape_string($_REQUEST['date1']);
chmod('upload', 0777);
if($_FILES['file_name1']['name']!="")
{
$file_name1=$_FILES['file_name1']['name'];
$ext=getExtension($file_name1);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name1=mktime().'thumb1'.'.'.$ext;
copy($_FILES['file_name1']['tmp_name'],"upload/".$file_name1);
}
}
if($_FILES['file_name2']['name']!="")
{
$file_name2=$_FILES['file_name2']['name'];
$ext=getExtension($file_name2);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name2=mktime().'thumb2'.'.'.$ext;
copy($_FILES['file_name2']['tmp_name'],"upload/".$file_name2);
}
}
if($_FILES['file_name3']['name']!="")
{
$file_name3=$_FILES['file_name3']['name'];
$ext=getExtension($file_name3);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name3=mktime().'thumb3'.'.'.$ext;
copy($_FILES['file_name3']['tmp_name'],"upload/".$file_name3);
}
}
if($_FILES['file_name4']['name']!="")
{
$file_name4=$_FILES['file_name4']['name'];
$ext=getExtension($file_name4);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name4=mktime().'thumb4'.'.'.$ext;
copy($_FILES['file_name4']['tmp_name'],"upload/".$file_name4);
}
}
if(trim($title)!="" && trim($des)!=""){
$sql_ins="insert into `jobs` set title='$title',des='$des',location='$location',state='$state',date1='$date1',userid='$userid',status='$status',newsimg='$file_name1',newsimg2='$file_name2',newsimg3='$file_name3',newsimg4='$file_name4'";
$rs=mysql_query($sql_ins) or die(mysql_error());
$lid=mysql_insert_id();
$notice="job";
}
header("location: admin.php?done=1");
?>

try the following lines
$ext = pathinfo($_FILES["file_name3"]["name"], PATHINFO_EXTENSION);
if($ext...)// your if else condition
{}
else
{}

Part 1 :
$valid_mime_types = array(
"image/gif",
"image/png",
"image/jpeg",
"image/pjpeg",
);
if (in_array($_FILES["file"]["type"], $valid_mime_types)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 2 :
$valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
$file_extension = strrchr($_FILES["file"]["name"], ".");
// Check that the uploaded file is actually an image
// and move it to the right folder if is.
if (in_array($file_extension, $valid_file_extensions)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 3 :
if (#getimagesize($_FILES["file"]["tmp_name"]) !== false) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}

Related

PHP Upload images script

This is my code:
function secure_img_upload($file, $path, $options = array()){
// HANDLE OPTIONS
$validExtensions = isset($options['validExtensions']) ? $options['validExtensions'] : array('jpg', 'jpeg', 'png');
$surfix = isset($options['surfix']) ? $options['surfix'] : '';
// HANDLES FILES
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$extension = explode(".", $fileName);
$extension = strtolower(end($extension));
$imageName = sha1($fileName.uniqid());
$destination = rtrim($path, '/').'/'.$imageName.$surfix.'.'.$extension;
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile, $destination)) {
return $destination;
}else{
return array('s'=>'ko', 'm'=>T("Invalid path."));
}
}else{
return array('s'=>'ko', 'm'=>T("Invalid extension."));
}
}
My problem is that in this way, Images are uploaded in a random way.
But I need that images are uploaded in the order I select them. Any tips? Thank you

Scandir not listing files when remote

I'm working on an image compression cron job for my sites assets. The problem I'm facing is that the code works fine locally but not on on the remote server.
I'm using scandir, I've seen the related post: php scandir() not showing files - only showing directories users were saying that it isn't recursive. However on my local system I've replicated the folder structure on the remote server and it works perfectly.
I have the following function which I use for both folders and files.
function getFilesInDir($path)
{
$directory = $path;
if (is_dir($directory))
{
$files = array();
foreach(scandir($directory) as $file)
{
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
// }
}
}
return $files;
}
When I use var_dump on the the folder I get the right results. It lists all folders within the specified directory.
Usage
$folders = getFilesInDir("site/assets/files");
foreach($folders as $folder)
{
$files = getFilesInDir($folder);
//...Do the rest
So var_dump($folders) displays the correct directories. When I do var_dump($files) I get NULL NULL NULL NULL NULL.
I reiterate, this works fine on my local machine but not my remote server.
Complete Code (if it's of use)
It's not pretty I know but it works and I'm on a deadline.
<?php
// $folders = getFilesInDir(getcwd());
$folders = getFilesInDir("site/assets/files");
foreach($folders as $folder)
{
$files = getFilesInDir($folder);
var_dump($files);
if ($files)
{
$x = array_filter($files, "isImage");
foreach($files as $f)
{
$path_parts = pathinfo($f);
if (#$path_parts['extension'] != null)
{
if (filesize($folder . "/" . $f) > 1000000)
{
echo $f . " - " . filesize($folder . "/" . $f) . "<br />";
if ($path_parts['extension'] == "jpg" || $path_parts['extension'] ==
"jpeg" || $path_parts['extension'] == "png")
{
// Make bin folder if not exists
MakeFolder($folder . "/");
// Compress file in folder to bin folder
$d = compress($folder . "/" . $f, $folder . "/bin/" . $f, 30);
// Delete files in base
unlink($folder . "/" . $f);
// Move files from bin to root
rename($folder . "/bin/" . $f, $folder . "/" . $f);
}
}
}
}
}
}
function MakeFolder($path)
{
if (!file_exists($path . "/bin/"))
{
mkdir($path . "/bin/", 0777, true);
}
}
function isImage($var)
{
$path_parts = pathinfo($var);
if (#$path_parts['extension'])
{
if ($path_parts['extension'] == "jpg" || $path_parts['extension'] == "jpeg" || $path_parts
['extension'] == "png")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
function getFilesInDir($path)
{
$directory = $path;
if (is_dir($directory))
{
$files = array();
foreach(scandir($directory) as $file)
{
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
// }
}
}
return $files;
}
function compress($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
?>
scandir only returns the filenames without path. You need to append the path of the original folder to the new one's.
$path = "site/assets/files"
$folders = getFilesInDir($path);
foreach($folders as $folder)
{
$files = getFilesInDir($path . "/" . $folder);
var_dump($files);
Hope this does it.

PHP: How to pass "current $_FILE" to another function after iterate $_FILES global variable?

If I submit a form with multiple files in it, how can I upload each of them after some kind of execution one by one?
Add something like this to your PHP page
//upload image 1
if ($filename1<>"") {
$filename = $filename1;
$file = 'file1';
$temp = explode(".", $_FILES["file1"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image1 = '$newfilename' where yachtid = '$yachtid'");
}
//upload image 2
if ($filename2<>"") {
$filename = $filename2;
$file = 'file2';
$temp = explode(".", $_FILES["file2"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image2 = '$newfilename' where yachtid = '$yachtid'");
}
And then the file called "upload_file.php should look something like this (change the validation sections if you want it to validate on different file names). Also, this renames the file to a random name before saving it to your location);
<?php
$length = 30;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$code = "";
for ($p = 0; $p < $length; $p++) {
$pos = mt_rand(0, strlen($characters)-1);
$code .= $characters{$pos};
}
$parts = explode('.',$filename);
$extension= end($parts);
$newfilename=$code .".".$extension;
$success = 0;
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end($temp);
if ((($_FILES[$file]["type"] == "image/gif") || ($_FILES[$file]["type"] == "image/jpeg") || ($_FILES[$file]["type"] == "image/jpg")
|| ($_FILES[$file]["type"] == "image/pjpeg") || ($_FILES[$file]["type"] == "image/x-png") || ($_FILES[$file]["type"] == "image/png"))
&& ($_FILES[$file]["size"] < 1000000) && in_array($extension, $allowedExts)) {
$filenamepng = "./images/yacht/".$code.".png";
$filenamegif = "./images/yacht/".$code.".gif";
$filenamejpeg = "./images/yacht/".$code.".jpeg";
$filenamejpg = "./images/yacht/".$code.".jpg";
$filenamepjpeg = "./images/yacht/".$code.".pjpeg";
$filenamexpng = "./images/yacht/".$code.".x-png";
if (file_exists($filenamepng)||file_exists($filenamegif)||file_exists($filenamejpeg)||file_exists($filenamejpg)||file_exists($filenamepjpeg)||file_exists($filenamexpng)) {
if (file_exists($filenamepng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.png';
unlink($filename);
}
if (file_exists($filenamegif)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.gif';
unlink($filename);
}
if (file_exists($filenamejpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpeg';
unlink($filename);
}
if (file_exists($filenamejpg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpg';
unlink($filename);
}
if (file_exists($filenamepjpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.pjpeg';
unlink($filename);
}
if (file_exists($filenamexpng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.x-png';
unlink($filename);
}
}
move_uploaded_file($_FILES[$file]["tmp_name"],
"images/yacht/" . $newfilename);
//echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
unset($code);
$success = 1;
}
else
{
$error = "Your image is over 1mb OR is not in an accepted format; gif, jpeg, jpg, pjpeg, x-png, or png. Please try again.";
}
?>
www.clubtray.com
www.clubtray-clubmembershipsoftware.com

move file to new location with new name

I am trying to move an existing image file from a temp folder to a proper location with a proper filename, for some reason it always fails.
function move_temp_image($article_id)
{
global $db, $config;
if (($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.jpg", 'r+')) && ($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.png", 'r+')) && ($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.gif", 'r+')))
{
$this->error_message = "Could not find temp image to load?";
return false;
}
else
{
$image_info = getimagesize($image_load);
$image_type = $image_info[2];
$file_ext = '';
if( $image_type == IMAGETYPE_JPEG )
{
$file_ext = 'jpg';
}
else if( $image_type == IMAGETYPE_GIF )
{
$file_ext = 'gif';
}
else if( $image_type == IMAGETYPE_PNG )
{
$file_ext = 'png';
}
// give the image a random file name
$imagename = rand() . 'id' . $article_id . 'gol.' . $file_ext;
// the actual image
$source = $image_load;
// where to upload to
$target = $_SERVER['DOCUMENT_ROOT'] . "/uploads/articles/topimages/" . $imagename;
if (rename($source, $target))
{
// remove old temp image
if ($image['article_top_image'] == 1)
{
unlink($_SERVER['DOCUMENT_ROOT'] . '/uploads/temp/' . $image_load);
}
unset($_SESSION['temp_tagline']);
$db->sqlquery("UPDATE `articles` SET `article_top_image` = 1, `article_top_image_filename` = ? WHERE `article_id` = ?", array($imagename, $article_id));
return true;
}
else
{
$this->error_message = 'Could not move temp file to tagline uploads folder!';
return false;
}
}
}
I am not sure what I am doing wrong, I read rename is the way to do this, but I am obviously overlooking something.
You don't have the filename in $source - In your code, $source contains a file resource...
rename doesn't work only with file names, so you have to change your code.
i.e. replace your condition with the following code
$types = array('jpg', 'png', 'gif');
$file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.";
$image_load = false;
foreach ($types as $type) {
if (file_exists($file . $type)) {
$image_load = $file . $type;
break;
}
}
if (!file_exists($image_load))

how can I add imaging handling got this script effectively

hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}

Categories