PHP - File Name With Extension
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 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 ? Hi, how do I extract just file extension? eg: $file="hello.xml"; $fileExt=??? print $fileExt; Any help much appreciated! 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; 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."; } ?> 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 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. 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"); } ?> 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. 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. i have problems with making a questionnaire. i have done a single questions but i have no idea how to add them al ltogether so they work as switch function. i`ve attached one of the questions. could anyone suggest how i make answers into a list rather than just a line of options? Hi there, trying to use PCNTL. I've recompiled PHP with --enable-pcntl in configure as described in PHP manual, but when I call pcntl_fork() I receive back " Fatal error: Call to undefined function pcntl_fork() ". What am I missing??? Thanks in advance Muflo Just started working with PHP and wrote a PHP extension in C. Got it working with hard coded variables and started to work on feeding it 3 string arguments as input. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss", &acct, &acct_len,&userid, &userid_len, &passwd, &passwd_len) == FAILURE) { RETURN_NULL(); } When I execute the extension with 3 arguments I always get the following. Code: [Select] [XXX@XXXVIPH01 smxauth]$ php -r "smxauth('myacct','nobody','password');" PHP Warning: smxauth() expects exactly 1 parameter, 3 given in Command line code on line 1 I thought the "sss" would dictate the number of args expected but it doesn't seem to work that way (for me at least). Using php-5.1.6 Any thoughts? Thanks Tim Hey guys! I just joined this forum today, and I'm wondering about something... I see a lot of sites, and in the code of the site, style sheets and javascript includes are references in a manner similar to this... "href='http://www.somesite.com/css/css.php/someDirectory/style.css'" How is this done? The path following the "css.php" is what confuses me. Thanks for any information you have! PHP v. 5.3.8 What is libxml extension and how would I know if it's enabled? My book told me Note To take advantage of SimpleXML, make sure PHP's libxml extension is enabled. Hi all, I just managed to make a little mod_rewrite rule which manages to interpret url's without the extension and calls the right file with the extension (ie. /articles calls articles.php) . But now i am left with another question which i am almost certain has nothing to do with mod_rewrite, but rather with a php trick. In case someone enters on my site www.mydomain.com/laalalalala.php How do i get rid of that last part(the extension for example)? Do i maybe have to get the GET['var'] and run it through a regex and reload the page with the stripped version? That was all i could think off but it sound so complicated. if anyone has an idea i would love to hear it cheers! P.s.s if anyone want's that rewrite rule, let me know. I saw quite some people on the internet looking for it How do I know if Filter extension is on with my webhost? Or does it always work with PHP5? If I cannot use it, can someone recommend a good regex to validate EMAIL addresses?? Thanks, Debbie |