I'm uploading a .PDF and .ZIP file via a HTML form then passing it to my PHP script where the file is moved from the temp folder and placed in a specified folder. Now this works great on files under 2mb, anything over I will get the following error message:
Warning: copy() [function.copy]: Filename cannot be empty
The filename isn't empty and the code works fine for files under 2mb in size.
I checked my php.ini file in /etc/ folder (im running centos6.4) and in its config I have
upload_max_filesize = 50M
I'm thinking this is still a PHP config issue thats causing the error on files over 2mb, is there any other config I need to be looking at?
<?php
session_start();
$ref = $_POST['doc_ref'];
$rev = $_POST['doc_rev'];
$owner = $_POST['doc_owner'];
$contract = $_POST['contract'];
$cat = $_POST['cat'];
$type = $_POST['type'];
$pdf = $_FILES['pdf'];
$zip = $_FILES['zip'];
$pdf_name = $_FILES['pdf']['name'];
$content = $_POST['doc_content'];
$userid = $_SESSION['users_id'];
date_default_timezone_set('UTC');
$date = date_create();
// get the pdf from the form then remove the extension
$title = $_FILES["pdf"]["name"];
$title = pathinfo($title,PATHINFO_FILENAME);
$sth = "SELECT * FROM `contracts` WHERE `contracts_id`='$contract'";
$result = $conn->query($sth);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$contract_name = $row['contracts_name'];
$contract_prefix = $row['prefix'];
}
if ($contract_prefix)
{
if ($type === '1')
{
$zippath = "zips/" . $contract_prefix . "/" . $contract_name . "/Forms/";
$arcpath = "arc/" . $contract_prefix . "/" . $contract_name . "/Forms/";
$pdfpath = "pdfs/" . $contract_prefix . "/" . $contract_name . "/Forms/";
}elseif ($type === '2')
{
$zippath = "zips/" . $contract_prefix . "/" . $contract_name . "/Work Instructions And Process Flows/";
$arcpath = "arc/" . $contract_prefix . "/" . $contract_name . "/Work Instructions And Process Flows/";
$pdfpath = "pdfs/" . $contract_prefix . "/" . $contract_name . "/Work Instructions And Process Flows/";
}
}else
{
if ($type === '1')
{
$zippath = "zips/" . $contract_name . "/Forms/";
$arcpath = "arc/" . $contract_name . "/Forms/";
$pdfpath = "pdfs/" . $contract_name . "/Forms/";
}elseif ($type === '2')
{
$zippath = "zips/" . $contract_name . "/Work Instructions And Process Flows/";
$arcpath = "arc/" . $contract_name . "/Work Instructions And Process Flows/";
$pdfpath = "pdfs/" . $contract_name . "/Work Instructions And Process Flows/";
}
}
$pdfpath = $pdfpath . $_FILES["pdf"]["name"];
$zippath = $zippath . $_FILES["zip"]["name"];
// create archpath to store for later use
$arcpathfinal = $arcpath;
// append the current revision to the start of the zip files name for the arc
$arcpath = $arcpath . "Revision " . $rev . " - " . $_FILES["zip"]["name"];
//check the uploaded file is in PDF format and then move to correct directory
$allowed = array('pdf');
$pdf = $_FILES['pdf']['name'];
$ext = pathinfo($pdf, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'The file type must be a PDF!';
}else
{
// move zip and pdf into correct folders
move_uploaded_file($_FILES["pdf"]["tmp_name"], $pdfpath);
move_uploaded_file($_FILES["zip"]["tmp_name"], $zippath);
}
// make a copy of zip file into arc folder
copy($zippath, $arcpath);
//INSERTING INTO DATABASE CODE HERE
UPDATE
Ok I have been doing a bit of testing, the $_FILES array seems to be empty when the filesize is over 2MB, under 2MB the array returns the name, type, tmp_name, error, size as expected.
What would the reason be the $_FILES is empty with files over 2MB. Yes my upload_max_filesize is set higher than the file size and my post_max_size is set higher than my upload_max_filesize. Yes I have restarted Apache after making changes to the php.ini file
http://www.php.net/manual/en/ini.core.php#ini.post-max-size
Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize.
Related
the following code is saving the converted jpg file to the home directory like where the code is placed i want to store it in a folder namely images.
the file dcm-to-jpg is the file that i am executing on the web browser and then all the functions are being called. basically this is a dicom to jpg converter the solution i want is to save the converted file to a new folder that i have already created and also do let me know how to change the name of the file is that possible too??
Thanks in advance!! :)
Filename = dcm-to-jpg.php
<?PHP
#
# Creates a jpeg and jpeg thumbnail of a DICOM file
#
require_once('../class_dicom.php');
$file = (isset($argv[1]) ? $argv[1] : 'image1.dcm');
if(!$file) {
print "USAGE: ./dcm_to_jpg.php <FILE>\n";
exit;
}
if(!file_exists($file)) {
print "$file: does not exist\n";
exit;
}
$job_start = time();
$d = new dicom_convert;
$d->file = $file;
$d->dcm_to_jpg();
system("ls -lsh $file*");
$job_end = time();
$job_time = $job_end - $job_start;
print "Created JPEG and thumbnail in $job_time seconds.\n";
?>
filename = class_dicom.php
### Convert a DICOM image to JPEG. $this->file is the filename of the image.
### $this->jpg_quality is an optional value (0-100) that'll set the quality of the JPEG produced
function dcm_to_jpg() {
$filesize = 0;
$this->jpg_file = $this->file . '.jpg';
$convert_cmd = BIN_DCMJ2PNM . " +oj +Jq " . $this->jpg_quality . " --use-window 1 \"" . $this->file . "\" \"" . $this->jpg_file . "\"";
$out = Execute($convert_cmd);
if(file_exists($this->jpg_file)) {
$filesize = filesize($this->jpg_file);
}
if($filesize < 1) {
$convert_cmd = BIN_DCMJ2PNM . " +Wm +oj +Jq " . $this->jpg_quality . " \"" . $this->file . "\" \"" . $this->jpg_file . "\"";
$out = Execute($convert_cmd);
}
return($this->jpg_file);
}
?>
I am trying to upload a tmp file and then copy it. But it is not appearing in the second folder, is there an overlay or something I have to watch?
$uploadPath = '/.../..../image/';
$uploadPathpreview = '/.../..../blog/';
if ($counter == 0){
$preview_file = $uploadPath . DS . 'preview_' . date("Ymd-Hi-") . $img_name;
$preview_file_save = $uploadPathpreview . DS . 'preview_' . date("Ymd-Hi-") . $img_name;
if(move_uploaded_file($tmp_name, $preview_file)){
$tmp = $preview_file;
$new = $preview_file_save;
}
copy($tmp,$new);
The file in image exists by the way. And I tried it without the if()
Im having issues with my code being able to open a zip file that i have uploaded and moved into a folder, the zip file uploads fine and you can open it in any Zip program however, when i attempt to open it with ZipArchive to extract the data it errors.
$path = "../"; // Upload directory
$count = 0;
foreach ($_FILES['files']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $name))
$count++; // Number of successfully uploaded file
}
$kioskFile = $_FILES['files']['name'][0];
$kioskFile = explode(".", $kioskFile);
$kioskFile = $kioskFile[0];
$zipFile = "../" . $kioskFile . ".zip";
$zip = new ZipArchive;
$res = $zip->open($zipFile);
if ($res === true) {
$zip->extractTo("./");
$zip->close();
} else {
echo "Error Cannot Open Zip File - Error Code: ";
}
When i run the code it shows me a Error Code 19
ZIPARCHIVE::ER_NOZIP - 19
This is the error im getting, however the file exists and if i use zip_open, it returns that it can open the zip file.
Any help would be very greatful
EDIT1
If i upload a zip file that i manually create (using a zip program) then the upload works fine. However if i use a ZipArchive created zip file, then it instantly errors with a error 19.
EDIT2
I have now added a check to make sure the file exists in the right directory and also put a print of the location also, both match, however still the same issue. Error 19
$path = "../"; // Upload directory
$count = 0;
foreach ($_FILES['files']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $name))
$count++; // Number of successfully uploaded file
}
$kioskFile = $_FILES['files']['name'][0];
$kioskFile = explode(".", $kioskFile);
$kioskFile = $kioskFile[0];
$realpath = realpath("../");
$zipFile = $realpath . "\\" . $kioskFile . ".zip";
if (file_exists($zipFile)) {
$extract = zip_extract($zipFile, "../");
if ($extract === TRUE) {
} else {
echo "The file " . $zipFile . " cannot be opened";
}
} else {
echo "The file " . $zipFile . " does not exist";
die();
}
UPDATE1
So i think ive narrowed it down to either this bit of code, or the download script that i use to download the .zip file from the system, if i leave the zip on the system and use the exact same bit of code it works fine.
Here is my download code, maybe ive missed something on this that is causing the issue.
$fileID = $_GET['id'];
$backupLoc = "backups/";
$sql = "SELECT * FROM backups WHERE id = '" . addslashes($fileID) . "' LIMIT 1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$backupFile = $row['backupFile'];
$zipFile = $backupLoc . "/" . $backupFile . ".zip";
$zipSize = filesize($zipFile);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($zipFile). '"');
ob_end_flush();
readfile($zipFile);
exit;
die();
Open the archive with a text or hex editor and make sure you have the 'PK' signature at the start of the file.
If you have any HTML before that signature, it would suggest that your buffers are not being cleaned or are being flushed when they should not be, meaning that PHP ZipArchive will assume an invalid archive.
It was the download.php file that was causing the issue, here is the solution. which was to do a OB CLEAN rather than a Flush
///echo "<div style='padding: 50px;'>Please Wait .....</div>";
$fileID = $_GET['id'];
$backupLoc = "backups/";
$sql = "SELECT * FROM backups WHERE id = '" . addslashes($fileID) . "' LIMIT 1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$backupFile = $row['backupFile'];
$zipFile = $backupLoc . "/" . $backupFile . ".zip";
$zipSize = filesize($zipFile);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($zipFile). '"');
//ob_end_flush();
ob_end_clean();
readfile($zipFile);
exit;
die();
I am making a web form for teachers where student can submit there assignment and teacher can check. but i am getting error i can not upload the .txt and .doc i am having probelm in my code here is my effort.
error_reporting(E_ALL ^ E_NOTICE);
if ($_POST["upload"] == "1") {
if ((($_FILES['file']['type'] == ".txt") || ($_FILES['file']['type'] == ".doc")) && ($_FILES['file']['size'] > "0")) {
$id = 4881;
$name = "Naeem";
/*first image folder i i showed abd get file and move*/
$fileName = $_FILES["file"]["name"];
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName);
$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
$fileName = $id . "(" . time() . rand() . ")." . $fileExt;
$to = "file/" . $fileName;
/*this step is used to move file from tmp to a folder*/
if (move_uploaded_file($_FILES['file']['tmp_name'], $to)) {
if ($query = mysql_query("INSERT INTO `file` (
`id` ,
`std_id` ,
`std_name` ,
`file_url`
)
VALUES (
NULL , '" . $id . "', '" . $name . "', '" . $to . "'
);"))
{
echo "Uploaded succesfully";
}
}
}
}
You have minor mistake in your code that you have put wrong extension.
if((($_FILES['file']['type']=="text/plain") || ($_FILES['file']['type']=="application/msword"))&&($_FILES['file']['size']>"0"))
It is not .txt and .doc it is text/plain for text files and for .doc it is application/msword.
I hope it will work.
Here is the issue -
(($_FILES['file']['type']==".txt") || ($_FILES['file']['type']==".doc"))
File Extension and MIME Type are not same.
Replace .txt by text/plain And .doc by application/msword.
I this PHP code:
<?php
// Check for errors
if($_FILES['file_upload']['error'] > 0){
die('An error ocurred when uploading.');
}
if(!getimagesize($_FILES['file_upload']['tmp_name'])){
die('Please ensure you are uploading an image.');
}
// Check filesize
if($_FILES['file_upload']['size'] > 500000){
die('File uploaded exceeds maximum upload size.');
}
// Check if the file exists
if(file_exists('upload/' . $_FILES['file_upload']['name'])){
die('File with that name already exists.');
}
// Upload file
if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], 'upload/' . $_FILES['file_upload']['name'])){
die('Error uploading file - check destination is writeable.');
}
die('File uploaded successfully.');
?>
and I need to act like a "windows" kind of treatment for existing files - I mean the if the file exists, i want it to be changed to the name of the file with the number 1 after it.
for example: myfile.jpg is already exists, so if you'll upload it again it will be myfile1.jpg, and if myfile1.jpg exists, it will be myfile11.jpg and so on...
how can i do it? i tried some loops but unfortunately without success.
You could do something like this:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
// add a suffix of '1' to the file name until it no longer conflicts
while(file_exists($name . '.' . $extension)) {
$name .= '1';
}
$basename = $name . '.' . $extension;
To avoid very long names, it would probably be neater to append a number, e.g. file1.jpg, file2.jpg etc:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
$increment = ''; //start with no suffix
while(file_exists($name . $increment . '.' . $extension)) {
$increment++;
}
$basename = $name . $increment . '.' . $extension;
You uploaded a file called demo.png.
You tried to upload the same file demo.png and it got renamed to demo2.png.
When you try to upload demo.png for 3rd time, it gets renamed to demo1.png once again and replaces the file you upload in (2).
so you won't find demo3.png
For user6930268;
i think your code should be:
$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
$dirname = pathinfo($_FILES['file_upload']['name'], PATHINFO_DIRNAME);
$dirname = $dirname. "/";
$increment = ''; //start with no suffix
while(file_exists($dirname . $name . $increment . '.' . $extension)) {
$increment++;
}
$basename = $name . $increment . '.' . $extension;
$resultFilePath = $dirname . $name . $increment . '.' . $extension);
Here is a my function i'm using. It will generate file (1).txt , file (2).txt , file ...
function getFilePathUnique($path) {
while ($this->location->fileExists($path)) {
$info = pathInfo($path);
//extract the current number of file
preg_match("/\([0-9]+\)$/",$info["filename"], $number);
$number = str_replace(["(" , ")"] , ["" , ""] , $number[0]);
//remove the old number
$info["filename"] = trim(preg_replace( "/\([0-9]+\)$/" , "" , $info["filename"] ));
//append new number
$info["filename"] .= " (" . (++$number) . ")";
//build path
$path = ($info["dirname"] != "." ? $info["dirname"]: "" ).
$info["filename"] . "." . $info["extension"];
}
return $path;
}