PHP - Renaming Files Form On Local Pc
I wrote this script to rename my many tv series I have on my pc, works by finding a string in the file name and replacing it
the script works fine until I want to replace the file name with something that is also in the path
file = band ep01.avi
path = j:\media\ TV shows\Band of Brothers\
so if I try to change "Band" to "Band of Brothers" the path changes as well
is there a way I can change the code so it dosent effect the path ??
<?php $path = 'J:\media\TV shows\Band of Brothers'; foreach(glob($path.'/*.*') as $filename){ echo $filename."</BR>"; } ?> <table align="center" width="200px" border="0" cellspacing="1" cellpadding="3"> <form name="form1" method="get" action="mov.php"> <tr> <td colspan="3"><strong> </strong></td> </tr> <tr> <td width="71">Replace</td> <td width="6">:</td> <td width="301"><input name="rep" type="text" id="rep"></td> </tr> <tr> <td>With</td> <td>:</td> <td><input name="with" type="text" id="with"></td> </tr> <tr> <tr> <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td> </tr></form> </table> <?php if (isset($_GET["rep"])) { $rep1=$_GET['rep']; } if (isset($_GET["with"])) { $with1=$_GET['with']; } foreach(glob($path.'/*.*') as $filename){ $strip = str_replace($rep1, $with1, $filename); echo $strip."</br>"; rename($filename,$strip); } ?> Similar TutorialsI have a folder containing files. I want to replace some characters in the file names (e.g. "_" with "-"), then make a list of new files (renamed ones). Thanks Hey all, this is my first post ever and am not really sure if this is the right place for it or not, sorry in advance if it isn't. I'm new to PHP and trying to learn. I'm running Ubuntu 10.04 LTS and Firefox 3.6.22. I have libapache2-mod-php5 installed and running, but for some reason everytime I try to open a local .php file in firefox the download manager pops up and ask me what I want to do with the file. Has anyone else encountered this before? Is it something simple that I overlooked? Any help would be appreciated. Hi, ive recently created a gallery website and im happy with the way everything currently works. However the main drawback is the site uploads using a html webfom which is great for remote users or the odd image. However, as i want to mass upload my existing collection i will need the ability to read a selected folder and then to carry out all the same processes that existed from the existing html form upload. Im also using gdlibrary and checking file types to ensure they are within my allowed list, but im wondering if there are any other common security alerts i should be aware of to keep things a little bit safer if/when i publish outside of my LAN. So in a nut shell i need some assistance with changing my upload process to work for more than one file at a time, ideally by reading a folder, or at least reading X amount of files at a time - processing them then moving onto next batch of files in the list. Then the next part i need help with is checking/improving basic security of the system Hi. I have php code that attempts to read a file into a string using get_file_contents(), but it claims the file does not exist. I do the same thing in another php file (same directory) and it works. Only difference is that the first file has the call in a function. File one: Code: [Select] $email_template = "../email_templates/new_instructor.html"; echo file_exists($email_template); $message = file_get_contents($email_template);//get the email template File two: Code: [Select] $email_template = "../email_templates/new_instructor.html"; echo file_exists($email_template); echo file_get_contents($email_file); please help.' thanx Is it possible to read from a file that is located on the user's local machine and not on the server? I have a CSV file that is about 70MB that I have to parse through and insert the data into a database. I have no problem doing this if I hard code the path to the file. Is there a way to get the path of the file that the user wants to be parsed into the database? I don't think uploading the file would be a good idea because, like I said, it is 70MB and is nearly 2 million lines. Simply parsing the file takes long enough without throwing in upload time.. I got this script: But it give me error, file_get_contents cannot open stream. I need to add the FTP connection with user/pass paramaters. then look in set http url, to get the file contents(images) and transfer to ftp server location. Can Anyone take alook and tell me if I am going down the right path and how to get there. Please Code: [Select] function postToHost($host, $port, $path, $postdata = array(), $filedata = array()) { $data = ""; $boundary = "---------------------".substr(md5(rand(0,32000)),0,10); $fp = fsockopen($host, $port); fputs($fp, "POST $path HTTP/1.0\n"); fputs($fp, "Host: $host\n"); fputs($fp, "Content-type: multipart/form-data; boundary=".$boundary."\n"); // Ab dieser Stelle sammeln wir erstmal alle Daten in einem String // Sammeln der POST Daten foreach($postdata as $key => $val){ $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n"; } // Sammeln der FILE Daten if($filedata) { $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$filedata['name']."\"; filename=\"".$filedata['name']."\"\n"; $data .= "Content-Type: ".$filedata['type']."\n"; $data .= "Content-Transfer-Encoding: binary\n\n"; $data .= $filedata['data']."\n"; $data .= "--$boundary--\n"; } // Senden aller Informationen fputs($fp, "Content-length: ".strlen($data)."\n\n"); fputs($fp, $data); // Auslesen der Antwort while(!feof($fp)) { $res .= fread($fp, 1); } fclose($fp); return $res; } $postdata = array('var1'=>'today', 'var2'=>'yesterday'); $filedata = array( 'type' => 'image/png', 'data' => file_get_contents('http://xxx/tdr-images/images/mapping/dynamic/deals/spot_map') ); echo '<pre>'.postToHost ("localhost", 80, "/test3.php", $postdata, $filedata).'</pre>'; Hi, Is there a way to send extracted information from one (local) MySQL db, via PHP, to an external web form - having that web form submit that info to it's connected MySQL db without human interaction? Basically, I need to automate a process using the $_GET function to that form but not sure if there is a way to accomplish this from just connecting to the web form (itself); bypassing direct MySQL access which is the later option. Any input appreciated - thanks! My question would be a little out of topic... what i am doing is trying to create a music album website for my customer.. nd have to create a form to upload the .mp3 files... the file my customer have are like complete albums.. each album named as track01.mp3 , track02.mp3.. i rename them as getting a value from the text box where the user enter the correct name and this track01 gets renamed.. by default the .mp3 files have the correct song name in its <title> tag.. like everysong have there properties.. and title is one them.. the title of the song is present in title tag of the song property.. is there a way i can get that title be assigned as the name of the song and finish of this manual way of entry of the name of the song by the user? i hope u understand what i am saying.. i want what ever is in the title track to automatically be assigned to the name of the song... please help me if this is possible? Hello, I made a site where to upload images. The images are saved to a directory (folder). After someoe uploads an image, he gets the link. For example, if someone has an image called "xxx.jpg", he gets the url like this: www.example.com/upload/xxx.jpg. What I want is, when someone uploads an images, the name of the image change to random numbers. I know the PHP function rand() and rename () function, but the only problem is, it is renaming the file without considering the file extension. Here is a sample of my codes: Code: [Select] $image = htmlentities($_FILES['file']['name']); $number = rand(1,1000); $newname = rename ($image, $number); echo $newname So, can someone tell me, how to rename images but taking into consideration of the file extension? If the image is xxx.jpg, I want it like 123.jpg not 123. Hi all I am writing a piece of code that takes the filename from a form and renames it so that the file overwrites the original in the directory. HEre's my code: if(!empty($_FILES['i1']['name'])) { copy($_FILES['i1']['tmp_name'], "/home/cqdesign/public_html/clientarea/argentequus/mobile/images/slideshow/".$_FILES['i1']['name']) or die("Error uploading image 1."); } This takes the file from the form where the name of the file is i1. I need it to then rename the file to i1.jpg. There are 9 different files with the same format. Many thanks for your help. Pete Hi Is there a way I can change my script to auto name the file when its being stored? Maybe by numbers lets say each time I upload a picture it should rename it to the number after the previous number.
like example"
Upload 1: 1.jpg
Upload 2: 2.jpg etc..
My current code I have is as follow
Form.html
<html> <body><br> <h1>My upload file form.</h1> <form enctype="multipart/form-data" action="process.php" method="post"> Enter File Name:<input type="text" name="name" value="Please enter file name:" /><br> Enter Description:<input type="text" name="desc" value="Description:" /><br> Select image:<input type="file" name="prodImg"><br> <input type="submit" value="Submit Page" /> </form> <?php include "menu3.php"; ?> </body> </html>And my processing script process.php <?php extract($_POST); $name; $desc; $fileType = $_FILES['prodImg']['type']; $fileSize = $_FILES['prodImg']['size']; if($fileSize/1024 > '150') { echo 'Filesize is not correct it should equal to 2 MB or less than 2 MB.'; exit(); } //FileSize Checking if($fileType != 'image/gif' && $fileType != 'image/jpg' && $fileType != 'image/jpeg' ) { echo 'Sorry this file type is not supported we accept only. Jpeg, Gif, PNG, or '; exit(); } //file type checking ends here. $upFile = 'files/galaxywars/'.date('Y_m_d_H_i_s').$_FILES['prodImg']['name']; if(is_uploaded_file($_FILES['prodImg']['tmp_name'])) { if(!move_uploaded_file($_FILES['prodImg']['tmp_name'], $upFile)) { echo 'Problem could not move file to destination. Please check again later. <a href="index.php">Please go back.</a>'; exit; } } else { echo 'Problem: Possible file upload attack. Filename: '; echo $_FILES['prodImg']['name']; exit; } $prodImg = $upFile; //File upload ends here. $upFile; echo "Thank you for sending your file"; ?> <?php include "menu3.php"; ?>Can anyone assist me with this problem please? Can someone help me in renaming an uploaded file with parameters from the input fields named firstname and lastname? I would like to name each uploaded file with the firstname and lastname along with a random number and then the file extension, but I am having trouble getting it right. Here is what I have so far: Code: [Select] <?php $firstname = ""; $lastname = ""; $address = ""; $city = ""; $state = ""; $zip = ""; $phone = ""; $position = ""; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>KulaE_WDP4451_U2IP</title> </head> <body> <form action="process_U2IP.php" method="post" enctype="multipart/form-data"> <h3>Please fill out the form below and upload your resume to apply for a position within our company:</h3> <table> <tr> <td><label for="firstname"><b>First Name*</b></label></td> <td><input name="firstname" type="text" size="20" id="firstname" value="<?php echo $lastname; ?>" /></td> </tr> <tr> <td><label for="lastname"><b>Last Name*</b></label></td> <td><input name="lastname" type="text" size="20" id="lastname" value="<?php echo $lastname; ?>" /></td> </tr> <tr> <td><label for="address"><b>Address*</b></label></td> <td><input name="address" type="text" size="20" id="address" value="<?php echo $address; ?>" /></td> </tr> <tr> <td><label for="city"><b>City*</b></label></td> <td><input name="city" type="text" size="20" id="city" value="<?php echo $city; ?>" /></td> </tr> <tr> <td><label for="state"><b>State*</b></label></td> <td><input name="state" type="text" size="20" id="state" value="<?php echo $state; ?>" /></td> </tr> <tr> <td><label for="zip"><b>Zip*</b></label></td> <td><input name="zip" type="text" size="20" id="zip" value="<?php echo $zip; ?>" /></td> </tr> <tr> <td><label for="phone"><b>Phone*</b></label></td> <td><input name="phone" type="text" size="20" id="phone" value="<?php echo $phone; ?>" /></td> </tr> <tr> <td><label for="position"><b>Position*</b></label></td> <td><input name="position" type="text" size="20" id="position" value="<?php echo $position; ?>" /></td> </tr> <tr> <td><b>Upload Resume*</b></td> <td><input type="file" name="file" id="file" /> </td> </tr> <tr> <td colspan="2"><p><i>Your information will not be sold or shared with others.</i></p></td> </tr> <tr> <td colspan="2"><p style="color: red;">* denotes required field</p></td> </tr> <tr> <td colspan="2" align="center"><input type="hidden" name="submitted" value="1" /> <input type="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></td> </tr> </table> </form> </body> </html> Code: [Select] <?php if (@$_POST['submitted']){ $firstname = (@$_POST['firstname']); $lastname = (@$_POST['lastname']); $address = (@$_POST['address']); $city = (@$_POST['city']); $state = (@$_POST['state']); $zip = (@$_POST['zip']); $phone = (@$_POST['phone']); $position = (@$_POST['position']); $file = (@$_POST['file']); if (get_magic_quotes_gpc()){ $firstname = stripslashes($firstname); $lastname = stripslashes($lastname); $address = stripslashes($address); $city = stripslashes($city); $state = stripslashes($state); $zip = stripslashes($zip); $phone = stripslashes($phone); $position = stripslashes($position); } $error_msg=array(); if ($firstname==""){ $error_msg[]="Please enter your first name"; } if(!preg_match("/^\b[a-zA-Z]+\b$/", $firstname)){ $error_msg[]="First Name can only contain letters"; } if ($lastname==""){ $error_msg[]="Please enter your last name"; } if(!preg_match("/^\b[a-zA-Z]+\b$/", $lastname)){ $error_msg[]="Last Name can only contain letters"; } if ($address==""){ $error_msg[]="Please enter your address"; } if(!preg_match('/^[a-z0-9 ]*$/i', $address)){ $error_msg[]="Address can only contain numbers, letters and spaces"; } if ($city==""){ $error_msg[]="Please enter your city"; } if (!preg_match("/^\b[a-zA-Z]+\b$/", $city)){ $error_msg[]="City can only contain letters"; } if ($state==""){ $error_msg[]="Please enter your state"; } if (strlen($state)<>2){ $error_msg[]="State can only contain 2 letters; use state abbreviation"; } if (!preg_match("/^\b[a-zA-Z]+\b$/", $state)){ $error_msg[]="State can only contain letters"; } if ($zip==""){ $error_msg[]="Please enter your zip code"; } if (strlen($zip)<>5){ $error_msg[]="Zip code can only contain 5 digits"; } if(!is_numeric($zip)){ $error_msg[]="Zip code must contain only numbers"; } if ($phone==""){ $error_msg[]="Please enter your phone number"; } if (strlen($phone)<>10){ $error_msg[]="Phone number can only contain 10 digits"; } if(!is_numeric($phone)){ $error_msg[]="Phone number must contain only numbers"; } if ($position==""){ $error_msg[]="Please enter your desired position"; } if(!preg_match('/^[a-z0-9 ]*$/i', $position)){ $error_msg[]="Position can only contain numbers, letters and spaces"; } if (file_exists("upload/" . $_FILES["file"]["name"])) { $error_msg[]= $_FILES["file"]["name"] . " already exists"; } if ((($_FILES["file"]["type"] != "document/msword") || ($_FILES["file"]["type"] != "document/pdf")) && ($_FILES["file"]["size"] > 20000)) { $error_msg[]= "Uploaded file can only be in MSWord or PDF format and can only be under 20KB in size"; } } if ($error_msg){ $display_errors = "<h3>There were errors in your submission.</h3> <p>Please review the following errors, press the Back button on your browser, and make corrections before re-submitting.</p> <ul style=color:red>\n"; foreach ($error_msg as $err){ $display_errors .= "<li>".$err."</li>\n"; } $display_errors .= "</ul>\n"; } if (!$error_msg){ echo " <h3>Thank you for applying! Applicants we are interested in interviewing will be contacted within 48 hours.</h3> <p>You have submitted the following information:</p> <table> <tr> <td><b>First Name:</b></td> <td>$firstname</td> </tr> <tr> <td><b>Last Name:</b></td> <td>$lastname</td> </tr> <tr> <td><b>Address:</b></td> <td>$address</td> </tr> <tr> <td><b>City:</b></td> <td>$city</td> </tr> <tr> <td><b>State:</b></td> <td>$state</td> </tr> <tr> <td><b>Zip Code:</b></td> <td>$zip</td> </tr> <tr> <td><b>Phone Number:</b></td> <td>$phone</td> </tr> <tr> <td><b>Position Desired:</b></td> <td>$position</td> </tr>"; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "<tr> <td><b>Uploaded File:</b></td> <td><a href=upload/" . $_FILES["file"]["name"] . ">" . $_FILES["file"]["name"] . "</a></td> </tr> </table>"; exit(); } echo $display_errors; ?> I found the following help online, but I can't get it right. Can anyone help? Code: [Select] <?php //This function separates the extension from the rest of the file name and returns it function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } //This applies the function to our file $ext = findexts ($_FILES['uploaded']['name']) ; //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. $ran = rand () ; //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended. $ran2 = $ran."."; //This assigns the subdirectory you want to save into... make sure it exists! $target = "images/"; if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$ran2.$ext; } else { echo "Sorry, there was a problem uploading your file."; } ?> Hi Guys, I use this function to generate seo friendly names for my products once pulled from the database: function generate_seo_friendly_links($pNM, $pID) { $replacedNM = str_replace(" ", "-", $pNM); $replacedNM = rtrim($replacedNM); $brandNewSEOFriendlyURL = "<a href='$replacedNM-$pID.html'>$pNM</a>"; return $brandNewSEOFriendlyURL; } This works great, the only thing is say a product is stored in the database like: product name it would then be converted to: product-name.html if for example theres 2 spaces: product name it would then be converted to: product--name.html with the 2 "--" so for every space it finds we replace with a "-" etc is there a way i could ignore more than 1 space and always have it like product-name-here.html so the names are more uniformed, i can't think of a way to do it. any help would be appreciated thanks guys Graham I am reading hundreds of CSVs to import into a DB. Some of the column names contain the same data but have different names across all the files. For example, one file will say Phone where the other says EveningPhone...both contain the same data, different names. I am trying to rename everything to EveningPhone because I had most of the code done when i realized there were different header names in different files. Too lazy to replace all i guess.. I am creating an assoc array to match the data then off to the db it goes.. The problem is I cannot get the keys to rename to one convention. Here is the function where it happens: Code: [Select] public function readCSV($file) { /** * @todo: LOAD THE FILE INTO A MULTIDIMENSIONAL ASSOCIATIVE ARRAY TO DETERMINE THE FILEDS */ // Read the first line to get the headers $headers = fgetcsv($file); if (!array_key_exists('EveningPhone', $headers)) { if (array_key_exists('Phone', $headers)) { $headers['EveningPhone'] = $headers['Phone']; unset($headers['Phone']); } else { die("other"); } } format::neat_r($headers); // basically print_r but adds a new line to read it easier... die(); At the end, I still get EveningPhone not defined errors from a file that uses Phone as the phone number.. Anybody have any ideas? I'm using the following code in a WordPress functions file to rename a folder in the uploads folder according to the date, but this only works if the chmodd settings of both folders are 777. How can I change this code so I can use at least chmodd 755 to keep my website save. Code: [Select] date_default_timezone_set('Europe/Amsterdam'); // set timezone $foldername = ''; $source = 'uploads'; $allfolders = getDirectory($source); // get folders $folder = $source.'/'.$allfolders[0]; // get first folder $month = (int)date('n'); $day = (int)date('j'); $f = 50-$day; $s = 100-$month; $newfolder = $source.'/'.(string)$f.(string)$s; if($folder != '' && $folder != $newfolder){ rename($folder, $newfolder); $foldername = $newfolder."/"; }else if($folder == $newfolder){ $foldername = $newfolder."/"; } else{ $foldername = 'error'; } Hello guys another difficult form case (for me) I have this super long form that pulls different files depending on what you select. The form works perfectly fine right now. the problem is that now the client need to run the form with a SSL certificate due to gov regulations. we are hosting all the files in the same folder for the secure and unsecure site and the certificate works fine. however when I run the form with the https:// address google chrome tells me that parts of the form are unsecured. I was reading something about the images have to be on a relative path using img scr="../images/path/file.ext" instead of just img scr="images/path/file.ext". I made that change and it didnt solve the problem. I changed all the links to " ../ " and didn't solve the problem. I have added rules to the .htaccess file RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^contact https://www.example.net/new-service.php [R=301,L] RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteCond %{REQUEST_URI} somefolder RewriteRule ^(.*)$ https://www.example.net/inc/$1 [R,L] And even changed all the links in the form to absolute paths and nothing works. does anyone know how to force the form to work on SSL or troubleshoot SSL certificate errors to point me in the right direction thanks guys i appreciate your help and advice Hi, I want to update a txt files 10. row with a form but I could not it how can I do it? I currently have a small 2 page message board, the main file is named index.php and the other core.php - I would like to rename the main file with the form to chat.php, but when I do that, the script no longer posts messages, and goes to the website root. Can someone tell me whats wrong? Here is the form info from the current index.php (that i wish to rename chat.php) Code: [Select] <form action="./" method="post"> <p>name (25 chars max)<br> <input id="name" name="author" maxlength="20" size="25"></p> <p>message (150 chars max)<br> <input id="message" name="message" maxlength="150" size="45"></p> <p>what is <?php echo "$num1 &#43; $num2?" ?><br> <input id="captcha" name="captcha" maxlength="2" size="10"></p> <p><input id="submit" name="submit" type="submit" value="submit"> (ip addresses are recorded)</p> </form> and the 2nd file core.php's function that I think is acting up (here or with the form above?) function getPosts() { $author = isset($_POST['author']) ? $_POST['author'] : false; $message = isset($_POST['message']) ? $_POST['message'] : false; global $nameMax; global $messageMax; global $error; if ($author && $message && ($error==false) ) { if (strlen($author) <= $nameMax && strlen($message) <= $messageMax) { $this->inputPost($author, $message); header('Location: ./'); } Why when I rename index.php to chat.php is it not working and falling back to the website root when I submit? any help would be great! I am sure it is something simple, but I am new...
I have a hopefully small issue on a form submitting data to the mysql database table and email. The email side works fine as does the adding the data to the database table but if I upload two files, it stores the support ticket twice in the database table where as I want to store just once and the files be stored as a array in the database table. I got the code from the link https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/
<?php require_once "registerconfig.php"; if (isset($_POST['submit'])) { // File upload configuration $targetDir = "support-ticket-images/"; $allowTypes = array('pdf','doc','docx','jpg','png','jpeg','gif'); $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; // Escape user inputs for security $ticket_subject = htmlentities($_POST['ticket_subject'], ENT_QUOTES); $ticket_message = strip_tags($_POST['ticket_message'], ENT_QUOTES); $ticket_status ='PENDING SUPPORT'; $username = htmlentities($_SESSION["user_name"], ENT_QUOTES); $user_id = htmlentities($_SESSION["user_id"], ENT_QUOTES); $fileNames = array_filter($_FILES['files']['name']); if(!empty($fileNames)){ foreach($_FILES['files']['name'] as $key=>$val){ // File upload path $fileName = basename($_FILES['files']['name'][$key]); $targetFilePath = $targetDir . $fileName; // Check whether file type is valid $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ // Image db insert sql $insertValuesSQL .= "('".$ticket_subject."','".$ticket_message."','".$fileName."','".$ticket_status."','".$username."', '".$user_id."'),"; }else{ $errorUpload .= $_FILES['files']['name'][$key].' | '; } }else{ $errorUploadType .= $_FILES['files']['name'][$key].' | '; } } if(!empty($insertValuesSQL)){ $insertValuesSQL = trim($insertValuesSQL, ','); // Insert image file name into database $insert = $link->query("INSERT INTO DB TABLE NAME (ticket_subject, ticket_message, file_name, ticket_status, user_name, user_id) VALUES $insertValuesSQL"); if($insert){ $to = "emailaddress"; $subject = "A new support ticket has been submitted"; $message = " <strong>$username</strong> has just created a support ticket, below is the support ticket <br /><br /> <u>Support Ticket Details</u> <br /><br> <strong>Support Ticket Subject</strong>: $ticket_subject <br/><br><strong>Support Ticket Message</strong>: $ticket_message <p><strong><u>Support Ticket Files</u></strong> <br> <img src='$fileName'> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; // More headers $headers .= 'From: <noreply@emailaddress>' . "\r\n"; $mail=mail($to,$subject,$message,$headers); $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):''; $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; header("location: support-ticket-confirmation?user=$username"); }else{ $statusMsg = "Sorry, there was an error uploading your file."; } } }else{ $statusMsg = 'Please select files to upload.'; } // Display status message echo $statusMsg; } ?> The structure of the db table column is file_name, VARCHAR(255), latin1_swedish_ci, NOT NULL 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? |