Hi I am attempting to create a new zip file, I have recompiled PHP enabling ZIP and here is my code
if($_SERVER['REQUEST_METHOD'] == "POST"){
$zip = new ZipArchive;
if($zip->open("/home/user1joe/public_html/upload/test.zip",ZIPARCHIVE::CREATE)!= true) {
echo "error file did not up upload";
exit(0);
}
foreach ($_FILES["images"]["error"] as $key => $error)
if ($error == UPLOAD_ERR_OK) {
$temp_name = $_FILES["images"]["tmp_name"][$key];
$new_name = $_FILES['images']['name'][$key];
var_dump($temp_name);
var_dump($new_name);
if(file_exists($temp_name)){
$zip->addFile($temp_name,$new_name);
move_uploaded_file($temp_name, "upload/".$new_name);
} else
echo "error file does not exist";
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
}
$res = $zip->close();
var_dump($res);
}
$zip->close() is returning false and no zip is being created.
I get no errors building up to this
$zip->numFiles shows there are files in the archive
The folder where I want to create the zip has writable permission
I am a bit lost of what else I can test for, any ideas would be great!
zip->close() method do some processing (actual compression, or just getting/writing file attributes), which require that files, added to archive, to exist.
However you are removing input files from the original location with move_uploaded_file() call.
Related
I am having some trouble with a PHP script. I am trying to do two things:
Create an XML file in /usr/local/ezreplay/data/XML/ directory and add contents to it using inputs passed to it from a HTML form;
Upload a PCAP file which is included in the submitted HTML form.
Here is my PHP (apologies it is a little long but I believe all of it is relevant here):
<?php
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm/dd/yyyy' string using 'date'
$expirydate = date('m/d/Y', $timestamp);
}
// Check if all required POST variables are set
if ( isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($expirydate) && isset($_POST['multiplier']) && isset($_POST['pcap']) ) {
// Set the path for the XML file
$path = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . $expirydate . ':' . trim($_POST['multiplier']) . ':' . trim($_POST['pcap']) . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Open the XML file in append mode
if ( $fh = fopen($path,"a+") ) {
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if ( trim( $_POST['destinationip'] ) != "" && trim( $_POST['destinationport'] ) != "" ) {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if ( trim( $_POST['multiplier'] ) != "" ) {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if ( trim( $_POST['pcap'] ) != "" ) {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_POST['pcap'] . '</pcap>';
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
}
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if ( fwrite( $fh, $contents ) ) {
// Success
} else {
echo "The XML config could not be created";
}
// Close the file
fclose($fh);
}
}
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
// Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>
Now the file upload is working and I can see the final echo message being returned in my browser however the XML file is never created. I have changed the directory ownership to the apache user and even chmod 777 to eliminate any permissions issues but it still doesn't create the file.
Any ideas why this is not working? The PHP and apache error logs don't show any issues and as I mentioned the script seems to be working to a degree as the file upload takes place perfectly.
Thanks!
I think the file is not being created due to "/" in the filename. As mentioned at Allowed characters in filename
I managed to fix this with the following edits.
<?php
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
//Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm-dd-yyyy' string using 'date'
$expirydate = date('m-d-Y', $timestamp);
}
// Check if 'destinationip', 'destinationport', 'multiplier' and 'pcap' required POST variables are set
if (isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($_POST['multiplier'])) {
// Set the filename and path for the XML file
$file = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . trim($_POST['multiplier']) . ':' . $expirydate . ':' . $_FILES["pcap"]["name"] . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if (trim($_POST['destinationip']) != "" && trim($_POST['destinationport']) != "") {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if (trim($_POST['multiplier']) != "") {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if (trim($_FILES["pcap"]["name"]) != "") {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_FILES["pcap"]["name"] . '</pcap>';
}
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if (file_put_contents($file, $contents)) {
// Success
} else {
echo "The XML config could not be created";
}
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>
The following PHP file creates a ZIP File and works as it should.
<?php
$zip = new ZipArchive();
$ZIP_name = "./path/Prefix_" .$date . ".zip";
if ($zip->open($ZIP_name, ZipArchive::CREATE)!==TRUE) {
exit("There is a ZIP Error");
}
if ($zip->open($ZIP_name, ZipArchive::CREATE)==TRUE) {
echo "ZIP File can be created" . "<br>";
}
foreach($list as $element) {
$path_and_filename = "../path_to_somewhere/product_"
. $element
. ".csv";
$zip->addFile($path_and_filename, basename($path_and_filename));
}
echo "numfiles: " . $zip->numFiles . "\n"; // number of element files
echo "status:" . $zip->status . "\n"; // Status "0" = okay
$zip->close();
?>
There is only a small blemish:
The above foreach-loop retrieves elements from an array where all elements are sorted in alphabetical order. After the ZIP-File creation, the files within the ZIP are in different order, maybe caused by different file size.
Is there a way to sort the csv files within the ZIP with PHP later on? I'm new to ZIP creation with PHP an I have not found something helpful in the documentation.
You can't do that, better just sort the file list in your program, not in the file system (-;
I am trying to move one image to new folder move_uploaded_file is returning 1 but the file is missing, I am working on localhost with XAMPP
$name = basename($_FILES['arr']['name'][0]);
move_uploaded_file($_FILES['arr']['tmp_name'][0],"\Images");
$name = basename($_FILES['arr']['name'][0]);
move_uploaded_file($_FILES['arr']['tmp_name'][0],'/images/' . $filename);
You have to add a destination for the file to go, including the filename that you wish to assign to it.
Refer to: http://php.net/manual/en/function.move-uploaded-file.php
You should specify the destination file name
if ( move_uploaded_file($_FILES['arr']['tmp_name'],dirname(__FILE__) . '/images/' . $_FILES['arr']['name'] ) ) {
echo "file uploaded";
} else {
echo "error in uploading";
}
Hi, I have a problem with uploading files in my server. This is my code:
<?php
session_start();
$user=$_SESSION['user_level'];
Check if a file has been uploaded
if(isset($_FILES['fileToUpload'])) {
// Make sure the file was sent without errors
if($_FILES['fileToUpload']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('$host', '$username', '$pass', '$tbl_name');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
//$id= mysql_insert_id();
$name = $dbLink->real_escape_string($_FILES['fileToUpload']['name']);
$mime = $dbLink->real_escape_string($_FILES['fileToUpload']['type']);
$data = $dbLink->real_escape_string
(file_get_contents($_FILES['fileToUpload']['tmp_name']));
$size = intval($_FILES['fileToUpload']['size']);
// Create the SQL query
$query = "
INSERT INTO files (email,name,type,size,content)
VALUES ('$user','$name', '$mime', $size, '$data')";
// Execute the query
$result = $dbLink->query($query);}}
?>
<?php
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]);
?>
<?php
if ($_FILES["fileToUpload"]["error"] > 0)
{
echo "Apologies, an error has occurred.";
echo "Error Code: " . $_FILES["fileToUpload"]["error"];
}
else
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]
["name"]);
}
if (($_FILES["fileToUpload"]["type"] == "image/DOC")
|| ($_FILES["fileToUpload"]["type"] == "image/jpeg")
|| ($_FILES["fileToUpload"]["type"] == "image/png" )
&& ($_FILES["fileToUpload"]["size"] < 10000))
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]);
ECHO "Files Uploaded Succesfully";
echo'<script type="text/javascript">
window.location.href ="resume2.php"
</script>';
}
else
{
}
echo "Your Resume was Successfully Upload";
?>
I have a folder named "upload" wherein it will store all the files uploaded by the user. My objective is to store the file in mysql and in the "upload" folder. The storing of file works fine with no error messages but I can't see the uploaded file inside the "upload" folder. Thanks for your help!
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]
You are missing a trailing slash / after upload. Change it to:
"/home/u152912911/public_html/upload/" . $_FILES["fileToUpload"]["name"]
As it is, the file is being saved as a file name with the prefix upload in the public_html directory.
If possible you should use a relative path for portability, there is a good chance that simply
"upload/" . $_FILES["fileToUpload"]["name"]
...would suffice.
HOWEVER
you should not be using $_FILES["fileToUpload"]["name"] directly like this. Consider what would happen if the user sent the string ../index.php as the file name - the user would be able to overwrite your index.php file. Also, consider what would happen if two users uploaded a file named picture.jpg - the second upload would overwrite the first.
Instead you should use a name for the file that you create yourself - it is not safe to rely on user input like this.
You forget a slash:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]);
should be
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload/" . $_FILES["fileToUpload"]["name"]);
Also, check the return value for succes, don't assume it.
Please check the permission provided to the folder where you are storing the files.
if its working fine on local host and giving problem in online testing then ask the server-host to change the folder permissions to 777.
I have a php script that sends large files via FTP. After the file is sent I'm trying to write to the browser "success". I'm also trying to send a query to the database to record that the file was sent. However, any code that I have that comes after the ftp_put does not get executed.
if (ftp_put($conn_id, $upload_filename, $filename, FTP_BINARY))
{
echo "File Sent";
echo $upload_filename." - ".date("d/m/Y H:i:s")." - ".filesize($filename)." bytes<br>" ;
}
else
{
echo "Problem while Uploading $filename\n <br/>". $upload_filename ;
}
If ftp_put is false the echo works. But, if the ftp_put is a success any code I put there will not run.
The file size I am sending is 7,305kb
It is likely that the problem here is that your script is timing out while the file is uploading. Try adding this line before the code above:
set_time_limit(0);
The thing is that ftp_put() blocks any further action until the upload is finished. Try ftp_nb_put() (no blocking) like so:
$upload = ftp_nb_put($conn_id, $upload_filename, $filename, FTP_BINARY);
if($upload == FTP_MOREDATA)
{
echo 'Uploading ' . $upload_filename . ' - ' . date("d/m/Y H:i:s") . ' - ' . filesize($filename) . ' bytes<br />';
while($upload == FTP_MOREDATA)
{
echo '.'; //Output a . to page or do whatever
$upload = ftp_nb_continue($conn_id);
}
}
//Note: While in the while above, it will either end in FTP_FINISHED or FTP_FAILED
if($upload == FTP_FAILED)
{
echo "Problem while Uploading $filename\n <br />". $upload_filename;
}