PHP - Php Managing Files
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 Similar TutorialsHi
As a beginner after much work i managed to display the results of a call to an access database as a list and have quite happy managed to get them to display as a list in a table. Below is the code i have used to do this.
while($row = odbc_fetch_array($UserProdResults)) { echo $row['ProductionName'] . "<br>"; }What i would like to be able to do is to populate each cell of a table which is 3 columns wide with the results eg: Hello,
Im designing a website and have a contact form, what is the best way of managing that and monitor it as just getting that contact form information sent to an email address they may end up having more and more people sending information will get all messy and will surely cause havoc. The only way at the moment i can think of is to store the first piece of information in a database table then store the reply's in a separate table but linked to the original first question by the id.
What do you guys things?
I have a table for collecting airline satisfaction survey results(see attached image). I run a query to select the staff field there are 25 rows in this column I run a switch case block to filter out a result set that includes the responses 'poor', 'fair', 'good', and 'excellent' the result set should contain 20 elements Code: [Select] function score_staff() { $staff_count = 0; $result_set_cnt = 0; $query = "SELECT staff FROM flight_survey"; $result = mysql_query($query); while ($get_info = mysql_fetch_row($result)){ foreach ($get_info as $field){ switch($field) { case "poor": $staff_count++; $result_set_cnt++; $exit; case "fair": $staff_count+=2; $result_set_cnt++; $exit; case "good": $staff_count+=3; $result_set_cnt++; $exit; case "excellent": $staff_count+=4; $result_set_cnt++; $exit; drfault: // do nothing } } } echo $staff_count."<br>"; echo $result_set_cnt."<br>"; } For each match I add 1 to the result set so with 20 matches $result_set_cnt should be 20 and not 53 as shown at the bottom of the attached image. The array $get_info bewilders me and I can't seem to access it's elements without putting it in a while loop. Anyway I'm pretty new to php and have a lot to learn. If anyone can explain how I could change the code so that the result set would contain 20 I think I'll be alright. thanks 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 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? I am using WPSQT plugin in my blog site .I code some files in PHP also.how to add that files in plugin files.
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 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 ? 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? 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. Hi All
I have a a directory website but numereous listings don't have their own website so they are requesting a single page to show a summary of their business and products.
I know how to do most of it the part I am unsure of is:
I have a form where they upload text, images, etc to a database and upload the images. what I would like to do is to save it as a file under a subdirectory. Is it possible to save a file php file using php
Thank you in advance
Lional
Hi there, I'm a beginner at php and mysql. I know a few basics, but i'm stuck. I'm trying to make something for my wifes company that will be as simple as i can make it. The files i have: login/register script (register.php / regcheck.php) member / profile script and a image upload script. (upload.php: which is now in register.php and process.php) What i want to do is: at register i've added a file upload form, but the reg.php points to regcheck.php and the upload.php points to process.php I want to combine those 2 files: regcheck.php and process.php to one file. Now i've been breakin my head over this for 2 day's and i cant find a solution and i'm not that experienced. what i've done so far is the following, but it does'nt fill my database: databas.sql: CREATE TABLE `klanten` ( `id` int(4) unsigned NOT NULL auto_increment, `username` varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `level` int(4) default '1', `filename` varchar(255) not null, `mime_type` varchar(255) not null, `file_size` int not null, `file_data` mediumblob not null, primary key (image_id), index (filename) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; <?php ob_start(); function assertValidUpload($code) { if ($code == UPLOAD_ERR_OK) { return; } switch ($code) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $msg = 'Image is too large'; break; case UPLOAD_ERR_PARTIAL: $msg = 'Image was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $msg = 'No image was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $msg = 'Upload folder not found'; break; case UPLOAD_ERR_CANT_WRITE: $msg = 'Unable to write uploaded file'; break; case UPLOAD_ERR_EXTENSION: $msg = 'Upload failed due to extension'; break; default: $msg = 'Unknown error'; } throw new Exception($msg); } $errors = array(); try { if (!array_key_exists('image', $_FILES)) { throw new Exception('Image not found in uploaded data'); } $image = $_FILES['image']; // ensure the file was successfully uploaded assertValidUpload($image['error']); if (!is_uploaded_file($image['tmp_name'])) { throw new Exception('File is not an uploaded file'); } $info = getImageSize($image['tmp_name']); if (!$info) { throw new Exception('File is not an image'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } if( isset( $_POST['user'] ) && isset( $_POST['pass'] ) ) { if( strlen( $_POST['user'] ) < 4 ) { echo "Username Must Be More Than 4 Characters."; } elseif( strlen( $_POST['pass'] ) < 4 ) { echo "Passwrod Must Be More Than 4 Characters."; } elseif( $_POST['pass'] == $_POST['user'] ) { echo"Username And Password Can Not Be The Same."; } else { include( 'database.php' ); $username = mysql_real_escape_string( $_POST['user'] ); $password = md5( $_POST['pass'] ); $filename = mysql_real_escape_string($image['name']); $mime_type = mysql_real_escape_string($info['mime']); $file_size = $image['size']; $file_data = mysql_real_escape_string(file_get_contents($image['tmp_name']) $sqlCheckForDuplicate = "SELECT username FROM klanten WHERE username = '". $username ."'"; if (count($errors) == 0) { // no errors, so insert the image if( mysql_num_rows( mysql_query( $sqlCheckForDuplicate ) ) == 0 ) { $sqlRegUser = "INSERT INTO klanten( username, password, filename, mime_type, file_size, file_data ) VALUES( '". $username ."', '". $password ."', '". $filename ."', '". $mime_type ."', '". $file_size ."', '". $file_data ."', )"; if( !mysql_query( $sqlRegUser ) ) { echo "You Could Not Register Because Of An Unexpected Error."; } else { echo "You Are Registered And Can Now Login"; $formUsername = $username; header('Location: view.php?id=' . $id); } } else { echo "The Username You Have Chosen Is Already Being Used By Another User. Please Try Another One."; $formUsername = $username; } } } else { echo "You Could Not Be Registered Because Of Missing Data."; } ob_end_clean(); ?> <html> <head> <title>Error</title> </head> <body> <div> <p> The following errors occurred: </p> <ul> <?php foreach ($errors as $error) { ?> <li> <?php echo htmlSpecialChars($error) ?> </li> <?php } ?> </ul> <p> <a href="upload.php">Try again</a> </p> </div> </body> </html> I guess i've mixed up things pretty badly right? I am using xammp with FileZilla running on it. I've changed my php.ini settings to "C:/xxx/tmp" directory but am unable to upload a file. Th cod is running but it dos not seem to upload the temporary fil. Plase somebody help me. ALso my form in upload.html has <form action="upload_file.php" method="post" enctype="multipart/form-data"> 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] This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=345120.0 First what are the possible $_FILES['file']['type'] s of .zip. I know one is "application/x-zip-compressed" but are there any others (basically I need to check if the uploaded file is a .zip? Second question; how could I extract the contents of .zip to a directory on the server without the use of FTP? Thanks 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 Hi, I have a script where employees of a company can upload invoices to their clients. This is done via a simple upload form. My question is, What would be most secure way to do this? How should i upload files, should i make different directories for each customer, or should i have one huge, where file names will be random or, what would you do? 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 Hello everyone, I'm writing a script that allows a user to upload multiple attachments to an email from PHP. So far, everything seems to be working except the multiple attachments part. If I upload one file, it works. If I upload 2, it's messing up the file names so the files don't exist. So if I upload a.jpg, it works. If I upload a.jpg and b.jpg, b.jpg gets named a b.jpg. Can someone help me understand why this is happening and how to fix it? I'm almost certain its happening on my while loop around lune 72, but the more I look at the syntax the more it looks okay to me. I had it appending the path to the file names (so a.jpg become uploads/a.jpg) so I commented that out in hopes that was causing the error but it didn't fix it. Below is the full script. <?php /******************************************* /* contact_us_process.php /* Author: Brandon Pence (brandonpence@gmail.com) /* /* Desc: This page process and checks the submitted form. /* /* variable meaning /* -------- ------- /* $FieldCheck Instance of the FieldCheck class. /* /******************************************/ //start session session_start(); //include files require ("./inc/include.inc.php"); //include Field Check Class include("classes/FieldCheck.php"); //instantiate fieldcheck class $FieldCheck = new FieldCheck; extract($_POST); /*****DEBUG*********/ echo '<h1>POST ARRAY:</h1>'; print_r($_POST); echo '<hr/>'; echo '<h1>DATAFILE:</h1>'; print_r($datafile); echo 'foreach: <hr/>'; echo '<h1>FILES ARRAY:</h1>'; print_r($_FILES); echo '<hr/>'; echo 'File name test: '.$_FILES['uploadedfile']['name']['0'].'<br/>'; echo 'File name test: '.$_FILES['uploadedfile']['name']['1'].'<br/>'; echo 'File name test: '.$_FILES['uploadedfile']['name']['2'].'<br/>'; /********************/ //foreach($datafile as $key=>$value){ //echo 'Datafile: '.$datafile.' || Key: '.$key.' || Value: '.$value.'<br/>'; //$value = $id.'/'.$value; //echo 'Datafile: '.$datafile.' || Key: '.$key.' || Value: '.$value.'<br/>'; //} if(file_exists("uploads/$id")){ echo 'Folder Exists!'; }else{ echo 'Folder does not exist. Create folder.'; //create directory mkdir("uploads/$id",0777,true); } //path we want the files stored in $target_path = "uploads/$id/"; //begin counter $i = 0; $files = array(); //begin loop while($i < 3){ //make sure each array key has valid data if(!is_null($_FILES['uploadedfile']['name'][$i])){ //append path to filenames in array //$target_path = $target_path . basename($_FILES['uploadedfile']['name'][$i]); //upload files if(move_uploaded_file($_FILES['uploadedfile']['name'][$i], $target_path)) { echo "The file ". basename($_FILES['uploadedfile']['name'][$i]). " has been uploaded"; $files[$i] = 'uploads/'.$id.'/'.$_FILES['uploadedfile']['name'][$i]; } //if file upload failed }else{ echo "There was an error uploading the file, please try again!"; } $i++; } //validate input if (!$FieldCheck->checkName($your_name)){ $errors['your_name'] = "Your name is not valid.";} if (!$FieldCheck->isEmpty($your_date)){ $errors['your_date'] = "Your date is not valid.";} if (!$FieldCheck->isEmpty($your_message)){ $errors['your_message'] = "Your message is not valid.";} foreach($_POST as $key=>$value){ $fields[$key] = $value; } //print_r($_POST); //check for error messages if (isset($errors)) { $_SESSION['errors'] = $errors; $_SESSION['fields'] = $fields; $_SESSION['error_msg'] = "Errors found! Please review your entries."; $url = "./testimonials.php?action=errors"; header ("Location: $url"); exit; }else{ echo '$files ARRAY:'; print_r($files); // email fields: to, from, subject, and so on $to = "a@c.om"; $from = "a@b.com"; $subject ="Testing Script"; $message = "My message"; $headers = "From: $from"; // boundary $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // headers for attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // multipart boundary $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; $message .= "--{$mime_boundary}\n"; // preparing attachments for($x=0;$x<count($files);$x++){ $file = fopen($files[$x],"rb"); $data = fread($file,filesize($files[$x])); fclose($file); $data = chunk_split(base64_encode($data)); $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; $message .= "--{$mime_boundary}\n"; } // send $ok = @mail($to, $subject, $message, $headers); if ($ok) { echo "<p>mail sent to $to!</p>"; } else { echo "<p>mail could not be sent!</p>"; } echo 'EMAIL SENT!'; } ?> |