Error 500 when trying to insert file into a zip - php

I wrote a function to generate a zip file.
See the code below.
This function works fine in wamp with php 7.2.10.
It also worked fine on the web server with php 7.2.18 but a problem occured after upgrading php to version 7.3.5.
The zip file is created, the directory images inside the zip is created, but it crashes with an error 500 when trying to add file to the zip.
Here are the error logs generated
[Fri Oct 09 08:59:43.382099 2020] [fcgid:warn] [pid 22236] (104)Connection reset by peer: [client ] mod_fcgid: error reading data from FastCGI server, referer:
[Fri Oct 09 08:59:43.382149 2020] [core:error] [pid 22236] [client ] End of script output before headers: index.php, referer:
Thanks in advance for your help
function createZIP($source,$destination)
{
$files=scandir($source.'/images',1);
$files= array_diff($files, array('..', '.'));
$zip = new ZipArchive;
$res = $zip->open($destination, ZipArchive::CREATE);
if ($res === TRUE)
{
if($zip->addEmptyDir('images'))
{
foreach ($files as $value)
{
$zip->addFile($source.'/images/'.$value, 'images/'.$value);
}
$zip->addFile($source.'/signature_client_lourd.html', 'signature_client_lourd.html');
$zip->addFile($source.'/signature_client_leger.txt', 'signature_client_leger.txt');
$zip->close();
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}

Related

PHP move_uploaded_file fail to upload file

I have the below PHP code to upload files
$uploadedFile = '';
if(!empty($_FILES["file"]["name"])){
// File path config
$fileName = $_FILES["file"]["name"];
$targetFilePath = 'uploads/'.$fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Allow certain file formats to upload
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
$uploadedFile = $fileName;
$uploadStatus = 1;
}else{
$uploadStatus = 0;
$response['message'] = 'Sorry, there was an error uploading your file.';
}
}else{
$uploadStatus = 0;
$response['message'] = 'Sorry, only '.implode('/', $allowTypes).' files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Insert form data in the database
$sqlInsertFilePath = "insert into soundexercises(filepath) values ('$targetFilePath')";
$resultFilePath = pg_query($cn, $sqlInsertFilePath);
if($resultFilePath){
$response['status'] = 1;
$response['message'] = 'Form data submitted successfully!';
}
}
}else{
$response['message'] = 'Please fill all the mandatory fields.';
I get error
Sorry, there was an error uploading your file.
I check the error.log from my apache and I get the below
2023-01-22 16:19:25 [:error] [pid 18980:tid 140169504040704] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248:35136] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248] ModSecurity: Warning. Match of "rx ^$" against "FILES:file" required. [file "/etc/httpd/conf/modsecurity.d/rules/comodo_free/000_i360_0.conf"] [line "158"] [id "77317957"] [msg "IM360 WAF: Track file upload||File:\\xe8\\x88\\x92\\xe6\\x9c\\x8d shufu.m4a||Size:20084||User:yskapell||SC:/var/www/vhosts/kaiqiaozhi.space/lxxxxxxx/exercises/upload_sound.php||T:APACHE||"] [severity "NOTICE"] [tag "service_i360custom"] [tag "noshow"] [hostname "xxxxxxx"] [uri "/exercises/upload_sound.php"] [unique_id "Y81F7YHZV4SyzQDeQqbhegAAAdM"], referer: https://xxxxxxx/admin/dashboard.php
2023-01-22 16:19:25 [:error] [pid 18980:tid 140169504040704] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248:35136] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248] ModSecurity: Warning. Match of "rx ^$" against "FILES_TMPNAMES:file" required. [file "/etc/httpd/conf/modsecurity.d/rules/comodo_free/000_i360_0.conf"] [line "158"] [id "77317957"] [msg "IM360 WAF: Track file upload||File:/tmp/20230122-161925-Y81F7YHZV4SyzQDeQqbhegAAAdM-file-2buepa||Size:20084||User:yskapell||SC:/var/www/vhosts/kaiqiaozhi.space/xxxxxxx/exercises/upload_sound.php||T:APACHE||"] [severity "NOTICE"] [tag "service_i360custom"] [tag "noshow"] [hostname "xxxxxxx"] [uri "/exercises/upload_sound.php"] [unique_id "Y81F7YHZV4SyzQDeQqbhegAAAdM"], referer: https://xxxxxxx/admin/dashboard.php
2023-01-22 16:19:25 [fcgid:warn] [pid 18980:tid 140169504040704] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248:35136] mod_fcgid: stderr: PHP Warning: move_uploaded_file(uploads/\xe8\x88\x92\xe6\x9c\x8d shufu.m4a): failed to open stream: No such file or directory in /var/www/vhosts/kaiqiaozhi.space/xxxxxxx/exercises/upload_sound.php on line 63, referer: https://xxxxxxx/admin/dashboard.php
2023-01-22 16:19:25 [fcgid:warn] [pid 18980:tid 140169504040704] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248:35136] mod_fcgid: stderr: PHP Warning: move_uploaded_file(): Unable to move '/tmp/phpvatIuu' to 'uploads/\xe8\x88\x92\xe6\x9c\x8d shufu.m4a' in /var/www/vhosts/kaiqiaozhi.space/xxxxxxx/exercises/upload_sound.php on line 63, referer: https://xxxxxxx/admin/dashboard.php
2023-01-22 16:19:25 [:error] [pid 18980:tid 140169504040704] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248:35136] [client 2a02:587:e919:9900:1f9d:65ab:b74b:4248] ModSecurity: Input filter: Failed to rename file from "/tmp/20230122-161925-Y81F7YHZV4SyzQDeQqbhegAAAdM-file-2buepa" to "/var/cache/modsec-upload/20230122-161925-Y81F7YHZV4SyzQDeQqbhegAAAdM-file-2buepa". [hostname "xxxxxxx"] [uri "/exercises/upload_sound.php"] [unique_id "Y81F7YHZV4SyzQDeQqbhegAAAdM"], referer: https://xxxxxxx/dashboard.php
I checked the permission on the upload folder and it's 755 with correct owner.
===UPDATE===
The $_FILES['file']['error'] return 0 .
1:0 {"status":0,"message":"Sorry, there was an error uploading your file.","results":"No results"}
What happens when You provide full absolute path for the $targetFilePath instead of 'uploads/'.$fileName ?
There's also comodo security Modsecurity warning error in Your logs.

