PHP - Extract File Extension
Hi, how do I extract just file extension?
eg: $file="hello.xml"; $fileExt=??? print $fileExt; Any help much appreciated! Similar TutorialsI 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? Folks,
I am building a membership script for 21 months now!!! That long!!!
Not pasting the whole script as really long. Would do your head in. if($_SERVER["REQUEST_METHOD"] == "POST") { if(!isset($_FILES["id_verification_video_file"])) //REtype { echo "no isset"; } else { $id_verification_video_file = $_FILES['id_verification_video_file']; //REtype //Feed Id Video Verification File Upload Directory Path. $directory_path = "uploads/videos/id_verifications/"; //Make Directory under $user in 'uploads/videos/id_verifications' Folder. if(!is_dir("$directory_path" . "$user")) { $mode = "0777"; mkdir("$directory_path" . "$user", "$mode", TRUE); //Thanks Requinix for my "$mode" typo hint. } //Grab Uploading File details. $Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ? $file_name = $_FILES["id_verification_video_file"]["name"]; $file_tmp = $_FILES["id_verification_video_file"]["tmp_name"]; $file_type = $_FILES["id_verification_video_file"]["type"]; $file_size = $_FILES["id_verification_video_file"]["size"]; $file_error = $_FILES['id_verification_video_file']['error']; //Grab File Extension details. $file_extension = pathinfo($file_name, PATHINFO_EXTENSION); if(file_exists('$directory_path' . '$user/' . '$file_name')) { $Errors[] = "Error: You have already uploaded a video file to verify your ID!"; exit(); } else { //Feed allowed File Extension(s). $allowed_file_extensions = array("mp4" => "video/mp4","wmv" => "video/wmv"); //Feed allowed file size. $max_file_size_allowed_in_bytes = 1024*1024*100; //Allowed limit: 100MB. $max_file_size_allowed_in_kilobytes = 1024*100; $max_file_size_allowed_in_megabytes = 100; $max_file_size_allowed = "$max_file_size_allowed_in_bytes"; //RETYPE //Verify File Extension. if(!array_key_exists($file_extension,$allowed_file_extensions)) die("Error: Select a valid video file format. Select an MP4 or WAV file."); //Verify MIME Type of the file. elseif(!in_array($file_type,$allowed_file_extensions)) { echo "Error:<font size ='5' font color ='red'><b>There was a problem uploading your video file $file_name! Make sure your file is an MP4 or a WAV file. You may try again now.</b></color></size>"; //THANKS TO REQUINIX FOR BRINNGING IT TO MY ATTENTION I AM STILL PROCESSING THE SCRIPT AFTER THIS LINE WHEN I SHOULD NOT. exit(); } //Verify File Size. Allowed Max Limit: 100MB. elseif($file_size>$max_file_size_allowed) die("Error: Your Video File Size is larger than the allowed limit of: $max_file_size_allowed_in_megabytes."); //Fixed variable name typo. Thanks to Requinix & Simon JM. //Move uploaded File to newly created directory on the server. move_uploaded_file("file_tmp","$directory_path" . "$user/" . "$file_name"); //Notify user their File was uploaded successfully. echo "<font size ='5' font color ='red'><b>Your Video File \"$file_name\" has been uploaded successfully! You will get notified once your Id has been verified successfully.</b></color></size>";
Can you spot my coding error ? I have a variable that holds the name of a File... Code: [Select] $origFileName = $_FILES['userPhoto']['name']; What is the best way to just get the File Name from this? Debbie Hi Guys, I am having some issues in trying to return a file extension in a php upload script, here is what I am trying to do, no extension is added when a file is uploaded. $p_id = $row['p_id']; $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'; $filename = $HTTP_POST_FILES['Filedata']['name']; $ext = end(explode('.', $filename)); $nfilename = $p_id . $ext; $targetFile = str_replace('//','/',$targetPath) . $nfilename; This code uploads a file to the server then renames it to the next id number from the database and adds the extension .jpg to the file name. index.php - I need .jpg to be a variable that will append .gif if it's a gif file or .png if it's a png file. Currently, if the file is a .jpg, .gif, or .png, the files are given the extension .jpg. <?php copy($_FILES['banner']['tmp_name']['file'], './banners/'.$photo_id.'.jpg'); ?> _photo.php - I want to replace .jpg in this code with the variable from above. <a href="<?php echo safe_output($photo['web_url']); ?>" target="_blank" class="bannerImg"><img src="banners/<?php echo $photo['id']; ?>.jpg"/></a> I'm trying to determine why when I select Upload, on the html page I see a message "My extension is:" only, instead of My extension is: webM" for example.Here's the code, I look forward to any assistance: <?php foreach (array('video', 'audio') as $type) { if (isset($_FILES["${type}-blob"])) { $fileName = $_POST["${type}-filename"]; $uploadDirectory = 'uploads/' . $fileName; // make sure that one can upload only allowed audio/video files $allowed = array( 'webm', 'wav', 'mp4', 'mov' ); $extension = pathinfo($filePath, PATHINFO_EXTENSION); die("My extension is: " . $extension); if (!$extension || empty($extension) || !in_array($extension, $allowed)) { echo 'Invalid file extension: '.$extension; return; } if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) { echo (" problem moving uploaded file"); } } } ?>
Help me I am getting Notice: Undefined index: extension Need some help with this script. I'm looking to limit the type of file you can upload to my server the script uploads ok but i when i try t view the uploaded file but i get an error cant find file extension for this file what am i doing wrong as i'm very new to php . Thank for your help in advance Code: [Select] <?php $allowedExtensions = array("jpg","jpeg","gif","png","bmp"); foreach ($_FILES as $image) { if ($image['tmp_name'] > '') { if (!in_array(end(explode(".", strtolower($image['name']))), $allowedExtensions)) { die($image['name'].' is an invalid file type!<br/>'. '<a href="javascript:history.go(-1);">'. '<< Go Back</a>'); } } } $target = "testimages/"; $target = $target . basename( $_FILES['image']['name']); // $company=$_POST['company']; $image=($_FILES['image']['name']); mysql_connect("localhost", "user", "pass") or die(mysql_error()) ; mysql_select_db("testupload") or die(mysql_error()) ; mysql_query("INSERT INTO `table` (company, image) VALUES ('$company', '$image')") ; if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { echo "Sorry, there was a problem uploading your file."; } ?> I'm not fluent in php, but I think this should be an easy fix for someone who is. Basically, I have a Wordpress theme that auto generates the images from posts in each slide of the feature slider on the homepage. Goal: for php to remove the css border around the image if it is a .png file Purpose: I want borders on photos in the feature slider, but no borders on images with transparent backgrounds... like free floating logos. So I figured I could use an if/else statement to determine if the file has a .png extension... if it does then it inserts the html style to remove the border. Here is the original code from the theme where it gets the image Code: [Select] <a href="<?php echo($arr[$i]["permalink"]); ?>" title="<?php printf(__('Permanent Link to %s', 'TheCorporation'), $arr[$i]["fulltitle"]) ?>"> <?php print_thumbnail($arr[$i]["thumb"], $arr[$i]["use_timthumb"], $arr[$i]["fulltitle"] , $width, $height, 'thumb'); ?> </a> Here is what I was trying to get to work.. I tried taking the variable for $file from the code I assumed was populating the image path Code: [Select] <?php $file = `print_thumbnail($arr[$i]["thumb"]`; $ext = `pathinfo($file, PATHINFO_EXTENSION)`; ?> <a <?php if($ext == ".png") echo ?>style="border:none 0px !important;" <?php ; else null; ?> href="<?php echo($arr[$i]["permalink"]); ?>" title="<?php printf(__('Permanent Link to %s', 'TheCorporation'), $arr[$i]["fulltitle"]) ?>"> <?php print_thumbnail($arr[$i]["thumb"], $arr[$i]["use_timthumb"], $arr[$i]["fulltitle"] , $width, $height, 'thumb'); ?> </a> Any help would be appreciated. Thanks. Hello,
I have managed to find, retrieve and save a file using CURL. But I am having to hard code the file extension, is there a way to find the file extension automatically? (it seems the file extension isn't within the download URL)
(also, is there a way of getting the file name so I can save it as the same filename - that would be great)
Thanks for your help,
Stu
p.s. I've tried the pathinfo($url) function, but that gets information out of the download URL rather than the download file.
$url="http://webmail.WEBSITE.com/src/redirect.php"; $cookie="cookie.txt"; $postdata = "login_username=USERNAME&secretkey=PASSWORD&js_autodetect_results=0&just_logged_in=1"; # get the cookie $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt ($ch, CURLOPT_REFERER, $url); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec ($ch); curl_close($ch); $ch = curl_init(); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); //read cookies from here curl_setopt($ch, CURLOPT_URL, "http://webmail.WEBSITE.com/src/right_main.php"); curl_setopt($ch, CURLOPT_HEADER, 0); $result = curl_exec($ch); curl_close($ch); # download file $source = "http://webmail.WEBSITE.com/src/download.php?mailbox=INBOX&passed_id=6475&startMessage=1&override_type0=text&override_type1=html&ent_id=2&absolute_dl=true"; $ch = curl_init(); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); //read cookies from here curl_setopt($ch, CURLOPT_URL, $source); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSLVERSION,3); $data = curl_exec ($ch); $error = curl_error($ch); curl_close ($ch); # !!! The line below needs to be automated !!! $destination = "./files/test.html"; $file = fopen($destination, "w+"); fputs($file, $data); fclose($file); Edited by stubarny, 17 June 2014 - 04:46 PM. Hi Gusy, Would be great if you can help me to sort this out and Thank you in advance. I would like to hide all files with "swf" extension from my file and folder directory, I know how to hide one specific file but not ll files with same extension. For example: *.swf. Here is my code which is work for full file names but not all files with same extension. <?php $filearray = array(); if ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && $file != ".htaccess" && $file != "index.php" && $file != "style.css" && $file != "Images" && $file != "*.swf" && $file != "index.html") { $filearray[] = $file; } } closedir($handle); natcasesort($filearray); foreach($filearray as $f) { $thelist .= '<img width="15" height="15" alt="[DIR]" src="/Images/folder.jpg"> <a href="'.$f.'">'.$f.'</a> '; } } ?> As you can see I have "&& $file != "*.swf"" which need your advise in this part. I just want people not seeing all .SWF files in the index directory of my server. I have already have index.html inside my folder as well which has been hided because of "$file != "index.html"". But this is not hiding my ".SWF" files. Many Thanks. Hello guys i have been trying to find an alternative file function to read multiple files into an array. My aim is to preg_replace every file in directory starting with Audit_Report with the font colours...i have been googling it for like 2 hours and the closest answer i can get to is using the glob() function but it doesn't work for me still. I would like you guys to give me suggestions if you can..thanks!! <?php $file = "Audit_Report.(SEAN).(192.168.199.129).txt"; $lines = file($file); foreach ($lines as $line) { $string = $line; $patterns = array(); $patterns[0] = '/\bPass\b/'; $patterns[1] = '/\bFail\b/'; $patterns[2]='/\b============ Major Audit and Account Policies============ \b/'; $replacements = array(); $replacements[1] = "<font color=red>Fail</font>"; $replacements[0] = "<font color=green>Pass</font>"; $replacements[2] = "<br><b>==== Major Audit and Account Policies====</b>"; ksort($patterns); ksort($replacements); $a = preg_replace($patterns, $replacements, $string); echo "$a<br />\n"; file_put_contents(basename($file, substr($file, strpos($file, '.'))) . ".html","$a<br />\n", FILE_APPEND) or die("Cannot write file"); } ?> 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 I want to remove the file extension - I have done that.
I want to remove the trailing slash. - I have done that
But I cannot for the life of me get the the regular page to display instead of the folder which show a tree of files within it.
site.com/website-tips.php site.com/website-tips/increase speed.php The extension drops off and the trailing slash too but when I navgate back through the vreadcrumb to website-tips (without php in html code) it gives me the folder and shows the file tree (files within website tips folder) How would I solve this? right now if I access the website-tips.php file, it shows the directory and its interior pages Pls hlp out. 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 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! 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 Hello, 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 This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=321546.0 |