uploading multiple pictures causeing 500 error - php

I modified a script i found on here to do process multiple pictures being uploaded at once. However when I try to run the script it throws an error. I use to have the script only allow one picture upload at time and that worked fine without any issue.
Here is my code.
Function uploadMultiple(){
$config = array(
'allowed_types' => 'jpg|png|jpeg|gif',
'upload_path' => $this->board_path,
'overwrite' => false,
//'file_name' => $fileName
);
//print_r($config);
$this->load->library('upload');
$errorCount = 0;
$results = array(
'errorsPresent' => false,
);
$successCount = 0;
//for each image...try to upload. if it fails, add it to the error list.
//keep a list of successful uploads.
print_r($_FILES);
for ($i = 0; $i<count($_FILES); $i++){
echo 'here';
$_FILES['userfile']['name'] = $_FILES['userfile' . $i]['name'];
$_FILES['userfile']['type'] = $_FILES['userfile' . $i]['type'];
$_FILES['userfile']['tmp_name'] = $_FILES['userfile' . $i]['tmp_name'];
$_FILES['userfile']['error'] = $_FILES['userfile' . $i]['error'];
$_FILES['userfile']['size'] = $_FILES['userfile' . $i]['size'];
$config['file_name'] = 'img_' . time() . '.png'; //inserts the unix time into the file name.
$config['upload_path'] = $this->board_path;
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
if ( ! $this->upload->do_upload()){
$results['errorsPresent'] = true;
$results['error'][$errorCount] = $this->upload->display_errors();
$errorCount ++;
} else {
$data = array('upload_data' => $this->upload->data());
$pictureData = $this->upload->data();
$file_location = $pictureData['full_path'];
$file_location = substr($file_location, 18);//this should probably be dynamic...
$file_location = $this->db->escape($file_location);
$results['success'][$successCount] = $file_location;
chmod($pictureData['full_path'], 777); //don't need to give it execute permissions but oh well.
$successCount ++;
}
}
return $results;
}
Here is the 500 error.
Internal Server Error
The server encountered an internal
error or misconfiguration and was
unable to complete your request.
Please contact the server
administrator, webmaster#localhost and
inform them of the time the error
occurred, and anything you might have
done that may have caused the error.
More information about this error may
be available in the server error log.
Additionally, a 500 Internal Server
Error error was encountered while
trying to use an ErrorDocument to
handle the request.
This is what the apache log file says:
[Wed Mar 23 02:29:41 2011] [error] [client 129.21.129.32] ModSecurity: Access denied with code 500 (phase 4). Pattern match "(?:\b(?:(?:s(?:elect list because it is not contained in (?:an aggregate function and there is no|either an aggregate function or the) GROUP BY clause|upplied argument is not a valid (?:(?:M(?:S |y)|Postgre)SQL|O(?:racle|DBC)))|S(?:yntax error converti ..." at RESPONSE_BODY. [file "/etc/apache2/conf.d/modsecurity/modsecurity_crs_50_outbound.conf"] [line "23"] [id "970003"] [msg "SQL Information Leakage"] [severity "WARNING"] [tag "LEAKAGE/ERRORS"] [hostname "hostname.com"] [uri "/longboard/index.php/board/add"] [unique_id "TYmTVYEVgWYAAASKoIcAAAAJ"]
Based on the error message I think modsecurity is blocking the script for some reason but i'm not sure why. Any insight would be greatly appreciated.
Thanks

try disabling mod_security ,
in .htaccess add this
SecFilterEngine Off

It ended up being a database error. Mod_security was blocking the error message. I went into the mod_security log file and found which rule was causing it to throw the 500 error. I then went into the file with that rule and commented it out. I restarted apache and retested and then the database error showed. I'm thinking of leaving this rule commented out since this is a development server. (It does broadcast to the whole world though, and the reason I have Mod_security installed.)

Related

escapeshellarg() has been disabled for security reasons. Added '#' still not working