PHP copy function works in Red Hat 5 but not in Red Hat 7 to copy files to a remote samba share directory

function check_readwrite($_mnt, &$Status)
{
$t = "Checking to see if we can write to the queue...<br>";
$retval = #copy("/etc/fstab",$_mnt . "testfile.part");
if($retval == 1)
{
$t .= "<font color='blue'>Copying of test file to queue succeeded.</font><br><br>";
} else {
$errors= error_get_last();
$t .= "COPY ERROR TYPE: ".$errors['type'] . "<br>";
$t .= " ERROR MESSAGE: ".$errors['message'] . "<br>";
$t .= "<font color='red'>Failed to copy test file to this queue.</font><br><br>";
$Status = 0;
}
$t .= "Checking to see if we can delete from the queue...<br>";
$retval = #unlink($_mnt . "testfile.part");
if($retval == 1)
{
$t .= "<font color='blue'>Deleting of test file from queue succeeded.</font><br><br>";
$Status = 1;
} else {
$t .= "<font color='red'>Failed to delete test file from this queue.</font><br><br>";
$Status = 0;
}
return $t;
}
The check_readwrite function shown above works successfully on Red Hat 5 but fails on Red Hat 7 with
the 'Permission denied' error message shown below. When executing the function the testfile.part file shows up on
the Samba Remote Host but the filesize is 0. The unlink to delete the file works successfully.
LOCAL HOST: Red Hat Enterprise Linux Server release 7.2 (Maipo) with php 7
---------- samba share ----------> BEGIN
drwxrwxrwx 2 faciledi faciledi 0 Aug 11 14:35 10.231.250.147_smbinput
drwxrwxrwx 2 faciledi faciledi 0 Aug 10 16:50 10.231.250.147_smboutput
lrwxrwxrwx 1 apache apache 51 Aug 11 14:34 smbinput -> /usr/local/queues/10.231.250.147_smbinput//
lrwxrwxrwx 1 apache apache 52 Aug 10 16:42 smboutput -> /usr/local/queues/10.231.250.147_smboutput//
---------- samba share ----------> END
Manual copy of a test file to the local host samba share directory:
sudo -u apache cp /etc/fstab /usr/local/queues/smbinput/testfile.part
sudo -u faciledi cp /etc/fstab /usr/local/queues/smbinput/testfile.part
SAMBA REMOTE HOST: The fstab file is successfully copied to the remote host using the manual steps above
/usr/local/smbinput/testfile.part
---------- check_readwrite function output ----------> BEGIN
Checking to see if we can write to the queue...
COPY ERROR TYPE: 2
ERROR MESSAGE: copy(/usr/local/queues/smbinput/testfile.part): failed to open stream: Permission denied
Failed to copy test file to this queue.
Checking to see if we can delete from the queue...
Deleting of test file from queue succeeded.
---------- check_readwrite function output ----------> END

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;
}

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);

uploading multiple pictures causeing 500 error

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.)

Categories