I am trying out PHP my first actual script, most of it from tutorial :(
Anyway's
I am having a problem on this part
// This is our limit file type condition
if (!($uploaded_type=="text/java")||!($uploaded_type=="file/class")||!($uploaded_type=="file/jar")) {
echo "You may only upload Java files.<br>";
$ok=0;
}
Basically it doesn't allow any files, even those up there
help!
I want the Java files to be allowed only!
EDIT:
Here is the full code
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$uploaded = basename( $_FILES['uploaded']['name']) ;
$ok=1;
//This is our size condition
if ($uploaded_size > 350000) {
echo "Your file is too large.<br>";
$ok=0;
}
// This is our limit file type condition
if (!($uploaded_type=="text/java")||!($uploaded_type=="file/class")||! ($uploaded_type=="file/jar")) {
echo "You may only upload Java files.<br>";
$ok=0;
}
echo $ok; //Here we check that $ok was not set to 0 by an error
if ($ok==0) {
echo "Sorry your file was not uploaded";
}else {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {
echo "The file ". $uploaded ." has been uploaded";
} else {
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You're using an OR... that means the whole statement evaluates as TRUE if ANY of its member arguments are true. Since a file can only be of one type, you're excluding ALL files. What you want is an 'and' match:
if (!($uploaded_type == 'text/java') && !($uploaded_type == ....)) {
^^---boolean and
Pretending that we're working with a file/class file type, then you version reads:
if the (file is not text/java) OR the (file is not file/class) OR the (file is not file/jar)
TRUE FALSE TRUE
TRUE or FALSE or TRUE -> TRUE
Switchign to AND gives you
TRUE and FALSE and TRUE -> FALSE
Only one of your three conditions could possibly be true, so that you end up with:
if (!false || !false || !true)
Which becomes:
if (true || true || false)
So you should either use an && in place of the OR, or use a nicer function to check for multiple things from a set:
if (!in_array($uploaded_type, array("text/java", "file/class","file/jar")) {
So the if will succeed if neither of the allowed values is found.
You can make this more flexible using in_array():
$allowed_types = array("text/java", "file/class", "file/jar");
if(!in_array($uploaded_type, $allowed_types)) {
echo "You're not allowed to upload this kind of file.<br />";
$ok = 0;
}
This makes it very easy to allow more file types later on. If you want to allow "text/html", you just need to add it to the array and do not need to create so many checks. You could even store the allowed types in a config file or a table in a database and create the array $allowed_types dynamically.
For client file format limit, refer to this Limit file format when using ?
<input type="file" accept="image/*" /> <!-- all image types -->
<input type="file" accept="audio/*" /> <!-- all audio types -->
For server, you can filter the uploaded file by this,
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;
}
Related
Code
if(is_array($_FILES) && isset($_FILES['photography_attachment'])) {
if(is_uploaded_file($_FILES['photography_attachment']['tmp_name'])) {
$fileName = $_FILES["photography_attachment"]["name"]; // The file name
$fileTmpLoc = $_FILES["photography_attachment"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["photography_attachment"]["type"]; // The type of file it is
$fileSize = $_FILES["photography_attachment"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["photography_attachment"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
$error = $error."<p>Please browse for a file before clicking the upload button.</p>";
} else if($fileSize > 10485760) { // if file size is larger than 2 Megabytes
$error = $error."<p><span>Your file was larger than</span> 10 <span>Megabytes in size</span>.</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if (!preg_match("/.(gif|jpg|png|jpeg)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
$error = $error."<p>Your file was not .gif, .jpg, .png</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
$error = $error."<p>An error occured while processing the file. Try again.</p>";
}
}else{ $error = "Please try again !!!"; }
}else{ $error = "Attachment field cannot be blank!"; }
Always goto "Please try again !!!" else while uploading image in windows, but it worked well in linux system.
Can you please any one help me for this issue?
On windows platforms you musst replace inside the file path the "\" with an "/"
Like this:
$file = str_replace ("\\", "/", $_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
Or use the php build in method, for all systems:
$file = realpath($_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
the following piece of code recognizes the image through getimagesize() but then when i try to move the file to an uploaded folder it moves the file there but says it's an array? im confused because im not setting any variables as an array?
<?php
//simple image check using getimagesize() instead of extensions
if($_FILES){
$empty_check = getimagesize($_FILES['file']['tmp_name']);
if(empty($empty_check)){
echo 'this is not an image';
}
else{
echo 'you have uploaded ' . explode('.',$_FILES['file']['name'])[0].'
and it is a ' . explode('.',$_FILES['file']['name'])[1].'.';
//an example of how i would extract the extension
$target = "C:\\xampp\\htdocs";
move_uploaded_file($_FILES['file']['tmp_name'], $target.'\\'.$_FILES['file']);
}
}
?>
$_FILES['file']
is an array, you're trying to use it as the target filename;
comment of deceze.
Echo the file you want to move/save, then you should see what he mentioned..
When using move_uploaded_file you get to pick the filename, so you can pick anything you want.
When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.
Use this coding for multiple file uploading....
//For Multiple file uploading
if (isset($_FILES['photo']) != "") {
$errors = array();
foreach($_FILES['photo']['tmp_name'] as $key = > $tmp_name) {
$file_name = $_FILES['photo']['name'][$key];
$file_size = $_FILES['photo']['size'][$key];
$file_tmp = $_FILES['photo']['tmp_name'][$key];
$file_type = $_FILES['photo']['type'][$key];
//change the image extension as png
$fileExt = "png";
$photorename[$key] = strtolower($property_code.
'_'.$key.
'.'.$fileExt);
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
//Path of Uploading file
$target = "images_property";
if (empty($errors) == true) {
if (is_dir($target) == false) {
mkdir("$target", 0700); // Create directory if it does not exist
}
if (file_exists("$target/".$photorename[$key])) {
unlink("$target/".$photorename[$key]);
}
move_uploaded_file($file_tmp, "$target/".$photorename[$key]);
} else {
print_r($errors);
}
}
if (empty($errors)) {
echo "Success";
}
}
I've been making an image uploader and I'm having a couple of issues.
Code is so simple: it gets a file (zip file) froom a form and a couple of info text, then generates an url if it isn't exists previously and then extracts the file there.
First one is, that the form variables ($_post["serie"] and $_POST["capitulo"] seems to expire if the file is large and take some time to upload.
Second one is that it tends to fail when uploading not jpg stuff >< and don't know why.
Thanks for your efforts in advance.
<?php
require_once('pclzip.lib.php');
function preextract($p_event, &$p_header) {
$info = pathinfo($p_header['filename']);
if ($info['extension'] == 'gif' || $info['extension'] == 'jpg' || $info['extension'] == 'png' || $info['extension'] == 'jpeg') {
return 1;
} else {
return 0;
}
}
if(is_uploaded_file($_FILES['file']['tmp_name'])) {
echo $_FILES['file']['tmp_name'];
}
$archive = new PclZip($_FILES['file']['tmp_name']);
$extractpath = "../series/" . $_POST["serie"] . "/" . $_POST["capitulo"];
echo $extractpath;
if (file_exists($extractpath)) {
} else {
mkdir($extractpath, 0755);
}
if (($archive->extract(PCLZIP_OPT_PATH, $extractpath, PCLZIP_CB_PRE_EXTRACT, 'preextract') == 0)) {
echo "\n error in extraction";
} else {
echo "\n done";
}
?>
A few things...
You need to increase the max filesize to submit larger files:
ini_set( 'upload_max_filesize', '100M' );
ini_set( 'post_max_size', '100M' );
Change your file_exists check:
if ( !file_exists( $extractpath ) )
mkdir( $extractpath, 0755 );
Change your extension check:
return in_array( $info['extension'], array( 'png', 'jpg', 'jpeg', 'gif' ) ) ? 1 : 0;
I'm not sure why it only works on one extension, maybe PclZip has a setting prohibiting certain files, so look for that.
I have a simple PHP upload script I have started. I am not the best to PHP. Just looking for some suggestions.
I want to limit my script to only .JPG, .JPEG, .GIF and .PNG
Is this possible?
<?php
/*
Temp Uploader
*/
# vars
$mx=rand();
$advid=$_REQUEST["advid"];
$hash=md5(rand);
# create our temp dir
mkdir("./uploads/tempads/".$advid."/".$mx."/".$hash."/", 0777, true);
# upload dir
$uploaddir = './uploads/tempads/'.$advid.'/'.$mx.'/'.$hash.'/';
$file = $uploaddir . basename($_FILES['file']['name']);
// I was thinking of a large IF STATEMENT HERE ..
# upload the file
if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
$result = 1;
} else {
$result = 0;
}
sleep(10);
echo $result;
?>
Yes, quite easily. But first off, you need some extra bits:
// never assume the upload succeeded
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['file']['error']);
}
$info = getimagesize($_FILES['file']['tmp_name']);
if ($info === FALSE) {
die("Unable to determine image type of uploaded file");
}
if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
die("Not a gif/jpeg/png");
}
Relevant docs: file upload errors, getimagesize and image constants.
File path isn't necessarily the best way to check if an image really is an image. I could take a malicious javascript file, rename it to have the .jpg extension, and upload it. Now when you try to display it in your website, I may have just compromised your site.
Here is a function to validate it really is an image:
<?php
function isImage($img){
return (bool)getimagesize($img);
}
?>
try this:
<?php
function isimage(){
$type=$_FILES['my-image']['type'];
$extensions=array('image/jpg','image/jpe','image/jpeg','image/jfif','image/png','image/bmp','image/dib','image/gif');
if(in_array($type, $extensions)){
return true;
}
else
{
return false;
}
}
if(isimage()){
//do codes..
}
?>
Or take a look at: http://php.net/manual/en/function.pathinfo.php
if (substr($_FILES["fieldName"]["name"], strlen($_FILES["fieldName"]["name"])-4) == ".jpg")
{
if(move_uploaded_file($_FILES["fieldName"]["tmp_name"],$path."/".$_FILES['fieldName']['name']))
{
echo "image sucessfully uploaded!";
}
}
similarly you can check for other image formats too.
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;
}