I have searched through the community and found that adding :
$cmd = 'file --brief --mime ' . #escapeshellarg($file['tmp_name']) .
might solve the issue but it has not.
I am trying to upload a file in Codeginter PHP.
I have developed an application that works fine on my local machine, I was able to upload files but then I moved it to live server.
Now I am getting an error :
A PHP Error was encountered
Severity: Warning
Message: escapeshellarg() has been disabled for security reasons
Filename: libraries/Upload.php
Line Number: 1039
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by (output started at /home/primeasp/public_html/bizlnps_prov/system/core/Exceptions.php:186)
Filename: helpers/url_helper.php
Line Number: 543
But it has not so I have posted here.
Why am I getting this error? And how will i be able to solve it?
Code:
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('customer/upload/upload_ini', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$id = $this->session->userdata('id');
foreach ($data as $row)
{
$file_name = $row['file_name'];
$file_path = $row['file_path'];
}
$site = $this->session->userdata('site');
$insert_data = array(
'customer_id' => $id,
'base_ini_filename' => $file_name,
'file_path'=>$file_path,
'site_key'=>$site
);
$this->db->insert('base_ini', $insert_data);
redirect('customer/upload_ini/index');
$this->data['subview'] = 'customer/upload/upload_success';
$this->load->view('customer/_layout_main', $this->data);
}
The host has disabled the escapeshellarg function. Using # in front of a function suppresses an error, it doesn't mean the function will actually work after adding it.
Either find a host that will allow this function or purchase dedicated resources such as a VPS / Dedicated server where you can install your own version of PHP and chose the functions that you wish to enable.
escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument.
That's simple enough to do yourself since its blocked on your host.
$cmd = "file --brief --mime '" . str_replace("'","\'",$file['tmp_name']). "'";
Fiddle

Tuleap Docman Permission Denied

Earlier today I installed Tuleap like instructed on CentOS 6.7.
Most of it works, but when I try to add a document with the DocumentManager, I get the following error: Error while creating initial version.
I looked into the log files of httpd [Sun Jan 03 16:45:36 2016] [error] [client 192.168.99.6] PHP Warning: mkdir():$Permission denied in /usr/share/tuleap/plugins/docman/include/Docman_FileStorage.class.php on line 112, referer: (domain)/plugins/docman/?group_id=101$
I now know that it is a permission problem, but I do not know where these files are being stored and how to get the permissions right. Does anyone can give me a direction on where to look?
Thank you in advance!
Solved.
When closely observed inside the httpd error log, it stated that it wanted to put the file in the root directory. Of course this isn't permitted. Therefore, it was needed to change the filepath that is created automatically by Domcman.
I found the Docman_FileStorage.class.php file that is causing the automatic path creation inside /usr/share/tuleap/plugins/docman/include and edited the getPath function/variable $path to /var/lib/tuleap/docman, so it would have the correct path.
For the complete edited function, see below:
*/
function _getPath($name, $group_id, $item_id, $version_number) {
$name = preg_replace('`[^a-z0-9_-]`i', '_', $name);
$name = preg_replace('`_{2,}`', '_', $name);
$hash1 = $item_id % 10;
$hash2 = ( ($item_id - $hash1) / 10) % 10;
$path_elements = array($this->root, $this->_getGroupName($group_id), $hash2, $hash1, $item_id, $version_number);
$path = '/var/lib/tuleap/docman';
foreach($path_elements as $elem) {
$path .= $elem .'/';
if (!is_dir($path)) {
mkdir($path, 0700);
}
}
$path .= $name;
return $path;
}

File upload / move temp not working on nginx

