PHP - Files Becoming Corrupt
I have a section where users can upload documents into our software. The code itself is a couple years old and could perhaps use some updating, but it seems some of the files (at this time it only seems to be *.pdf) that have been uploaded are not able to be opened and the error "the file is damaged and could not be repaired" is being displayed as an "Adobe Reader" error in Internet Explorer 8.
The largest concern is that it is an irreversible error and many of the documents users have uploaded are now corrupt. I can't seem to find any relevant information from Google (or Adobe) that does anything towards resolving the problem. Note: This does not happen on every .pdf, and I am not sure if there is a common bond between the failing documents (trying to find this now). Similar TutorialsI used the following script to limit number of downloads but the downloaded zip files become corrupt. I altered the code several times but no positive result. This is the code can anyone debug this script $path ="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //addslashes($_SERVER['REQUEST_URI']); $ip = addslashes($_SERVER['REMOTE_ADDR']); $dl = false; $sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time FROM downloaded WHERE filepath = '%s' AND ipadres = '%s' ORDER BY last_access DESC", $path, $ip); $res = mysql_query($sql); if (mysql_num_rows($res) > 0) { $last_xs = mysql_result($res, 0, 'last_time')+3600; if ($last_xs < time()) { mysql_query(sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip)); $dl = true; } } else { $sql = sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip); mysql_query($sql); $dl = true; } echo"<br> here is : ".$path."<br>"; if ($dl) { $fullPath = $_SERVER['DOCUMENT_ROOT'].$path; if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); //$chunksize = 1*(1024*1024); if ($fd = fopen ($path, "r")) { $fname = basename($path); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: Binary"); header("Content-Length: ".filesize($path)); header("Content-Disposition: attachment; filename=\"".basename($fname)."\""); header("Content-Description: File Transfer"); //header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); //header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: private"); header("Accept-Ranges: bytes"); header('Vary: User-Agent'); while(!feof($fd)) { //$buffer = fread($fd,500*1024); $buffer = fread($fd,filesize($path)); //$buffer = readfile($fd); //$buffer = fread($fd, $chunksize); //$buffer = fread($fd, (1*(1024*1024))); //$buffer = file_get_contents($fd); echo $buffer; //ob_flush(); ob_end_flush(); } fclose ($fd); exit; } } else { header('HTTP/1.0 503 Service Unavailable'); die('Abort, You reached your download limit for this file.'); } ?> I tried several options as shown with // Inputs by you all will be extremely helpful. So far I have managed to create an upload process which uploads a picture, updates the database on file location and then tries to upload the db a 2nd time to update the Thumbnails file location (i tried updating the thumbnails location in one go and for some reason this causes failure) But the main problem is that it doesn't upload some files Here is my upload.php <?php include 'dbconnect.php'; $statusMsg = ''; $Title = $conn -> real_escape_string($_POST['Title']) ; $BodyText = $conn -> real_escape_string($_POST['ThreadBody']) ; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $Thumbnail = "upload/Thumbnails/'$fileName'"; if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf', "webm", "mp4"); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; $targetFilePathArg = escapeshellarg($targetFilePath); $output=null; $retval=null; //exec("convert $targetFilePathArg -resize 300x200 ./upload/Thumbnails/'$fileName'", $output, $retval); exec("convert $targetFilePathArg -resize 200x200 $Thumbnail", $output, $retval); echo "REturned with status $retval and output:\n" ; if ($retval == null) { echo "Retval is null\n" ; echo "Thumbnail equals $Thumbnail\n" ; } }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, mp4, webm & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg ; } else { echo "\n Failed to update Thumbnail. Thumbnail equals $Thumbnail" ; } // Display status message echo $statusMsg; ?> And this does work on most files however it is not working on a 9.9mb png fileĀ which is named "test.png" I tested on another 3.3 mb gif file and that failed too? For some reason it returns the following Updated the thumbnail to sql correctly.Updated the thumbnail to sql correctly. Whereas on the files it works on it returns REturned with status 0 and output: Retval is null Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif' Failed to update Thumbnail. Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif'The file rainbow-trh-stache.gif has been uploaded successfully. Any idea on why this is? Hello I have a simple question about file handling... Is it possible to list all files in directories / subdirectories, and then read ALL files in those dirs, and put the content of their file into an array? Like this: array: [SomePath/test.php] = "All In this php file is being read by a new smart function!"; [SomePath/Weird/hello.txt = "Hello world. This is me and im just trying to get some help!";and so on, until no further files exists in that rootdir. All my attempts went totally crazy and none of them works... therefore i need to ask you for help. Do you have any ideas how to do this? If so, how can I be able to do it? Thanks in Advance, pros I am using WPSQT plugin in my blog site .I code some files in PHP also.how to add that files in plugin files.
lets say I own a file, and you own a file, both these files are the exact same file, the only difference is the filename. So lets say we both have The Gimp 2.6 but one is named TG2.6.exe and the other is named the_Gimp-2.6.exe. What would be the best way to count the files that are the same even if they have a different file name? Another example would be: I have a file called me.jpg and someone else has a file me.jpg but they are two completely different pictures. What would I do to tell that? first of all...its good to see the site back .
my question guys is i'm wondering is there a way of getting the column number when reading a .cvs file?
ie. a, b, c, d, aa, ab etc?
$row = 1; if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { //echo $data[$c] . "<br />\n"; } } fclose($handle); }now $num counts the columns...but i want to convert that into a alphabetical column...is there a easy solution? thanks guys Hey, Trying to learn to generate PDF files, something apparently WAAAAYYY more complex than I thought. Can someone please give me an explanation on '$optlist' from this function..... PDF_load_image ( resource $pdfdoc , string $imagetype , string $filename , string $optlist ) What is it? PHP.net doesn't have any info at all. Thanks, IceKat. BTW - Any (recent) tutorials or pages would be appreciated. Everything I find is out of date or doesn't work. I have told that the php files I was working on contains BOM by default cause of the editor I m using. I have installed other editor that can create php files without BOM. So my question is what's the difference between 2 files, one with BOM and other without BOM ? Any problems I may face for long term usage ? Which one is better to use ? I have a delete statement to delete images, but I also want it to delete the thumbnail image as well. $query = "DELETE from products where urnid = '$urnid'"; if(file_exists("images/$product.jpg")){ unlink("images/$product.jpg")} Is there a way to delete the product_th.jpg image? I'm an intermediate php coder however I have a new situation. I need to do some remapping of categories from CSV files we get from our supplier for our php ecommerce store. We use mySQL back end. We are importing data from a Supplier and need to remap the category names for our online store. There are 16,000 entries in the CSV file. This is what I need to do. 1) grab the CSV from the suppliers (from their ftp location) 2) remap the suppliers category names on the acquired CSV to our stores category names. I can either create a new table with the category name relation ships (probably best?) or read my mapping CSV ? 3) save the new CSV to our server where our auto import program can grab it. Eventually, Id like a cron to run the new script but for now Ill do it manually during testing period. Thats it! but... as simple as it sounds, I dont know how to start this. Below is an example of what needs to be dont just to clarify. PHP Code: Our Category(A) | Their Category(B) | Product (C) | Product Cat (D) | New Product Cat (E) 1. dog/leash/long | Pet/walking | Item A | Pet/sleeping|bed ** This is what we need to get** 2. dog/leash|long | Pet/walking | Item B | Pet/walking 3. dog/leash|long | Pet/sleeping bed | Item C | Pet/walking Here is my pseudo code: Code: [Select] for each value in Column D (run the test on each value in Column D) for each value in B as i ( check each value in Column B) if B(i) = D1 then E1 =A(i) end for end for The new path in this example for Item A would be A3 and would be written to E1. I have 15,000 entries to do. Thank you for any help Hello, I've been assigned the task of creating an internal site for our office that has links to all the websites we use as well as the applications we use. I'm very comfortable using php with mysql for handling forms and displaying database information but I'm not sure how to go about this. So my question is, is there anyway I can use php to open an exe file? Hello all I have been trying to loop thru a dir. of .gz files and unzip them into the dir. that this script runs in, can not seem to get it can someone help? Here is what I have$buffer_size = 4096; // read 4kb at a time if ($handle = opendir('./gz')) { while ($in_file = readdir($handle)) { if($in_file != "." && $in_file != ".." && $in_file != "index.php"){ $file = gzopen($in_name, 'rb'); $out_file = fopen($out_file_name, 'wb'); while(!gzeof($file)) { fwrite($out_file, gzread($file, $buffer_size)); } fclose($out_file); gzclose($file); } } closedir($handle); } Thank all Hi, I have songs that I have uploaded. There are tracks in each song. So I want my users to click download and they'll be able to download all of the tracks combined in a zip file. I have seen this hapening on several sites. Can any body tell me how that works using PHP codes / classes Regards, Faisal I have a small form which executes a php file, and the executable php file. is there anyway to have it just using the 1 php file? form code: Code: [Select] <form enctype="multipart/form-data" action="upload-exec.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> uploader.php Code: [Select] <?php $target = "upload/"; $target = $target . 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/php") { echo "No PHP files<br>"; $ok=0; } //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } ?> i did try using: Code: [Select] if (isset($_POST['submit'])) { with no luck. Many thanks Hi Chaps, I have a PHP app that allows users to login and view contents of an FTP folder (that is unique to their login). They can upload and download files but some users are having problems. As some of the files can be quite large, the app seems to be a bit tempremental when uploading files. Also, when downloading very large files, sometimes in excess of 200-300 Mb, the script seems to timeout. The script reads the file to be downloaded, then loads it to the header, to force open/download. But again, this is very tempremental and there's nothing much to go on in terms or trouble-shooting. Everytime I test it, it seems to work, but users are having trouble. I have checked the Windows IIS 7/PHP file settings, and all are OK. So my questions a 1. what is the best way to handle very large file uploads? 2. what is the best way to force open/download of large files, without PHP having to 'read' the file first? Any help or guidence would be most appreciated. Cheers when the blow code is ran it produces this warning error Quote Warning: filemtime() [function.filemtime]: stat failed for 048_Baby_Colors.png in /home/public_html/.com/kill.php on line 23 The code deletes all the files in the directory no matter how many hours or seconds ago they was last modified. could someone help me figure out why? <?php $dir = '/home/br/public_html/l.com/dfile'; if ($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { if ($file[0] == '.' || is_dir("$dir/$file")) { continue; } if ((time() - filemtime($file)) > ($days * 604800)) { unlink("$dir/$file"); } } closedir($handle); } ?> I am looking to allow people to also upload pdf and doc ad txt files can you show me how to convert this script . Thanks. Code: [Select] [php] // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp","image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } [/php] Hi, I have a script which uses a connect file but I am struggling to get files in other folders to read and for the "$loggedIn = checkLogin();" code to work. If I connect to the database within the same script it works straight away. If I change my password then I have to change every file but otherwise I cannot include the connect file as I have to link to it locally. So if the connect file is in: www.domain.co.uk/php/login/connect.php then www.domain.co.uk/php/login/index.php -- this works www.domain.co.uk/php/logout.php -- this doesn't regardless of how I link to the connect file. Hey All, First post so please be gentle! I have a website www.antiquesattic.co.uk and i have been left in the lurch and without it being fully finished. I want to add google analytics code to everypage and i am a bit stuck. I have access to the server (apache 2.2.19) and have been able to add site maps etc but i am not sure where to paste the analytics code. Which folder would i look in and whereabouts do i paste. I would be extremely extremely grateful if someone could do me a quick step by step guide Also, if you would like to have a look at the website and give me some feedback that would be great! One final thing, i can't add content to the homepage just auctions, would it be a easy job to get some one to edit the site so i can add say 1000 words of text at the bottom of the homepage from my admin area? Apologies for the noob questions but my expertise is in sales and marketing not coding. Thanks Chris Hi, (Just wanna say thanks to the guy who helped me earlier as i cannot find the topic) I have a game, it has 3 frames, menu, header & the main content, it WAS fine until i deleted a 4th frame, now when i click a link from the menu, instead of showing the link in the 'Main' content area, it takes you to the actual page with no menu, header etc. Thanks in advance! |