PHP - Trying To Extract Contents Of Zip File To A Folder
I'm trying to extract the contents of a zip file to a folder. I found the ZipArchive class and followed the examples to get it to work for the most part. But I want to extract the files in the folder inside the zip file but leave the folder out. So it should extract just the files to my given destination. I found this on php.net.
Code: [Select] If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder). <?php $path = 'zipfile.zip' $zip = new ZipArchive; if ($zip->open($path) === true) { for($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); $fileinfo = pathinfo($filename); copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']); } $zip->close(); } ?> For some reason that 'copy' line is not working for me. Obviosly I've changed the variables in the line to the correct variables. Can someone help me out. Thanks Mike Similar TutorialsI have made a file explorer for my site so i can upload files, delete them and rename them. Everythings working fine except when i want to delete a folder. I realise you cant use ftp_delete, coz' that only works for files. I have tried rmdir, and even though I am getting no errors, it seems to do nothing :s So what is the best way to delete a folder and its contents using PHP FTP commands? Thanks guys how do i make this part of the script delete the folder and contents. Code: [Select] <?php $path = "../../gallery/gallery_files/gallery/"; if(isset($_POST['file']) && is_array($_POST['file'])) { foreach($_POST['file'] as $file) { rmdir($path. "/" . $file) or die("Failed to delete file"); } } ?> Hey Guys, I want to be able to upload a large amount of mp3's to a private area on our website and have a script that will scan the folder for all the filenames and then create a record in the db of all the filenames. It is to help with creating the playlist for my friends radio show. To manually insert all the filenames each month woudl be a nightmare! I have been messing with a partial script I found on the web, and it kind of does something but not what I want it to. heres the db id int(4) title varchar(250) mp3 varchar(250) sort int(4) visible int(1) added datetime heres the script i am trying to use: <? $listDir = array(); $dir = "./music"; if($handler = opendir($dir)) { while (($sub = readdir($handler)) !== FALSE) { if ($sub != "." && $sub != ".." && $sub != "Thumb.db") { if(is_file($dir."/".$sub)) { $listDir[] = $sub; }elseif(is_dir($dir."/".$sub)){ $listDir[$sub] = $this->ReadFolderDirectory($dir."/".$sub); } } } closedir($handler); } $db = mysql_connect("localhost","gfab_ml","xxxxxxx"); mysql_select_db("gfab_ml",$db); $colors=serialize($listDir); //takes the data from a post $sql="INSERT INTO ml_music (ID, title, added) VALUES('','$colors','')"; $result = mysql_query($sql) or die (mysql_error()); ?> it does insert the values into the db but what it does is creates 1 record and spits all the results in a really weird way like this. into the title field. a:18:{i:0;s:23:"14 Mr Magic Premier.mp3";i:1;s:23:"track1.mp3";i:2;s:15:"track2.jpg";i:3;s:15:"track3.fxp";i:4;s:12:"track4.mp3";i:5;s:7:"track5.mp3";i:6;s:7:"track6.jpg";i:7;s:7:"track7.mp3";i:8;s:12:"track8.mp3" Could anyone please help me to make it work? im a bit of a noob. but i do like to tinker! I am attempting to us glob to display contents of a users folder using a session variable. Example: I have a session variable called department Code: [Select] $row_fullname['department']; In department I have the name of the department the user belongs to such as: office, plant, maintenance, and groundskeeping I created a folder called docs inside of docs there are 4 subfolders called office, plant, maintenance, and groundskeeping I found this code which will display the contents of the folder: Code: [Select] <?php $files = glob( './docs/office/*.*' ); foreach ( $files as $file ) { echo '<a href="./docs/office/' . basename( $file ) . '"target="_blank">' . basename( $file ) . '</a><br />'; } ?> The above code works fine, but I would like it to only display the contents of a departments folder only if the user is part on that department. Here is an example that I know is completely wrong but it may help explain what I am trying to do. Code: [Select] <?php ]<?php $files = glob( './docs/echo $row_fullname['department'];/*.*' ); foreach ( $files as $file ) { echo '<a href="./docs/echo $row_fullname['department'];/' . basename( $file ) . '"target="_blank">' . basename( $file ) . '</a><br />'; } ?>Thanks for your time I have a page using forms to help build listing templates for eBay. I have a folder where I have hundreds of logos stored. I know the logo names but not their extensions. . . . I have to test each potential (jpg, jpeg, gif, png, etc.) until I guess right. Here is an example code for the web form:
<form action="extension_test2.php" method="post"> <p>Logo: <input name="e" value="" type="text" size="15" maxlength="30" /><p> <input name="Submit" type="Submit"/> </form> and the form's result: <? $e =$_POST['e']; if(!empty($e)) { echo '<img src="http://www.gbamedica...ebayimg/logos/'.$e.'">'; }; ?> Here is a link to the example: http://www.gbamedica...ension_test.php Use "olympus.jpg" for test. I am looking for code that can determine the file type and dynamically add the extension. Can it be done? Hi guys, I'm using this upload/extract zip script. I wonder if I can modify the script to link the file after it is unzip. Now it just unzip and show the content, I want to give the link to that content. Please let me know if this even possible with the code below. <form enctype="multipart/form-data" action="index.php" method="POST"> Upload a Zip Archive (*.zip): <input name="zip" type="file" /><input type="submit" value="Upload" /> </form> <?php /* UnZip on Server - using PHP by 3scriptz.com */ //check if file is uploaded if(isset($_FILES['zip'])){ require_once('pclzip.lib.php'); //include class $upload_dir = 'uploads'; //your upload directory NOTE: CHMODD 0777 $filename = $_FILES['zip']['name']; //the filename //move file if(move_uploaded_file($_FILES['zip']['tmp_name'], $upload_dir.'/'.$filename)) echo "Uploaded ". $filename . " - ". $_FILES['zip']['size'] . " bytes<br />"; else die("<font color='red'>Error : Unable to upload file</font><br />"); $zip_dir = basename($filename, ".zip"); //get filename without extension fpr directory creation //create directory in $upload_dir and chmodd directory if(!@mkdir($upload_dir.'/'.$zip_dir, 0777)) die("<font color='red'>Error : Unable to create directory</font><br />"); $archive = new PclZip($upload_dir.'/'.$filename); if ($archive->extract(PCLZIP_OPT_PATH, $upload_dir.'/'.$zip_dir) == 0) die("<font color='red'>Error : Unable to unzip archive</font>"); //show what was just extracted $list = $archive->listContent(); echo "<br /><b>Files in Archive</b><br />"; for ($i=0; $i<sizeof($list); $i++) { if(!$list[$i]['folder']) $bytes = " - ".$list[$i]['size']." bytes"; else $bytes = ""; echo "".$list[$i]['filename']."$bytes<br />"; } unlink($upload_dir.'/'.$filename); //delete uploaded file } ?> Thanks Hi, how do I extract just file extension? eg: $file="hello.xml"; $fileExt=??? print $fileExt; Any help much appreciated! For example: I am using this code: Code: [Select] $myFile = "newuser.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh, 5); fclose($fh); echo $theData; and it displays: Code: [Select] Bob 2 Which I am reading from my newuser.txt file! Which corresponds to the username bob, and he has the ID of 2. Now I want to make that linkable like this: Code: [Select] <a href=.?act=Profile&id=$IDFROMTEXTFILE(2)>$NAMEFROMTEXTFILE(BOB)</a> this is possible? If so, Thanks! Hi all, Does anyone know of a way of extracting/reading images from an excel file using PHP? This seems great (http://phpexcel.codeplex.com/) but I can't see a way of reading images from excel files. Any help would be greatly appreciated! Thanks Hello, I need some help...I want to read the contents of a file into a variable and then insert/write that content into another file. Code: [Select] $handle = fopen($create_mysql_db_url, "rb"); $contents = fread($handle, filesize($create_mysql_db_url)); fclose($handle); $userFileName = $_POST['mysqluser'] . time() . ".php.txt"; $fhandle = fopen($userFileName,"wb"); fwrite($fhandle, $contents); fclose($fhandle); $fh = fopen($userFileName,"wb"); $contents = fread($fh, filesize($userFileName)); $content = preg_replace("/###USERNAME###/", $_POST['mysqluser'], $contents); $content = preg_replace("/###PASSWORD###/", $_POST['mysqlpass'], $content); fwrite($fh, $content); fclose($fh); please help Hello. I have one programming problem. I have this log, from witch i have to read specific area of text: webtopay.log OK 123.456.7.89 [2012-03-15 09:09:59 -0400] v1.5: MIKRO to:"1398", from:"865458961", id:"13525948", sms:"MCLADM thing" So i need the script to extract word "thing" from that log. Also that script has to check if there is new entries in the log, and extract text from the last one. (Explaining in other words, that script should extract word AFTER MCLADM. Every time its a different word) p.s. I need that script to be integrated here (this has to send command to server "/manuadd (text from log)" : Code: [Select] <?php try{ $HOST = "178.16.35.196"; //the ip of the bukkit server $password = "MCLietuva"; //Can't touch this: $sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("error: could not create socket\n"); $succ = socket_connect($sock, $HOST, 4445) or die("error: could not connect to host\n"); //Authentification socket_write($sock, $command = md5($password)."<Password>", strlen($command) + 1) or die("error: failed to write to socket\n"); //Begin custom code here. socket_write($sock, $command = "/Command/ExecuteConsoleCommandAndReturn-SimpleBroadCast:broadcast lol;", strlen($command) + 1) //Writing text/command we want to send to the server or die("error: failed to write to socket\n"); sleep(2); // This is example code and here has to be that script i want to make. //while(($returnedString = socket_read($sock,50000))!= ""){ $returnedString = socket_read($sock,50000,PHP_NORMAL_READ); print($returnedString) //} print("End of script"); socket_close($sock); }catch(Exception $e){ echo $e->getMessage(); } ?> I hope i made things clear and you will help me Thanks Hello friends, if i have the following $path = "http://*site*.com"; why can't i write the following $ORGtext= file_get_contents('$path'); it works only if i write $ORGtext= file_get_contents('http://*site*.com'); but i want to put $path instead of the url at file_get_contents is it possible and if yes then how ? thank you Hello, I have a simply query that will if a simple two different things: Code: [Select] $cssyn = mysql_query("SELECT `12` FROM `12345` WHERE `abc` = '$_SESSION[number]'"); $cssy = mysql_fetch_row($cssyn); if($cssy[0] == "YES") { echo "Yes"; } else { echo "No"; } The YES or NO result is stipulated earlier on so thats not the problem. But basically before I added the if statement simply would have echoed a table with all the rows etc from another query. However I would like to give the user a choice between echoeing the results into one table or a neater two. I have separated the code for the table and the queries into two separate files but say if I use: file_get_contents then it just prints the HTML and doesnt actually populate it will the queried parts. Nor if I use something like include() then it wont echo anything, which it wouldnt unless called so what I am asking is: Is there a way to get EVERYTHING from the file if the answer is YES or the other file if NO. eg http://www.xxxxxxx.com/index.php?action=viewarti&artid=5 How can I write the content of this link into file. Hi, I assigned a project where i have to import the mobile numbers from the file, but i have no idea how to proceed this. What kind of file to accept as input and how to read. Thanks I set up a Twilio number so a client could have a SMS keyword response setup... but I don't know how to get the contents of a file to be returned as the response. I am using the php functions.. I setup a system so that my client could change the responses to different keywords. Basicly it uses a webform to change the contents of a file which gets returned as a response. What I need to know is how to read in the contents of the file into this function: BTW... this works fine and will return "READ_FILE_CONTENTS_INTO_HERE" function app(){ $response = new Services_Twilio_Twiml(); $response->sms("READ_FILE_CONTENTS_INTO_HERE"); echo $response; } I tried this but it stopped the script dead: function app(){ $response = new Services_Twilio_Twiml(); $response->sms("<?php include 'file.txt'; ?>"); echo $response; } Any ideas? Thanks BTW... below is the entire php script: <?php /* Include twilio-php, the official Twilio PHP Helper Library, * which can be found at * http://www.twilio.com/docs/libraries */ include('Services/Twilio.php'); /* Controller: Match the keyword with the customized SMS reply. */ function index(){ $response = new Services_Twilio_Twiml(); $response->sms("Thank You For Contacting SweetLeafAZ.com - Reply with one of the following keywords: APP = Make Appt, CS = Current Strains, DP = Delivery Prices, SP = Current Specials."); echo $response; } function app(){ $response = new Services_Twilio_Twiml(); $response->sms("http://www.vcita.com...01f2c7d/home"); echo $response; } function cs(){ $response = new Services_Twilio_Twiml(); $response->sms("http://mobile.dudamo...sweetleafaz2"); echo $response; } function dp(){ $response = new Services_Twilio_Twiml(); $response->sms("As of Sept 26 2014, Our Delivery Rates are $2 per mile during the hours of 9am to 6pm. No deliveries will be made after 6pm."); echo $response; } function sp(){ $response = new Services_Twilio_Twiml(); $response->sms("We are currently offering FREE delivery within 10 miles for orders over $100."); echo $response; } /* Read the contents of the 'Body' field of the Request. */ $body = $_REQUEST['Body']; /* Remove formatting from $body until it is just lowercase characters without punctuation or spaces. */ $result = preg_replace("/[^A-Za-z0-9]/u", " ", $body); $result = trim($result); $result = strtolower($result); /* Router: Match the ‘Body’ field with index of keywords */ switch ($result) { case 'app’': app(); break; case 'cs': cs(); break; case 'dp': dp(); break; case 'sp': sp(); break; /* Optional: Add new routing logic above this line. */ default: index(); } Hello, I am a PHP newbie, and have been mostly playing around with PHP/MySQL in a CMS ares (i.e. building my own CMS). Now I am trying to expand my knowledge outside of the basic php commands, and a particular subject caught my attention. Getting page source code, parsing out bits from it, and displaying it. This is more of my personal goal to get it working, to learn more about some of PHP's abilities, and especially search parameter flag thingies D: http://nexrem.com/scripts/get_source/ That is my webpage i made real quick, as you can see it shows basic stuff. Code for it is: Code: [Select] <html> <head> <title>Content Site</title> </head> <body> <p>This is intro text</p> <a href="http://google.com" title="Search Engine">Google Link</a><br /> <a href="http://yahoo.com" title="">Yahoo Page</a></br > <a href="http://http://www.phpfreaks.com" title="Awesome Site">PHP Freaks Help</a><br /> Bottom of file </body> </html> Now, I have a php file called get_link.php >> http://nexrem.com/scripts/get_source/get_links.php Code: [Select] <?php $url = 'http://nexrem.com/scripts/get_source/'; $needle = 'google'; $contents = file_get_contents($url); if(strpos($contents, $needle)!== false) { echo 'found'; } else { echo 'not found'; } // The \\2 is an example of backreferencing. This tells pcre that // it must match the second set of parentheses in the regular expression // itself, which would be the ([\w]+) in this case. The extra backslash is // required because the string is in double quotes. $html = $contents; echo $contents; preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); foreach ($matches as $val) { echo "matched: " . $val[0] . "\n"; echo "part 1: " . $val[1] . "\n"; echo "part 2: " . $val[2] . "\n"; echo "part 3: " . $val[3] . "\n"; echo "part 4: " . $val[4] . "\n\n"; } ?> From what I understand, file_get_contents gets what the user sees? Or it gets the source code, and I just can't output it as such, cause my browser renders it? Question 1: Is it possible to get the html code of the page, rather than what the html renders it to be? How? Question 2: I can just Right click > view source and paste that result into a text file. I think I know how to search for a specific string, but how would I do it recursively, along the lines of: Search for text between <a href=" and " so I get the raw link Then add the results to an array. And then use foreach to output all the links from the array? Any help, hints are appreciated! Thank You! P.S. I quite frankly, got no idea what "/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/ is... Can someone refer me to a page where I can learn about those expressions? Hi All, sure this is simple but I'm still new to php/mySQL so errors are abundant! I have a simple form with one input: a browse button so the user can find a .csv file on their computer. User then clicks button, upon which I would like the file to be read and the contents put into an array, and the values to be added to the database. I do not need the file to be stored (uploaded). So far my code is not erroring, it just doesn't add the values to the db. I'm wondering if it's just that I HAVE to upload and save the file to the webserver else I can't read it? if(isset($_FILES['file_path']['tmp_name'])&& $_FILES['file_path']['tmp_name'] !=''){ $file_to_import = $_FILES['file_path']['tmp_name']; $import_data = file($file_to_import); print_r($import_data); if ($import_data !=''){ for($index = 1; $index < sizeof($import_data); $index++){ $order_data = explode(",",$import_data[$index]); tep_db_query("UPDATE orders SET act_shipping_cost = '" . $order_data[8]. "' WHERE orders_id = '". $order_data[0]."'"); echo "done it"; } }else{ echo 'error cant read file!'; } } else{ ?> <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> etc etc etc <form id="shipping_costs_upload" name="csv_file_reader" method="post" action="shipping_cost_upload.php"> <div class="main" id="info_text"><h2>Upload Actual Shipping Costs CSV</h2><p>To upload actual shipping cost data, browse to your csv and click the Upload Data button.<br /><br /></p> <div class="date" id="file"> <strong>CSV File: </strong><input type="file" name="file_path" id="file_url" /> </div> <div class="date"><input type="submit" value="Upload Data"> </div> </form> etc etc etc Apologies if I'm being a complete dunce! Hi, I have a file which contains settings for a user. Similar to wordpress except simpler like setting a default email for error messages or something. The idea is that it's used as an installation script for web-ware where someone fills in a form with their database details, my script will hard-code them into the settings file and then delete itself. I'll admit I did get the idea from wordpress. Only the way it's coded currently requires a certain combination of characters at the end and seems really messy. The script looks like this (and does work): $endpos = strpos ( $contents, '"; //replace with name//', $startpos); The settings file looks like this: $hard_name = "Smith"; //replace with name// As you can see I use the comment in the settings file, which follows what I'm actually changing, to find the end of the variable. I am sure there must be a better way of doing things but don't know what. It just seems really inefficient because if the comment is removed the script breaks. Any info and tips would be much appreciated. IceKat |