So, i've read this question about move_uploaded_file() problems. However, on my apache-powered localhost lamp stack, its working just fine. So i think it may be a filesystem / path thing, and not a code thing.
when uploading files to my site locally, it works.
but when I'm on the QA server (which is nginx powered), i get this error:
2012/09/08 15:34:21 [error] 11794#0: *5187 FastCGI sent in stderr: "files not empty
PHP Warning: move_uploaded_file(/var/www/qa.mysite.com/mysite/app/files/maps-aprilfools.tiff): failed to open stream: No such file or directory in /var/www/qa.mysite.com/mysite/app/models/files.php on line 516
PHP Warning: move_uploaded_file(): Unable to move '/tmp/phpvdtznP' to '/var/www/qa.mysite.com/mysite/app/files/maps-aprilfools.tiff' in /var/www/qa.mysite.com/mysite/app/models/files.php on line 516" while reading response header from upstream, client: 72.xxx.xxx.xxx, server: qa.mysite.com, request: "POST /projects/3/files HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "qa.mysite.com", referrer: "http://qa.mysite.com/projects/3/files"
and this is the code that I wrote to handle uploading a file:
public function fileUploadToProject( $project_id ) {
if ($_FILES["upload-file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
} else {
$dbSuccess = false;
$tmp_name = $_FILES["upload-file"]["tmp_name"];
$name = $_FILES["upload-file"]["name"]; // someFile.ext
$size = $_FILES['upload-file']['size']; //size in bytes
$mime = $_FILES['upload-file']['type']; //size in bytes
$destination = __FILES__.'/'.$name;
$uploaded = move_uploaded_file( $tmp_name, $destination );
// add entry to database.
/*
* null because there is no container yet.
* We're only uploading to local
*/
$user_container_name = null;
$uploaded_by = LoggedInUser::get_user_id();
/*
* Set this 1 when we're not dealing with our external fileserver
*/
$isLocal = 1;
/*
* Probably shouldn't do this forever for storage size reasons, but for now its useful.
*/
$localPath = $destination;
$task_id = null;
if( $uploaded ) {
$dbSuccess = $this->insertFileRefService( $task_id,
$project_id,
$user_container_name,
$name,
$mime,
$size,
$uploaded_by,
$isLocal,
$localPath
);
if($dbSuccess) {
return true;
} else {
// should I rollback / delete that file?
return false;
}
} else {
return false;
}
}
}
So, is there anything I should know about moving temp files to my filesystem with on nginx? or do you think it is simply a path problem? code problem?
Also, please note that line 516 is this: $uploaded = move_uploaded_file( $tmp_name, $destination );
The folder had problems with permissions, among other things.
the /files directory in that path actually doesn't exist. I somehow never realized that the folder simply wasn't there. Whoops.
then, i had to determine what user was used by nginx to execute php:
ps aux | grep "nginx"
then i had to chown the files directory:
chown -R root:userFromStep1 files
then i had to chmod the directory:
chmod g+w files
that worked like a charm.
Can please try with giving the exact path instead of using the __FILES__. Because it'll not be nginx problem. it will be path problem only

Write binary file in PHP

I have wrote a PHP file which will save a JPEG file in the server and part of the code is listed as follow:
//create folder if folder not exist
if (!is_dir($save_path)){
$old = umask(0);
$flag = #mkdir($save_path,0777);
umask($old);
if(isset($flag)){
$string = 'Folder Create Success!'."\n";
}else{
$string= 'Folder Create Fail!'."\n";
}
echo $string;
}else{
echo "Folder exist!!!!";
}
//write the content to the server
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: image/jpg; charset=utf-8');
if(!$file = fopen($path, 'wb')){
echo 'Image upload Fail!'."\n";
return;
}
else
{
fwrite($file, $binary);
fclose($file);
}
The problem is when I run the code, if the folder does not exist, it create the folder only but the content can't save in the folder. The error message is :
[Thu Jul 05 16:59:06 2012] [error] [client 10.95.61.220] PHP Warning: fopen(/mnt/csis/upload/newphoto/others/12346_test/12346_test_2012-07-05_others_abc.jpg): failed to open stream: Permission denied in /var/www/html/upload_image.php on line 57
However, if I run the code again, since the folder was created in the past, it work properly. The content can save in the folder......
Anything I get wrong? I try to find the answer on the web but still can't solve the problem.
Anyone can help, many thanks!
I would try changing the creation of the folder to use the recursive flag:
$flag = #mkdir($save_path . "/" . $file,0777,true);

PHP upload form doesn't accept .pdf

For some reason, my PHP-upload field doesn't accept pdf-files. I don't get it cause I thought there is no selection made while uploading the file... Any advice?
$name = $_FILES["uploadedfile"]["name"];
$tmp_name = $_FILES["uploadedfile"]["tmp_name"];
$add = "downloads/lkverslagen/".$name;
move_uploaded_file($tmp_name, $add);
if(file_exists("downloads/lkverslagen/$name")) {
$lkverslag = new LKverslag();
$jaar = date (Y);
$lkverslag->titel = $titel;
$lkverslag->datum = $datecorrect;
$lkverslag->link = $name;
$lkverslag->jaar = $jaar;
$lkverslag->auteur = $_SESSION['user']['naam'];
$lkverslag->teller = $_POST['titel'];
if ($lkverslag->saveverslag($_DB)) {
$feedback = "OK";
} else {
$feedback = "NOT OK";
}
} else {
$feedback = "ERROR";
}
Here are some things to check:
Ensure that your file upload and post limits are not reached by editing upload_max_filesize and post_max_size in your .htaccess or php.ini file. If you have error reporting on, you should see an error when they're reached. See this: http://drupal.org/node/97193
Check for file upload error codes. See the documentation for these: http://www.php.net/manual/en/features.file-upload.errors.php
Ensure that your memory_limit has not been reached. Again, with error logging enabled, you should receive an error message about this. http://drupal.org/node/207036
Check PHP's common pitfalls documentation and make sure there's nothing there that helps: http://www.php.net/manual/en/features.file-upload.common-pitfalls.php
If none of this helps, enable error reporting and post what you receive so we can tailor our answers better to your situation.
So, to repeat my comment: there are limits on the allowed size of uploaded files -- the PDF file might simply be too large.

Categories