PHP - File Upload Form Processing
Having some issues getting this to work properly... I keep getting my own error message
I know where it fails, but I can't seem to figure out why it fails. The test file I'm using is an MP3 file, which is why I'm here asking if anyone other than I can shed some experienced light on this :p Code: [Select] File Upload Failed! No File Exists!The file type or extension you are trying to upload is not allowed! You can only upload MP3 files to the server! My upload form looks like: <?php session_start(); define('PITCHFORK', true); if(!isset($_SESSION['USERS_AUTHENTICATED'])) { die("You must be logged in to do that"); } if(isset($_POST['upload'])) { include("config.php"); include("classes/class.media.upload.php"); $file = $_GET['file']; $upload = new Upload; $upload->doAudio($file); } ?> <!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>PITCHFORK Login</title> <link rel="stylesheet" href="style/login.css" type="text/css" media="all"> <meta name="robots" content="noindex,nofollow"> </head> <body> <div id="login"><h1><a title="A SpaazZ Industries Concept"></a></h1> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label>File (one at a time for now)<br> <input name="file" id="user_login" class="input" size="20" tabindex="10" type="file" /> </label> </p> <p> </p> <?php if(isset($_SESSION['errMessage'])) { echo("<div id=\"login_error\"><strong>ERROR</strong>:<br />"); echo($_SESSION['errMessage']); unset($_SESSION['errMessage']); echo("</div>"); } ?> <p class="submit"> <input name="upload" id="submit" class="button-primary" value="Upload File" tabindex="100" type="submit"> </p> </form> </div> </body> </html> My Upload Class looks liks: <?php // TO DO : ERROR HANDLING // AJAX INTERFACING session_start(); define('PITCHFORK', true); class Upload { // The path to local (relivent to the user uploading - on their computer) file var $file; public function doAudio($file) { $target_path = $_SESSION['USERS_Media_Folder']."/"; // Set at login in class.users.php $flag = 0; // Safety net, if this gets to 1 at any point in the process, we don't upload. $filename = $_FILES[$file]['name']; $filesize = $_FILES[$file]['size']; $mimetype = $_FILES[$file]['type']; $filename = htmlentities($filename); $filesize = htmlentities($filesize); $mimetype = htmlentities($mimetype); $target_path = $target_path . basename( $filename ); if($filename != ""){ echo "Beginning upload process for file named: ".$filename."<br>"; echo "Filesize: ".$filesize."<br>"; echo "Type: ".$mimetype."<br><br>"; } //First generate a MD5 hash of what the new file name will be //Force a MP3 extention on the file we are uploading $hashedfilename = md5_file($filename); $hashedfilename = $hashedfilename.".mp3"; //Check for empty file if($filename == ""){ $_SESSION['errMessage'] .= "No File Exists!"; $flag = $flag + 1; } //Now we check that the file doesn't already exist. $existname = $target_path.$hashedfilename; if(file_exists($existname)) { if($flag == 0) { $_SESSION['errMessage'] .= "Your file already exists on the server! Please choose another file to upload or rename the file on your computer and try uploading it again!"; } $flag = $flag + 1; } //Whitelisted files - Only allow files with MP3 extention onto server... $whitelist = array(".mp3"); foreach ($whitelist as $ending) { if(substr($filename, -(strlen($ending))) != $ending) { $_SESSION['errMessage'] .= "The file type or extention you are trying to upload is not allowed! You can only upload MP3 files to the server!"; $flag++; } } //Now we check the filesize. If it is too big or too small then we reject it //MP3 files should be at least 1MB and no more than 6.5 MB if($filesize > 6920600) { //File is too large if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too large! Your file can be up to 6.5 MB in size only. Please upload a smaller MP3 file or encode your file with a lower bitrate."; } $flag = $flag + 1; } if($filesize < 1048600) { //File is too small if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too small! Your file has been marked as suspicious because our system has determined that it is too small to be a valid MP3 file. Valid MP3 files must be bigger than 1 MB and smaller than 6.5 MB."; } $flag = $flag + 1; } //Check the mimetype of the file if($mimetype != "audio/x-mp3" and $mimetype != "audio/mpeg") { if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload does not contain expected data. Are you sure that the file is an MP3?"; } $flag = $flag + 1; } //Check that the file really is an MP3 file by reading the first few characters of the file $f = @fopen($_FILES[$file]['tmp_name'],'r'); $s = @fread($f,3); @fclose($f); if($s != "ID3") { if($flag == 0){ $_SESSION['errMessage'] .= "The file you are attempting to upload does not appear to be a valid MP3 file."; } $flag++; } //All checks are done, actually move the file... if($flag == 0) { if(move_uploaded_file($_FILES[$file]['tmp_name'], $target_path)) { //Change the filename to MD5 hash and FORCE a MP3 extention. if(@file_exists($target_path.$filename)) { //Rename the file to an MD5 version rename($target_path.$filename, $target_path.$hashedfilename); echo "The file ". basename( $filename ). " has been uploaded. Your file is <a href='$target_path$hashedfilename'>here</a>."; } else{ echo "There was an error uploading the file, please try again!"; } } else { echo "There was an error uploading the file, please try again!"; } } else { echo "File Upload Failed!<br>"; if($error != "") { echo $error; } } } // Close function doAudio } // Close Class audioUpload ?> Similar TutorialsHi can someone assist me with adding a second upload that grabs all files from within a directory. 1. user select .csv file (coding down for that) 2. user select folder with .docx files in side (this folder will only have docx files) 3. on submit .csv and all .docx files are upload to /temp_docx/ folder 4. the .csv has a matching docx_id that relates to the .docx file name (ex file 1.docx == docx_id = 1 in the csv file) so every time an insert is done a move_file happens and 1.docx would be moved to /docx_files/ 5. and if there is ever an error or no match at the end output all errors. I think the part where i'm stuck and confused the most is handling the second upload where all docx files in the folder are upload and looped through moving and inserting Code: [Select] <?php if(isset($_POST['submit'])) { $filename = file_get_contents($_FILES['uploadedfile']['tmp_name']); $handle = fopen("$filename", "r"); while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) { $import="INSERT into kmmb_member1(docx_id,no_ahli,no_pin,nama,no_ic_baru,no_ic_lama) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; } else { print "<form action='import.php' method='post'>"; print "Type file name to import:<br />"; print "Select csv file: <input name='uploadedfile' type='file' /><br />"; print "<input type='submit' name='submit' value='submit' /></form>"; } ?> I tried to add a second file upload to my previously properly functioning form, but after adding it, now when I submit the form, it submits the data twice. It appears to be submitting the file right on the first insert, but on the second insert, the second image is not inserted, but just blank. Can anyone help me figure out why? I must have done something wrong in my insert statement or second file statement. Here is the page itself which contains the form: http://midwestcreativeconsulting.com/jhrevell/add/ And below is my insert page: Code: [Select] <?php $dbhost = 'localhost'; $dbuser = 'username'; $dbpass = 'password'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'jhrevell_jewelry'; mysql_select_db($dbname); $name = $_POST['name']; $metal = $_POST['metal']; $desc = $_POST['desc']; $item_no = $_POST['item_no']; $cut = $_POST['cut']; $color = $_POST['color']; $carats = $_POST['carats']; $clarity = $_POST['clarity']; $size = $_POST['size']; $type = $_POST['type']; $other = $_POST['other']; $total = $_POST['total']; $certificate = $_POST['certificate']; $value = $_POST['value']; //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { //echo "Upload: " . $_FILES["file"]["name"] . "<br />"; //echo "Type: " . $_FILES["file"]["type"] . "<br />"; //echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image = $_FILES["file"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} // IMAGE 2 // //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file2"]["error"] > 0) { echo "Return Code: " . $_FILES["file2"]["error"] . "<br />"; } else { //echo "Upload: " . $_FILES["file"]["name"] . "<br />"; //echo "Type: " . $_FILES["file"]["type"] . "<br />"; //echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file2"]["name"])) { echo $_FILES["file2"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file2"]["tmp_name"], "upload/" . $_FILES["file2"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image2 = $_FILES["file2"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} echo '<script language="Javascript">'; echo 'window.location="http://midwestcreativeconsulting.com/jhrevell/collections"'; echo '</script>'; ?> Can anyone see what could be causing it to insert the record twice? files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
I've looked over it a couple times and I still get the error. Here's the code <?php require('header.php'); require('links.php'); $name = mysql_real_escape_string($_POST['file']); $url = mysql_real_escape_string($_POST['file']); $filename = $_FILES['file']['name']; $temp = $_FILES['file']['tmp_name']; $error = $_FILES['file']['error']; $sql = "insert into books set name='$name', url='$url'"; if(isset($_POST['submit'])) { if($error > 0) { die("Error uploading file! Code $error."); }else{ move_uploaded_file($temp,"/center/resources/books/".$filename); mysql_query($sql); } } ?> <form method='post' enctype='multipart/form-data'> Book Name<input type="text" name="name"></br> File<input type="file" name="file"></br> <input type="submit" name="submit" value="Upload"> </form> I have been spending the majority of this week figuring out why my files are not showing up at my upload location that I set up in my newly created simple upload form. It just seems like php doesn't like me at all. Here is what my code looks like below. Code: [Select] <?php if (move_uploaded_file($_FILES['thefile']['name'], $upload_file)) $destination = "/www/zymichost.com/m/t/l/mtlproductions/htdocs/"; $upload_file = $destination . basename($_FILES['thefile']['name']);{ echo "Your file has been uploaded successfully!"; }/* else { echo "Your file did not upload successfully. Check to make sure your file meets the requirements and then try again."; print_r($_FILES);}*/?> I have the orange marked areas commented out due to the unexpected T_ELSE error thing. What do I do to get my files to show up at my upload location when I use my upload form? Thanks! I want to let users select and upload a file. The select form and upload sritp work when they are on different pages, but I want them on the same page with the upload script executing only if the form has been submitted. Here the upload form <!--select the file --> <form enctype="multipart/form-data" action="manage_files.php" method="POST">Please choose a file to upload: <input name="uploaded" type="file" /><input type="submit" value="Upload" /></form> ... and here's the upload code... <!--upload the file --> <?php if (isset($_POST['submit'])) { $target = "safes/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition //if ($uploaded_size > 350000) //{ //echo "Your file is too large.<br>"; //$ok=0; //} //if (!($uploaded_type=="application/zip")) { //echo "You may only upload ZIP files.<br>"; //$ok=0; //} //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } } ?> What am I missing? Thanks for any help! Hi all I have a script that I have patched together and got to work in pieces. I'm up to the last part. I have the form working and emailing. It also will upload an image by itself and put it in a folder. Now i just need to tie those together and have the image put in the email as an attachment then deleted from server. I have it at a stage where it sends me the users details.. and it tries to send the photo but it comes through as junk txt. I think its the MIME encoding stuff that I have wrong.. not sure? Here's what I have so far. Code: [Select] $attachment = $path_of_uploaded_file; $fileatt = $attachment; // Path to the file $fileatt_type = "application/octet-stream"; // File Type $start= strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1; $fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers = "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n"; // create email headers $headers .= 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); Thanks Wolfsta I have an excel file that has several columns with different data and I need to create a form that can upload this excel file and insert the data from the columns into its conrresponding data columns in a mysql database. I know how to create the form but I have no idea how to get the file and tell it to input each cell of data into its corresponding field in the mysql database. Does anyone know how to do this? Any help would be appreciated. Thanks, I'm trying to add a file size limit to my upload form-code (below) Hi, I have a form that allows a user to enter details and also to upload a image. The form works great and inserts into the database if i dont include the file input. What i would like happen is: The user enters details and selects a file The file then gets uploaded to ../images and the path is then written to bedroom1 variable The addresses and the bedroom1 variable that now holds the uploaded file path e.g. images/test.jpg is written to the database Form Code: [Select] <form action="admin.php" method="POST"> <table> <tr><td> Address 1: </td><td> <input type="text" name="address1" id="address1" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> Address 2: </td><td> <input type="text" name="address2" id="address2" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> County: </td><td> <input type="text" name="county" id="county" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> Bedroom 1: </td><td> <input type="file" name="bedroom1" id="bedroom1" input name="uploadedfile"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> <input type="submit" name="submitaddapartment" value="Add" id="registerbutton"> </td></tr> </table </form> And the php code to add it to the database Code: [Select] <?php //get variables $submitaddapartment = $_POST['submitaddapartment']; $address1 = strip_tags($_POST['address1']); $address2 = strip_tags($_POST['address2']); $county = strip_tags($_POST['county']); $bedroom1 = strip_tags($_POST['bedroom1']); if ($submitaddapartment) //if submit button was pressed { if ($address1&&$address2&&$county&&$bedroom1&&) //if fields arn't blank { include 'dbase.php'; //connect to database if ((($_FILES["bedroom1"]["type"] == "image/gif") || ($_FILES["bedroom1"]["type"] == "image/jpg") || ($_FILES["bedroom1"]["type"] == "image/pjpeg")) && ($_FILES["bedroom1"]["size"] < 20000000)) { if ($_FILES["bedroom1"]["error"] > 0) { echo "Return Code: " . $_FILES["bedroom1"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["bedroom1"]["name"] . "<br />"; echo "Type: " . $_FILES["bedroom1"]["type"] . "<br />"; echo "Size: " . ($_FILES["bedroom1"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["bedroom1"]["tmp_name"] . "<br />"; if (file_exists("../images/" . $_FILES["bedroom1"]["name"])) { echo $_FILES["bedroom1"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["bedroom1"]["tmp_name"], "/" . $_FILES["bedroom1"]["name"]); echo "Stored in: " . "../images/" . $_FILES["bedroom1"]["name"]; $bedroom1=".'images/.' $_FILES["bedroom1"]["name"]"; } } } else { echo "Invalid file"; } mysql_query ("INSERT INTO user VALUES(NULL,'$address1','$address2','$county','$bedroom1')"); } else { } } ?> Any help would be greatly appreciated. Thanks Fred I have a one-page responsive website template with a built-in contact email form whereby I would like to add an upload file attachment provision to the contact form. While I have been able to successfully add two fields (source, URL) to the built-in contact email form, with exception of adding the HTML to the form , modification to the contact email form's PHP files appears to be much more involved whereby I have been unable to find a barebones PHP code I can add to the existing PHP to make this work. I should also add that while I am well versed in HTML, CSS, and Javascript, I am not when it comes to PHP. In brief, I prefer not to replace the built-in contact form with different HTML and PHP for adding a contact form email file attachment. Any suggestions regarding this subject matter are appreciated. Since PHP is not listed under accepted file types for attachment to this post, I can provide download links to the contact email form PHP files from my iHost server for review if need be. The website address to view the HTML source code for the built-in contact form is https://www.seoauditspecialists.com. Apart from my having to add 'enctype=”multipart/form-data”' to the contact form's <form action> line of code, the HTML to add the 'file' field is provided below. Thank you ahead of time.
<div class="form-group"> Hi, This is the code I made to show the problem: $useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729)"; $timeout = 10 ; $cookie = tempnam ("/tmp", "CURLCOOKIE"); $post = array('_method'=>"put", 'authenticity_token'=>' zcvcxfsdfvxcv', 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg" ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_USERAGENT, $useragent); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_URL, "http://localhost/test.php"); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); curl_setopt( $ch, CURLOPT_ENCODING, "" ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $html = curl_exec($ch); curl_close($ch); Now this link used above: http://localhost/test.php has this code: print_r($_POST); print_r($_FILES); It simply prints whats in post and files. So the above code displays this on screen: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image] => Array ( [name] => Array ( [a] => Girl-Next-Door-movie-f01.jpg ) [type] => Array ( [a] => image/jpeg ) [tmp_name] => Array ( [a] => /tmp/phppLJPQV ) [error] => Array ( [a] => 0 ) [size] => Array ( [a] => 55377 ) ) ) but we need to modify the code so that it should display this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) Meaning, it is taking this(profile_image[a]) as an array when we are defining $post because that's how curl recognizes that we want to upload only a file or an array of files on server by http post. So, basically the problem is the name of the input field that is defined as an array (profile_image[a]) on the web page that we are trying to mock. If this(profile_image[a]) was this (profile_image_a)(without []) on that webpage, then it would not have been a problem. So, if you understand, this is basically a syntax problem. I do not know how stop curl from reading 'profile_image[a]' as an array here 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg. I need curl to read 'profile_image[a]' as an string and not array. I have to use [], otherwise I will not be able to mock the webpage as the name will change. It will give error. I hope I explained the problem and also gave you a way to test if you have a solution. Again, if your code starts displaying this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) ,then we have a solution. Thanks for helping in advance. Regards, Manoj Hello, Im trying to find a way to check around 500-600 links to check if they are alive. It works fine for 5-6 links but once i add more links it just times out. Is there a way i could process this so it does 1 link at a time or somthing ? <?php include("config.php"); $query = "SELECT * FROM `games` WHERE `r_fileserve` <> \"\" LIMIT 500"; $result = mysql_query($query); while($row=mysql_fetch_assoc($result)) { $link_str = file_get_contents("$row[r_fileserve]"); $pattern = '<input type="hidden" name="download" value="normal"/>'; preg_match($pattern,$link_str,$match); if ($match[0] != null) { echo "Working <br />"; } else { echo "File Down <br />"; } } ?> If I want to read in and process a CSV of a 1000 lines how easy is it to do without a database? By process, I mean read in the data and do simple manipulations + compare each line with a line from another file, that maybe have 50 lines I was just concerned that I might start hogging the CPU and memory of the server trying to process 1000 lines of data It's VERY important that I can do WITHOUT a database I'd only consider a database if it proves that not using will take too much CPU and memory I've only just began considering making the application - can't give full details - as I've got to figure them out myself! Any general advice would be great Thanks OM I have a PHP file that does some data processing work in the database and I run in from a web browser each weekend. The PHP file usually completes the job in 4 hours, but past 2 weekends, it failed to complete. Then, i need to reexecute the file. Why? And how to fix this? Can you take a look at this page? It uses php code that I have been creating. I need it to accept the form even if checkboxes are left empty. Currently it comes up with an error. http://www.pilotrock.com/color_contact/ Here is the PHP code: <?php if(isset($_POST['Email_Address'])) { include 'lite_settings.php'; function died($error) { echo "Sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br /><br />"; echo $error."<br /><br />"; echo "Please go back and fix these errors.<br /><br />"; die(); } if(!isset($_POST['organization']) || !isset($_POST['Full_Name']) || !isset($_POST['title']) || !isset($_POST['company']) || !isset($_POST['address']) || !isset($_POST['city_state']) || !isset($_POST['zip']) || !isset($_POST['Telephone_Number']) || !isset($_POST['cell_phone']) || !isset($_POST['fax']) || !isset($_POST['Email_Address']) || !isset($_POST['confirm_email']) || !isset($_POST['powder_coated_steel_blue']) || !isset($_POST['powder_coated_steel_black']) || !isset($_POST['powder_coated_steel_green']) || !isset($_POST['powder_coated_steel_brown']) || !isset($_POST['powder_coated_steel_yellow']) || !isset($_POST['powder_coated_steel_red']) || !isset($_POST['powder_coated_steel_gray']) || !isset($_POST['powder_coated_steel_burgendy']) || !isset($_POST['thermo_plastic_coated_type_expanded']) || !isset($_POST['thermo_plastic_coated_type_perforated']) || !isset($_POST['thermo_plastic_coated_black']) || !isset($_POST['thermo_plastic_coated_blue']) || !isset($_POST['thermo_plastic_coated_brown']) || !isset($_POST['thermo_plastic_coated_gray']) || !isset($_POST['thermo_plastic_coated_red']) || !isset($_POST['thermo_plastic_coated_green']) || !isset($_POST['recycle_plastic_red']) || !isset($_POST['recycle_plastic_yellow']) || !isset($_POST['recycle_plastic_black']) || !isset($_POST['recycle_plastic_blue']) || !isset($_POST['recycle_plastic_gold']) || !isset($_POST['recycle_plastic_redwood']) || !isset($_POST['recycle_plastic_cedar']) || !isset($_POST['recycle_plastic_green']) || !isset($_POST['recycle_plastic_gray']) || !isset($_POST['recycle_plastic_brown'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $organization = $_POST['organization']; // required $full_name = $_POST['Full_Name']; // required $title = $_POST['title']; // not required $company = $_POST['company']; // not required $address = $_POST['address']; // required $city_state = $_POST['city_state']; // required $zip = $_POST['zip']; // required $telephone = $_POST['Telephone_Number']; // required $cell_phone = $_POST['cell_phone']; // not required $fax = $_POST['fax']; // not required $email_from = $_POST['Email_Address']; // required $confirm_email = $_POST['confirm_email']; // required $powder_coated_steel_blue = $_POST['powder_coated_steel_blue']; // required $powder_coated_steel_black = $_POST['powder_coated_steel_black']; // required $powder_coated_steel_green = $_POST['powder_coated_steel_green']; // required $powder_coated_steel_brown = $_POST['powder_coated_steel_brown']; // required $powder_coated_steel_yellow = $_POST['powder_coated_steel_yellow']; // required $powder_coated_steel_red = $_POST['powder_coated_steel_red']; // required $powder_coated_steel_gray = $_POST['powder_coated_steel_gray']; // required $powder_coated_steel_burgendy = $_POST['powder_coated_steel_burgendy']; // required $thermo_plastic_coated_type_expanded = $_POST['thermo_plastic_coated_type_expanded']; // required $thermo_plastic_coated_type_perforated = $_POST['thermo_plastic_coated_type_perforated']; // required $thermo_plastic_coated_black = $_POST['thermo_plastic_coated_black']; // required $thermo_plastic_coated_blue = $_POST['thermo_plastic_coated_blue']; // required $thermo_plastic_coated_brown = $_POST['thermo_plastic_coated_brown']; // required $thermo_plastic_coated_gray = $_POST['thermo_plastic_coated_gray']; // required $thermo_plastic_coated_red = $_POST['thermo_plastic_coated_red']; // required $thermo_plastic_coated_green = $_POST['thermo_plastic_coated_green']; // required $recycle_plastic_red = $_POST['recycle_plastic_red']; // required $recycle_plastic_yellow = $_POST['recycle_plastic_yellow']; // required $recycle_plastic_black = $_POST['recycle_plastic_black']; // required $recycle_plastic_blue = $_POST['recycle_plastic_blue']; // required $recycle_plastic_gold = $_POST['recycle_plastic_gold']; // required $recycle_plastic_redwood = $_POST['recycle_plastic_redwood']; // required $recycle_plastic_cedar = $_POST['recycle_plastic_cedar']; // required $recycle_plastic_green = $_POST['recycle_plastic_green']; // required $recycle_plastic_gray = $_POST['recycle_plastic_gray']; // required $recycle_plastic_brown = $_POST['recycle_plastic_brown']; // required $error_message = ""; $email_exp = "^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$"; if(!eregi($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.<br />'; } if(strlen($full_name) < 2) { $error_message .= 'Your Name does not appear to be valid.<br />'; } if(strlen($address) < 2) { $error_message .= 'Your Address does not appear to be valid.<br />'; } if(strlen($city_state) < 2) { $error_message .= 'Your City/State does not appear to be valid.<br />'; } if(strlen($zip) < 2) { $error_message .= 'Your Zip/Postal Code does not appear to be valid.<br />'; } if(strlen($telephone) < 2) { $error_message .= 'Your Telephone Number does not appear to be valid.<br />'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\r\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "Organization: ".clean_string($organization)."\r\n"; $email_message .= "Full Name: ".clean_string($full_name)."\r\n"; $email_message .= "Title: ".clean_string($title)."\r\n"; $email_message .= "Company Name: ".clean_string($company)."\r\n"; $email_message .= "Street Address: ".clean_string($address)."\r\n"; $email_message .= "City/State: ".clean_string($city_state)."\r\n"; $email_message .= "ZIP/Postal Code: ".clean_string($zip)."\r\n"; $email_message .= "Telephone: ".clean_string($telephone)."\r\n"; $email_message .= "Cell Phone: ".clean_string($cell_phone)."\r\n"; $email_message .= "Fax: ".clean_string($fax)."\r\n"; $email_message .= "Email: ".clean_string($email_from)."\r\n"; $email_message .= "Confirm Email: ".clean_string($confirm_email)."\r\n"; $email_message .= "Powder Coated Steel Blue: ".clean_string($powder_coated_steel_blue)."\r\n"; $email_message .= "Powder Coated Steel Black: ".clean_string($powder_coated_steel_black)."\r\n"; $email_message .= "Powder Coated Steel Green: ".clean_string($powder_coated_steel_green)."\r\n"; $email_message .= "Powder Coated Steel Brown: ".clean_string($powder_coated_steel_brown)."\r\n"; $email_message .= "Powder Coated Steel Yellow: ".clean_string($powder_coated_steel_yellow)."\r\n"; $email_message .= "Powder Coated Steel Red: ".clean_string($powder_coated_steel_red)."\r\n"; $email_message .= "Powder Coated Steel Gray: ".clean_string($powder_coated_steel_gray)."\r\n"; $email_message .= "Powder Coated Steel Burgendy: ".clean_string($powder_coated_steel_burgendy)."\r\n"; $email_message .= "Thermo Plastic Coated Type Expanded: ".clean_string($thermo_plastic_coated_type_expanded)."\r\n"; $email_message .= "Thermo Plastic Coated Type Perforated: ".clean_string($thermo_plastic_coated_type_perforated)."\r\n"; $email_message .= "Thermo Plastic Coated Black: ".clean_string($thermo_plastic_coated_black)."\r\n"; $email_message .= "Thermo Plastic Coated Blue: ".clean_string($thermo_plastic_coated_blue)."\r\n"; $email_message .= "Thermo Plastic Coated Brown: ".clean_string($thermo_plastic_coated_brown)."\r\n"; $email_message .= "Thermo Plastic Coated Gray: ".clean_string($thermo_plastic_coated_gray)."\r\n"; $email_message .= "Thermo Plastic Coated Red: ".clean_string($thermo_plastic_coated_red)."\r\n"; $email_message .= "Thermo Plastic Coated Green: ".clean_string($thermo_plastic_coated_green)."\r\n"; $email_message .= "Recycle Plastic Red: ".clean_string($recycle_plastic_red)."\r\n"; $email_message .= "Recycle Plastic Yellow: ".clean_string($recycle_plastic_yellow)."\r\n"; $email_message .= "Recycle Plastic Black: ".clean_string($recycle_plastic_black)."\r\n"; $email_message .= "Recycle Plastic Blue: ".clean_string($recycle_plastic_blue)."\r\n"; $email_message .= "Recycle Plastic Gold: ".clean_string($recycle_plastic_gold)."\r\n"; $email_message .= "Recycle Plastic Redwood: ".clean_string($recycle_plastic_redwood)."\r\n"; $email_message .= "Recycle Plastic Cedar: ".clean_string($recycle_plastic_cedar)."\r\n"; $email_message .= "Recycle Plastic Green: ".clean_string($recycle_plastic_green)."\r\n"; $email_message .= "Recycle Plastic Gray: ".clean_string($recycle_plastic_gray)."\r\n"; $email_message .= "Recycle Plastic Brown: ".clean_string($recycle_plastic_brown)."\r\n"; $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); header("Location: $thankyou"); ?> <script>location.replace('<?php echo $thankyou;?>')</script> <? } ?> I have a form that is not doing anything after I click "submit". The code is below and a demo with the code is he http://communitycouch.com/index.php?action=register Code: [Select] <?php /* Things to do: Create error to show error when special characters are inputted in First and Last Name Fields Verify Dates to be true upon submit (for bithdays) Create birthday variable to be submitted into database, also add is_numberic() change activate.php to index?action=activate */ if($action == 'register') { if (isset($_POST['submit'])) { $errors = array(); require_once('connection.php'); //////////Checks Username //////////Makes sure username is 4-20 characters and contains only letters and numbers if(ereg("[[:alnum:]]{4,20}",stripslashes(trim($_POST['username'])))) { $user = mysql_real_escape_string($_POST['username']); $query = "SELECT username FROM reg_vars WHERE username = '$username'"; $result = @mysql_query($query); $num = @mysql_num_rows($result); if ($num> 0) { $errors[] = '<font color="red">The username you have chosen has already been taken, please try again.</font>'; } else { $username = mysql_real_escape_string($_POST['username']); } } else { $errors[] = '<font color="red">Please provide a valid username between 4 and 30 characters.</font>'; } //////////Checks E-mail if (!eregi('^[a-zA-Z]+[a-zA-Z0-9_-]*@([a-zA-Z0-9]+){1}(\.[a-zA-Z0-9]+){1,2}', stripslashes(trim($_POST['email'])) ) || empty($_POST['email'])) { $errors[] = '<font color="red">Please provide a valid email address.</font>'; } else { $email = mysql_real_escape_string($_POST['email']); } ///////// Check Names if (empty($f_name)) { $error["f_name"] = "First Name is blank."; } if (empty($l_name)) { $error["l_name"] = "Last Name is blank."; } ////////// Check PASSWORDS if (!empty($_POST['password'])) { if ($_POST['password'] != $_POST['cpassword']) { $errors[] = '<font color="red">The passwords you have entered do not match.</font>'; } else { $password = $_POST['password']; } } else { $errors[] = '<font color="red">Please provide a password.</font>'; } /////////Send Activation E-mail //////// Add Birthday to the registrarion Variables if (empty($errors)) { $a = md5(uniqid(rand(), true)); $query = "INSERT INTO reg_vars (username, f_name, l_name, email, password, active) VALUES ('$username', '$email', SHA1('$password'), '$a')"; $result = @mysql_query($query); if (mysql_affected_rows() == 1) { ////////// Send the Activation email $body = "Thank you for registering at the User Registration site. To activate your account, please click on this link:\n\n"; $body .= "http://www.communitycouch.com/activate.php?x=" . mysql_insert_id() . "&y=$a"; mail($_POST['email'], 'Registration Confirmation', $body, 'From: noreply@communitycouch.com'); ////////// Show thank you message echo '<h3>Thank You!</h3> You have been registered, you have been sent an e-mail to the address you specified before. Please check your e-mails to activate your account.'; } else { echo '<font color="red">You could not be registered, please contact us about the problem and we will fix it as soon as we can.</font>'; } } else { echo '<h3>Error!</h3> The following error(s) occured:<br />'; foreach ($errors as $msg) { echo " <div id=\"success_or_fail\"><font color=\"red\">$msg</font><br />\n</div>"; } } } echo " <div id=\"register_container\" class=\"Container\"> <div id=\"register_Center\" class=\"BoxCenter\"> "; echo" <div id=\"register_BoxContainer\" class=\"Container\"> <div class=\"HeaderLeft\"></div><div id=\"register_Header\" class=\"HeaderCenter\">Register for Community Couch</div><div class=\"HeaderRight\"></div><br /> <div id=\"register_Content\" class=\"BoxContent\"> <form name=\"reg_form\" action=\"";$_SERVER['PHP_SELF']; echo"\" method=\"post\" style=\"margin: 0;\"> <div class=\"Container FormBoxLeft\"> <b>Username:</b> </div> <div class=\"Container FormBoxRight\"> <input name=\"username\" size=\"30\" type=\"text\" /> </div> <br class=\"EndColumn\" /> <div class=\"Container FormBoxLeft\"> <b>First Name:</b> </div> <div class=\"Container FormBoxRight\"> <input name=\"f_name\" size=\"30\" type=\"text\" /> </div> <br class=\"EndColumn\" /> <div class=\"Container FormBoxLeft\"> <b>Last Name:</b> </div> <div class=\"Container FormBoxRight\"> <input name=\"l_name\" size=\"30\" type=\"text\" /> </div> <br class=\"EndColumn\" /> <div class=\"Container FormBoxLeft\"> <b>Birthdate:</b> </div> <div class=\"Container FormBoxRight\"> <select name=\"month\"><option value=\"\">-Month-</option> <option value=\"01\">January</option> <option value=\"02\">February</option> <option value=\"03\">March</option> <option value=\"04\">April</option> <option value=\"05\">May</option> <option value=\"06\">June</option> <option value=\"07\">July</option> <option value=\"08\">August</option> <option value=\"09\">September</option> <option value=\"10\">October</option> <option value=\"11\">November</option> <option value=\"12\">December</option> </select> <select name=\"day\"> <option value=\"\"> -Day-</option>'; //Print 31 Days "; for ($x=1; $x<=31; $x++) { echo "<option value='".$x."'"; if(isset($_POST['submit']) && $day == $x) { echo " selected"; } echo ">".$x."</option>\n"; } echo "</select> <input name=\"year\" size=\"2\" maxlength=\"4\" type=\"text\"> </div> <br class=\"EndColumn\" /> <div class=\"Container FormBoxLeft\"> <b>E-Mail:</b> </div> <div class=\"Container FormBoxRight\"> <input name=\"email\" size=\"30\" type=\"text\" /> </div> <br class=\"EndColumn\" /> <div class=\"Container FormBoxLeft\"> <b>Display E-Mail to the Public:</b> </div> <div class=\"Container FormBoxRight\"> <input name=\"disp_email\" value=\"yes\" type=\"radio\" /> Yes <input name=\"disp_email\" value=\"no\" type=\"radio\" checked /> No </div> <br class=\"EndColumn\" /> <div class=\"Container FormBoxLeft\"> <b>Password:</b> </div> <div class=\"Container FormBoxRight\"> <input name=\"password\" size=\"30\" type=\"password\" /> </div> <br class=\"EndColumn\" /> <div class=\"Container FormBoxLeft\"> <b>Confirm Password:</b> </div> <div class=\"Container FormBoxRight\"> <input name=\"cpassword\" size=\"30\" type=\"password\" /> </div> <br class=\"EndColumn\" /> <div id=\"register_submit\" class=\"Container\"> <input name=\"tos\" type=\"checkbox\" /> I have read and agree to the Terms of Use and Privacy Policy<br /> <input type=\"submit\" value=\"Submit\"><input type=\"reset\" value=\"Reset\"> </div> <br class=\"EndColumn\" /> </form> </div> <div class=\"FooterLeft\"></div><div id=\"register_Footer\" class=\"FooterCenter\"></div><div class=\"FooterRight\"></div> </div> </div> </div> <br class=\"EndColumn\" /> <br />"; }?> [\code] So I know a little about PHP but I am no expert by any means. But I have a project that I am working on for a fantasy football league and need some help. My users pick players from a list and then their selections are put into a database. So more than one user is likely to pick the same player. Then I need to score the players based off their games for the week. So I have code that gets the Distinct PlayerID and creates a form to update the player score (see code below), but I have no idea how to process the form. It's a little more complicated then the forms I've used before because the MySQL query would need to UPDATE all the rows for each individual PlayerID. Am I making any sense? Anyway, here is the code. If anyone has suggestions on how to process this form or a better way of doing it then please let me know. <? print '<form id="form1" name="form1" method="post" action="update_player.php">'; // Connecting, selecting database $link = mysql_connect('localhost','user','pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } //Query $query=mysql_query("select DISTINCT(PlayerID), PlayerName, Team From fantasy4.temp ORDER BY Team;") or die ('Could not connect: ' . mysql_error()); print' <center> <table align=center border=0 cellpadding=0 cellspacing=2 width=350> <tr align=center> <td width=50 align=center><b>Player ID </b></td> <td width=50 align=center><b>Team</b></td> <td width=200 align=center><b>Player Name</b></td> <td width=50 align=center><b>Score</b></td> <tr><td colspan="10" bgcolor="black" height="1"></td></tr> '; while($row=mysql_fetch_array($query)){ if($color == 1) { print '<tr bgcolor=#dDdDdD> <td align=center> ' . $row['PlayerID'] . ' </td> <td align=center> ' . $row['Team'] . ' </td> <td align=center> ' . $row['PlayerName'] . ' </td> <td align=center> <input name="' . $row['PlayerID'] . '" type="text" id="' . $row['PlayerID'] . '" size="5" maxlength="5" /> </td> </tr>'; $color=0; } else { print '<tr> <td align=center> ' . $row['PlayerID'] . ' </td> <td align=center> ' . $row['Team'] . ' </td> <td align=center> ' . $row['PlayerName'] . ' </td> <td align=center> <input name="' . $row['PlayerID'] . '" type="text" id="' . $row['PlayerID'] . '" size="5" maxlength="5" /> </td> </tr>'; $color=1; } } print '</table>'; print '<input type="submit" name="button" id="button" value="Update Player Scores" /></form>'; ?> This is what I tried that did not work <? // Connecting, selecting database $link = mysql_connect('localhost','user','pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } //Query $query=mysql_query("select DISTINCT(PlayerID) From fantasy4.temp;") or die ('Could not connect: ' . mysql_error()); while($row=mysql_fetch_array($query)){ $PlayerID = $_POST[$row['PlayerID']]; } while($score = array($_POST['$PlayerID'])){ //Insert Query $query2=mysql_query("UPDATE fantasy4.temp set Score='$score' where PlayerID='$PlayerID'") or die ('Yikes could not connect: ' .mysql_error()); $result = @mysql_query($query2); } //Check whether the query was successful or not if($result) { header("location: register-success.php"); exit(); }else { die("Query failed - " .mysql_error()); } ?> I've read the php manual and a good few posts with similar but not identical problems and I am struggling to understand how to do this. Ive tailored my test site to help describe the problems that I have. www.peterod.co.uk the form is the first link in the left hand bar. Here is the code that creates the form. <?php // make connection require_once "../classes/sqlconselfbuild.php"; $query = mysql_query("SELECT * FROM `materials` ORDER BY `id` ASC"); ?> <form action="../engines/testengine1.php" method="post"> <?php // results while ($row = mysql_fetch_array($query)): $id = $row['id']; ?> <p> id number: <input type="text" name="materials[<?php echo $id; ?>][name]" value="<?php echo $row['id']; ?>" /> Material: <input type="text" name="materials[<?php echo $id; ?>][material]" value="<?php echo $row['material']; ?>" /> Stage: <input type="text" name="materials[<?php echo $id; ?>] [stage]" value="<?php echo $row['stage']; ?>" /> Qantity: <input type="text" name="materials[<?php echo $id; ?>][quantity]" value="<?php echo $row['quantity']; ?>" /> Unit: <input type="text" name="materials[<?php echo $id; ?>][unit]" value="<?php echo $row['unit']; ?>" /> <br /> </p> <?php endwhile; ?> <input type="submit" name="submit" value="Submit" /> </form> I am unsure how to get this information to insert into the database. How do you use the UPDATE query with a loop generated form ? [php] Per usual, I'm having an issue wrapping my head an issue, or I'm just not able to narrow the search well enough.
I have a form... method = post action = /process.php Upon hitting process.php, it will UPDATE a data table with the $_POST data it gets from the form. After that, I want to send it to PayPal.
It seems like at some point I was able to complete two 'actions' at once, but it's so long since I've created my own forms. Then again, maybe it was a redirect after executing the UPDATE. I just don't remember, and anything I search for doesn't seem to produce results of something that worked. |