PHP - Php File Upload Not Working Properly
I have been searching for an answer for several days but have not yet resolved my problem. Essentiallty I started out looking for an image upload script then slowly went towards just a basic upload script. Each time I try a new script I am getting the same error. My folder permissions are set, file uploads is enabled, safe mode is disabled.
As of right now my page is giving me an error that says 'Failed to open stream' My existing code: Code: [Select] <?php $target = "images/"; $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; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP 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."; } } ?> <form enctype="multipart/form-data" action="uploader.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> You for testing purposes I have made my temporary upload page available for you to view and help disgnose the issue: http://www.sophienoelle.me/uploader.php also you can find the phpinfo at http://www.sophienoelle.me/phpinfo.php If you need further information than what I have supplied please let me know and I will be available to provide what you are requesting. If you have a suggestion I will gladly take it. Any steps I can get to uploading images the better. Similar TutorialsI have a form that includes uploading a headshot. This is the form handling f ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $dob = $_POST['dateOfBirth']; if(!empty($_FILES['fileToUpload'])){ $errors= array(); $file_name = $_FILES['personHeadshot']['name']; $file_size =$_FILES['personHeadshot']['size']; $file_tmp =$_FILES['personHeadshot']['tmp_name']; $file_type=$_FILES['personHeadshot']['type']; $file_ext=strtolower(end(explode('.',$_FILES['personHeadshot']['name']))); $newFileName = $fn."-".$ln.".".$file_ext; $extensions= array("jpeg","jpg","png"); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } if($file_size > 2097152){ $errors[]='File size must be smaller than 2 MB'; } if(empty($errors)==true){ move_uploaded_file($file_tmp,"img/people/".$newFileName); echo "Success"; }else{ print_r($errors); } $personHeadshot = $newFileName; } $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id, image, dob) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param('ssiiissssssiss', $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA, $personHeadshot, $dob); $stmt -> execute(); header("location: admin-people-list.php"); } I also have this file <?php $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> This was working locally but now i have uploaded it i cannot get it to work. All of the person data gets put into the DB asside from the file name I appreciate you may need more info to help me which i will provide on request Hi Guys, I found this upload script a while ago and I'm sure the last time I used it, it worked perfectly but for some reason '$path1' keeps returning as blank. I'm not very good with file uploads, can anyone help me out please? Code: [Select] if ($_POST['customBackground']) { $path1= '/upload/' . date(U). $HTTP_POST_FILES['customBackground']['name'][0]; if(empty($path1)) { $message = '<p class="red size10font">Background field cannot be blank!</p>';} else { //copy file to where you want to store file copy($HTTP_POST_FILES['customBackground']['tmp_name'][0], $path1); } } The field it is being populated from is <input class="fullwidth biggun" name="customBackground" type="file" id="customBackground" size="70" value=""> Thank you in advance. I can't seem to get this file system to upload. It's returning an error about directory not writable. I have also verified it's 777 on the server, so I know permissions are right. File Class Code: [Select] <?php /** * Uploader is a file transfer class. it can upload files and images. * It also can resize and crop images. * Works on PHP 5 * @author Alaa Al-Hussein * @link http://www.freelancer-id.com/projects * @version 1.0 * */ class uploader{ /** * Array, The file object as $_FILES['element']. * String, file location. */ public $source; /** * Destination file location as folder. */ public $destDir; /** * Directory for Resized images. */ public $resizeDir; /** * Directory for Cropped images. */ public $cropDir; /** * stores information for uploading file */ private $info = ''; /** * Enabling autoName will generate an auto file name for the uploaded file. */ public $generateAutoName = true; /** * Handles the error when it occurs. */ private $errorMsg = ''; /** * new width for resizing and cropping. */ public $newWidth; /** * new height for resizing and cropping. */ public $newHeight; /** * TOP postion to cropping image. */ public $top = 0; /** * LEFT position for cropping image. */ public $left = 0; /** * JPG quality (0 - 100). used for image resizing or cropping. */ public $quality = 60; public function __construct(){ //nothing } /** * Uploads the file to the server. * @param Array $_FILES[] */ public function upload($source){ if($source != ""){ $this->source = $source; } if(is_array($this->source)){ if($this->fileExists()){ return false; } // Check for auto-name generation. If it's set then generate the name automatically. if ($this->generateAutoName == true) { $this->autoName(); } return $this->copyFile(); } else { return $this->source; } } /** * return the error messages. * @return String messages. */ public function getError(){ return $this->errorMsg; } /** * Get uploading information. */ public function getInfo(){ return $this->info; } /** * Auto Name */ private function autoName() { $num = rand(0, 2000000); $num2 = rand(0, 2000000); $this->source['name'] = $num . $num2 . $this->source['name']; return $this->source; } /** * Get Image Sizes * Returns an array of variables pertaining to properties of the image. * USE THIS ON IMAGES ONLY */ public function getImageSize() { // Get the size information of the provided image. $image_size = getimagesize($this->getTemp()); // Setup the height/width so they can be returned in a readable format $return_array['width'] = $image_size[0]; $return_array['height'] = $image_size[1]; // Return the array of new data. return $return_array; } /** * Copy the uploaded file to destination. */ private function copyFile(){ if(!$this->isWritable()){ $this->errorMsg .= '<div>Error, the directory: ('.$this->destDir.') is not writable. Please fix the permission to be able to upload.</div>'; return false; } if(copy($this->source['tmp_name'],$this->destDir . $this->source['name'])){ // Done. $this->info .= '<div>file was uploaded successfully.</div>'; } else { $this->errorMsg .= '<div>Error, the file was not uploaded correctly because of an internal error. Please try again, if you see this message again, please contact web admin.</div>'; } } /** * Checks if the file was uploaded. * @return boolean */ private function uploaded(){ if($this->source['tmp_name']=="" || $this->source['error'] !=0){ $this->errorMsg .= '<div>Error, file was not uploaded to the server. Please try again.</div>'; return false; } else return true; } /** * Prepares the directory. */ private function preDir(){ if($this->destDir!="" && substr($this->destDir, -1,1) != "/"){ $this->destDir = $this->destDir . '/'; } if($this->resizeDir!="" && substr($this->resizeDir, -1,1) != "/"){ $this->destDir = $this->resizeDir . '/'; } if($this->cropDir!="" && substr($this->cropDir, -1,1) != "/"){ $this->destDir = $this->cropDir . '/'; } } /** * Check if the folder is writable or not. * @return boolean */ private function isWritable(){ $err = false; if(!is_writeable($this->destDir) && $this->destDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->destDir.') is not writeable. File could not be uploaded.</div>'; $err = true; } if(!is_writeable($this->resizeDir) && $this->resizeDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->resizeDir.') is not writeable. File could not be resized.</div>'; $err = true; } if(!is_writeable($this->cropDir) && $this->cropDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->cropDir.') is not writeable. File could not be cropped.</div>'; $err = true; } if($err == true){ return false; } else { return true; } } /** * Checks if the file exists on the server * @return boolean */ private function fileExists(){ $this->preDir(); if(file_exists($this->destDir.$this->source)){ $this->errorMsg .= '<div>Upload error because file already exists.</div>'; return true; } else { return false; } } /** /586742130./8532 Crops image. * @return String fileName or False on error */ public function crop($file='',$width='',$height='',$top='',$left=''){ if($file!=""){ $this->source = $file;} if ($width != '') $this->newWidth = $width; if ($height != '') $this->newHeight = $height; if ($top != '') $this->top = $top; if ($left != '') $this->left = $left; return $this->_resize_crop(true); } /** * Resizes an image. * @return String fileName or False on error */ public function resize($file='',$width='',$height=''){ if($file!=""){ $this->source = $file; } if($width != '') $this->newWidth = $width; if($height != '') $this->newHeight = $height; return $this->_resize_crop(false); } /** * Get the Temp file location for the file. * If the Source was a file location, it returns the same file location. * @return String Temp File Location */ private function getTemp(){ if(is_array($this->source)){ return $this->source['tmp_name']; } else { return $this->source; } } /** * Get the File location. * If the source was a file location, it returns the same file location. * @return String File Location */ private function getFile(){ if(is_array($this->source)){ return $this->source['name']; } else { return $this->source; } } /** * Resize or crop- the image. * @param boolean $crop * @return String fileName False on error */ private function _resize_crop ($crop) { $ext = explode(".",$this->getFile()); $ext = strtolower(end($ext)); list($width, $height) = getimagesize($this->getTemp()); if(!$crop){ $ratio = $width/$height; if ($this->newWidth/$this->newHeight > $ratio) { $this->newWidth = $this->newHeight*$ratio; } else { $this->newHeight = $this->newWidth/$ratio; } } $normal = imagecreatetruecolor($this->newWidth, $this->newHeight); if($ext == "jpg") { $src = imagecreatefromjpeg($this->getTemp()); } else if($ext == "gif") { $src = imagecreatefromgif ($this->getTemp()); } else if($ext == "png") { $src = imagecreatefrompng ($this->getTemp()); } if($crop){ //$pre = 'part_'; //We want to overwrite file, so comment this out. if(imagecopy($normal, $src, 0, 0, $this->top, $this->left, $this->newWidth, $this->newHeight)){ $this->info .= '<div>image was cropped and saved.</div>'; } $dir = $this->cropDir; } else { //$pre = 'thumb_'; //We want to overwrite file, so comment this out. if(imagecopyresampled($normal, $src, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height)){ $this->info .= '<div>image was resized and saved.</div>'; } $dir = $this->resizeDir; } if($ext == "jpg" || $ext == "jpeg") { imagejpeg($normal, $dir . $pre . $this->getFile(), $this->quality); } else if($ext == "gif") { imagegif ($normal, $dir . $pre . $this->getFile()); } else if($ext == "png") { imagepng ($normal, $dir . $pre . $this->getFile(),0); } imagedestroy($src); return $src; } } /* Examples Section */ /* Let me explain first how to manage an image to be uploaded and then to be cropped or resized. <?php $uploader = new uploader(); // Setting properties then Uploading the image $uploader->source = $_FILES['field_image']; $uploader->destDir = "images/"; $uploader->upload(); // ===================== // Or you may use this too $uploader->destDir = "images/"; $uploader->upload($_FILES['field_image']); ?> Note: upload() returns the file name uploaded. To get error messages, use this code: <?php echo $uploader->getError(); // This function will return all errors occured while uploading the image. But it's not printing it to print it where ever you want. ?> And to get Information messages use this code: <?php echo $uploader->getInfo(); // This function will return all information to let the user print it where ever he wants. ?> After uploading this image, we may resize it. To do that use the following code: <?php $uploader->newWidth = 75; // in Pexels. $uploader->newHeight = 75; $uploader->resizeDir = "images/resized/"; $uploader->resize(); ?> You may also use this syntax: <?php // $uploader->resize($file,$width,$height); // $file could has a value of "" (nothing), in this case we use the last uploader file. // if the $file has a String value (file url) it will resize this new file. $uploader->resizeDir = "images/resized/"; $uploader->resize('',75,75); // Or you may upload and resize in the same line: $uploader->resizeDir = "images/resized/"; $uploader->resize($uploader->upload(),75,75); ?> Crop this image after uploading it: <?php $uploader->cropDir = "images/cropped/"; $uploader->newWidth = 75; $uploader->newHeight = 75; $uploader->top = 20; // Default is ZERO.. This used to set the cropping top location from the original image. $uploader->left = 40; // Default is ZERO.. This used to set the cropping left location from the original image. $uploader->crop(); // You may also use this: // $uploader->crop($file,$width,$height,$top,$left); $uploader->cropDir = "images/cropped/"; $uploader->crop('',75,75,20,40); ?> */ ?> Upload Function Code: [Select] <?php /* END STANDARD FUNCTIONS */ /* General function to deal with image uploads site_wide. */ function upload_image($file, $dir, $table, $fieldname, $id, $exists, &$data) { // Get image information if ($file['tmp_name'] != '' && $file['name'] != '') { if ($exists == 1) { // Delete Associated Image $imageSQL = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '" . $id . "'"; $imageQuery = mysql_query($imageSQL); while($row = mysql_fetch_array($imageQuery, MYSQL_ASSOC)) { if ($row[$fieldname] != '') { $tmpdirectory = '../assets/' . $dir . '/'.$row[$fieldname]; if (file_exists($tmpdirectory)) { unlink($tmpdirectory); } } } } $directory = '../assets/' . $dir . '/'; // Default DIR // Upload $uploader = new uploader; $uploader->destDir = $directory; $uploader->generateAutoName = true; $file_name = $uploader->upload($file); $image_sizes = $uploader->getImageSize(); echo $uploader->getInfo(); } // Check if image was uploaded and if so database name. if ($uploader->source['name'] != '') { $data[$fieldname] = $uploader->source['name']; }else { if ($exists == 1) { $tmpSelect = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '".$id."'"; $tmpQuery = mysql_query($tmpSelect); if ($row = mysql_fetch_array($tmpQuery, MYSQL_ASSOC)) { $data[$fieldname] = $row[$fieldname]; }else { $data[$fieldname] = NULL; } }else { $data[$fieldname] = NULL; } } } ?> Code to call function Code: [Select] <?php // Upload all images $picture_1 = $_FILES['picture_one']; if ($picture_1['tmp_name'] != '' && $picture_1['name'] != '') { $functions->upload_image($picture_1, 'product_pictures', 'products', 'picture_1', $product_id, $exists, &$data); } ?> At this point I have done all of the debugging I can and it's not working out. Any advice is appreciated. 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 am in the process of creating a script where only certains video types can be uploaded but at the moment am stuck.
Here is my code -
<?php $title = isset($_POST['title']) ? $_POST['title'] : null; $desc = nl2br(isset($_POST['description'])) ? $_POST['description'] : null; $name = isset($_POST['fullname']) ? $_POST['fullname'] : null; $email = isset($_POST['email']) ? $_POST['email'] : null; $country = isset($_POST['country']) ? $_POST['country'] : null; $video = isset($_FILES['video']); $videoname = isset($_FILES['video']['name']); $videotmp = isset($_FILES['video']['tmp_name']); $videosize = isset($_FILES['video']['size']); $videotype = isset($_FILES['video']['type']); $videoacceptable = array( "video/mp4", "video/ogg", "video/quicktime", ); $videopath = "/videos/"; $videofile = $videopath . $video; if(isset($_POST['submit'])) { //ERROR MESSAGES / VALIDATION if(empty($title)) { $errors[] = "A title is required"; echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($title) > 80) { $errors[] = "Your title can only be 80 characters long"; echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($desc)) { $errors[] = "A description is required"; echo "<style type=\"text/css\"> #description { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($name)) { $errors[] = "Please enter your full name"; echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($name) > 32) { $errors[] = "Your name can only be 32 characters long"; echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($email)) { $errors[] = "Please enter your email address"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($email) > 50) { $errors[] = "Your email addess can only be 50 characters long"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Please enter a valid email address"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if($videosize = 0) { $errors[] = "You forgot to upload a video"; } elseif($videosize >= 20000000) { $errors[] = "Your video size is too large, 20mb max"; } elseif(!in_array($videotype, $videoacceptable)) { $errors[] = "The file type is not allowed, only allowed .mp4, .ogg and .mov"; } if(count($errors) === 0) { $connect = mysqli_connect("localhost","username","password"); if(!$connect) { header("Location:"); // ADD ERROR LINK } $dbselect = mysqli_select_db("database"); if(!$dbselect) { header("Location:"); // ADD ERROR LINK } $query = mysqli_query("INSERT INTO cover_videos(title, desc, name, email, country, videotmp, videotype, videosize, videopath) VALUES('$title','$desc','$name','$email','$country','$videotmp','$videotype','$videosize','$videopath')"); move_uploaded_file($videotmp, $videofile); //SEND AN EMAIL TO THE USER $to = $email; $subject = "Thank's for your upload"; $message = ' <html> <head><title>We have received your video</title></head> <body> <h3>Good News!</h3> <p>We have recieved your video and is awaiting approval.</p> </body> </html> '; $headers = 'FROM: no-replyk' . "\r\n"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers = 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); header("Location:"); //SUCCESSFUL UPLOAD PAGE } } ?>So whats happening is when i go to upload a file, im uploading a .mov file but the error message that pops up is "The file type is not allowed, only allowed .mp4, .ogg and .mov" but the .mov mime is in the videoacceptable array so im a bit stuck at the moment, any know whats the problem? ...and the file is to be copied into a folder created by me. I was wondering what the file path would be for Windows, since it does not seem to recognise the file path that I have chosen: Upload Form code: Code: [Select] <html> <head><title>Car Accident Report Uploader</title></head> <body> <form action="fileuploadform.php" method="post" enctype="multipart/form-data"> <input type="file" size="45" name ="file"><br> <input type="submit" value = "Upload Car Accident Report"> </form> </body> </html> Copying Script Code: Code: [Select] <?php if ($_FILES['file']['name'] !="") { copy ($_FILES['file']['tmp_name'], 'C:\xampp\htdocs\rcm' . $_FILES['file']['name']) or die ("Could not copy Car Accident Report Form"); } else {die ("No Car Accident Report Form has been chosen");} ?> <html> <head><title>Car Accident Report Form Upload Complete</title></head> <body><h3>Car Accident Report Form has been uploaded</h3> <ul> <li>Sent: <?php echo $_FILES['file']['name']; ?> <li>Size: <?php echo $_FILES['file']['size']; ?> bytes <li>Type: <?php echo $_FILES['file']['type']; ?> <a href = "<?php echo $_FILES['file']['name']; ?>"> Click here to view the Car Accident Report Form</a> </body> </html> If anyone can help me find the relevant file path, it would be appreciated! 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! 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'");
Hiya, Firstly, I'm a complete novice, apologies! But I have got my upload.php working which is nice. I will post the code below. However, I would now like to restrict the file size and file type to only word documents. I currently have a restriction of 200KB but it's not working - no idea why as I've looked at other similar codes and they look the same. Also, just to complicate things - can I stop files overwriting each other when uploaded? At the moment, if 2 people upload files with the same name one will overwrite the other. Is this too many questions in 1? Any help is very much appreciated! Code below: Code: [Select] <form enctype="multipart/form-data" action="careers.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> <?php $target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 200) { echo "Your file is too large.<br>"; $ok=0; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP 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 "Your file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded."; } else { echo "Sorry, there was a problem uploading your file."; } } ?> In this multi file upload form, choose three images, click submit and preview the images on the preview page. If the user wishes to delete or replace an image, click edit and the form will go back to the previous page. Select the replace radio button for example on one of the three images and select a new image from the file input prompt and click submit. The form will go to the preview page again to display the images. During this process the image names are being input into a table and the images are being moved to a directory. The table is `id` AUTO_INCREMENT, `image0` `image1` `image2` `status` So input name='image[image0]' can be directed to table `image0` and so on. The code for keep and delete work fine, but how do I replace an image? I have two foreach blocks. The first one deletes the image file from the directory and deletes the image name from the table, but the second foreach dose not move the new image file into the directory. Thanks. <input type='radio' name='image[image0]' value='keep' checked='checked'/> <input type='radio' name='image[image0]' value='delete' /> <input type='radio' name='image[image0]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image1]' value='keep' checked='checked'/> <input type='radio' name='image[image1]' value='delete' /> <input type='radio' name='image[image1]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image2]' value='keep' checked='checked'/> <input type='radio' name='image[image2]' value='delete' /> <input type='radio' name='image[image2]' value='replace' /> <input type="file" name="image[]" /> <?php if (isset($_POST['status'])) { $status = $_POST['status']; $confirm_code = $status; #--------------------------- replace -------------------------------------------- if (isset($_POST['submitted']) && ($image = $_POST['image'])) { foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $query = "SELECT $imageKey FROM table WHERE status = '$status' "; if($result = $db->query( $query )){ $row = $result->fetch_array(); } unlink( UPLOAD_DIR.$row[0] ); $query = "UPDATE table SET $imageKey = '' WHERE status = '$status' "; } } foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $filenm = $_FILES['image']['name']; $file = $_FILES['image']['tmp_name']; move_uploaded_file($file, UPLOAD_DIR . $filenm); $filename[] = $filenm; $query = "INSERT INTO table VALUES ('','$filename[0]','$filename[1]','$filename[2]','$confirm_code')"; } } } } ?> <td><label for='images'> <b>File to upload:</b> </label></td> <td><input type='file' name = 'drama_image' '<?php echo $row['drama_image']; ?>'/></ </tr> <?php $target_path = "images/"; $target_path = $target_path . basename( $_FILES['images']['name']); if(move_uploaded_file($_FILES['images']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['images']['name']). " has been uploaded"; } else{ echo $row['drama_image']; } ?> ['drama_image'] is the name of the file I wanna echo it out in the box of file upload so when I save , the default picture will still be there instead of being overwritten as the box does not have any value in it. So, I'm learning how to upload pictures into a system from my awesome PHP book. I've looked and looked through the script but I can't figure out whats wrong with it. Goal: The script is meant to save a full version of the image in the images folder and a thumbnail in the thumbnail folder. Bug: The full image does not appear in any folder, and the thumbnail is created but its put in the images folder. I've checked the GD library, and everything is supported. image_effect.php <?php //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // make sure the requested image is valid if (isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir . '/' . $_GET['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_GET['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_GET['e'])) ? $_GET['e'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_GET['capt'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']); } //add the logo watermark if requested if (isset($_GET['logo'])) { // determine x and y position to center watermark list($width, $height) = getimagesize($dir . '/' . $_GET['id'] . '.jpg'); list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // show the image header('Content-Type: image/jpeg'); imagejpeg($image, '', 100); ?> check_image.php <?php include 'db.inc.php'; //connect to MySQL $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your thumbnail directory $thumbdir = $dir . '/thumbs'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // handle the uploaded image if ($_POST['submit'] == 'Upload') { //make sure the uploaded file transfer was successful if ($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK) { switch ($_FILES['uploadfile']['error']) { case UPLOAD_ERR_INI_SIZE: die('The uploaded file exceeds the upload_max_filesize directive ' . 'in php.ini.'); break; case UPLOAD_ERR_FORM_SIZE: die('The uploaded file exceeds the MAX_FILE_SIZE directive that ' . 'was specified in the HTML form.'); break; case UPLOAD_ERR_PARTIAL: die('The uploaded file was only partially uploaded.'); break; case UPLOAD_ERR_NO_FILE: die('No file was uploaded.'); break; case UPLOAD_ERR_NO_TMP_DIR: die('The server is missing a temporary folder.'); break; case UPLOAD_ERR_CANT_WRITE: die('The server failed to write the uploaded file to disk.'); break; case UPLOAD_ERR_EXTENSION: die('File upload stopped by extension.'); break; } } //get info about the image being uploaded $image_caption = $_POST['caption']; $image_username = $_POST['username']; $image_date = @date('Y-m-d'); list($width, $height, $type, $attr) = getimagesize($_FILES['uploadfile']['tmp_name']); // make sure the uploaded file is really a supported image $error = 'The file you uploaded was not a supported filetype.'; switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error); break; default: die($error); } //insert information into image table $query = 'INSERT INTO images (image_caption, image_username, image_date) VALUES ("' . $image_caption . '", "' . $image_username . '", "' . $image_date . '")'; $result = mysql_query($query, $db) or die (mysql_error($db)); //retrieve the image_id that MySQL generated automatically when we inserted //the new record $last_id = mysql_insert_id(); // save the image to its final destination $image_id = $last_id; imagejpeg($image, $dir . '/' . $image_id . '.jpg'); imagedestroy($image); } else { // retrieve image information $query = 'SELECT image_id, image_caption, image_username, image_date FROM images WHERE image_id = ' . $_POST['id']; $result = mysql_query($query, $db) or die (mysql_error($db)); extract(mysql_fetch_assoc($result)); list($width, $height, $type, $attr) = getimagesize($dir . '/' . $image_id . '.jpg'); } if ($_POST['submit'] == 'Save') { // make sure the requested image is valid if (isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir . '/' . $_POST['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_POST['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_POST['emb_caption'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $image_caption); } //add the logo watermark if requested if (isset($_POST['emb_logo'])) { // determine x and y position to center watermark list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // save the image with the filter applied imagejpeg($image, $dir . '/' . $_POST['id'] . '.jpg', 100); //set the dimensions for the thumbnail $thumb_width = $width * 0.10; $thumb_height = $height * 0.10; //create the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); imagejpeg($thumb, $dir . '/' . $_POST['id'] . '.jpg', 100); imagedestroy($thumb); ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>Your image has been saved!</h1> <img src="images/<?php echo $_POST['id']; ?>.jpg" /> </body> </html> <?php } else { ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>So how does it feel to be famous?</h1> <p>Here is the picture you just uploaded to our servers:</p> <?php if ($_POST['submit'] == 'Upload') { $imagename = 'images/' . $image_id . '.jpg'; } else { $imagename = 'image_effect.php?id=' . $image_id . '&e=' . $_POST['effect']; if (isset($_POST['emb_caption'])) { $imagename .= '&capt=' . urlencode($image_caption); } if (isset($_POST['emb_logo'])) { $imagename .= '&logo=1'; } } ?> <img src="<?php echo $imagename; ?>" style="float:left;"> <table> <tr><td>Image Saved as: </td><td><?php echo $image_id . '.jpg'; ?></td></tr> <tr><td>Height: </td><td><?php echo $height; ?></td></tr> <tr><td>Width: </td><td><?php echo $width; ?></td></tr> <tr><td>Upload Date: </td><td><?php echo $image_date; ?></td></tr> </table> <p>You may apply special options to your image below. Note: saving an image with any of the options applied <em>cannot be undone</em>.</p> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div> <input type="hidden" name="id" value="<?php echo $image_id;?>"/> Filter: <select name="effect"> <option value="-1">None</option> <?php echo '<option value="' . IMG_FILTER_GRAYSCALE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE) { echo ' selected="selected"'; } echo '>Black and White</option>'; echo '<option value="' . IMG_FILTER_GAUSSIAN_BLUR . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR) { echo ' selected="selected"'; } echo '>Blur</option>'; echo '<option value="' . IMG_FILTER_EMBOSS . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS) { echo ' selected="selected"'; } echo '>Emboss</option>'; echo '<option value="' . IMG_FILTER_NEGATE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE) { echo ' selected="selected"'; } echo '>Negative</option>'; ?> </select> <br/><br/> <?php echo '<input type="checkbox" name="emb_caption"'; if (isset($_POST['emb_caption'])) { echo ' checked="checked"'; } echo '>Embed caption in image?'; echo '<br/><br/><input type="checkbox" name="emb_logo"'; if (isset($_POST['emb_logo'])) { echo ' checked="checked"'; } echo '>Embed watermarked logo in image?'; ?> <br/><br/> <input type="submit" value="Preview" name="submit" /> <input type="submit" value="Save" name="submit" /> </div> </form> </body> </html> <?php } ?> Any help appreciated. Hello, all: been trying to convert this little single-file upload to multiple by naming each file form-field as "userfile[]" as it's supposed to automatically treat them as an array.. but no luck! Can you guide me as to what am I doing wrong?? appreciate the help! Code: [Select] <?php if (!isset($_REQUEST["seenform"])) { ?> <form enctype="multipart/form-data" action="#" method="post"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> <input type="submit" value="Upload"> <input type="hidden" name="seenform"> </form> <?php } else { // upload begins $userfiles = array($_FILES['userfile']); foreach ($userfiles as $userfile) { // foreach begins $uploaded_dir = "uploads/"; $userfile = $_FILES['userfile']["name"]; $path = $uploaded_dir . $userfile; if (move_uploaded_file($_FILES['userfile']["tmp_name"], $path)) { print "$userfile file moved"; // do something with the file here } else { print "Move failed"; } } // foreach ends } // upload ends ?> I havent included the whole title as it wouldnt let me but I was wondering if someone could help me on this? I know this is possible as torrentflux caters for this but unsure of where to start. I dont want to allow file or directory uploads or creation in my /etc/php.ini file (this is turned off). Yet then torrentflux allows me to link a torrent from an external source (using legal downloads of course ) but then it uploads it on my server and creates folders on a per user basis. How is this possible can someone give me some pointers please? I look forward to any replies, Jeremy. HI All, I have a form submission that uploads a photo as well as submitting other data. I would like to change the name of the photo to the id of the person record (created automatically on by the database) then a hyphen, then their first name and lastname. (i am flexible on this). This file name will also need to be submitted into the person record so the photo and the person can be linked. I am struggling with this one - but here is the code i have so far.
<?php include 'includes/dbconn.php'; $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["personHeadshot"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param(ssiiissssssi, $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA); $stmt -> execute(); // Check if image file is a actual image or fake image //photo upload $check = getimagesize($_FILES["personHeadshot"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } //photo upload header("location: ../admin-people-list.php"); } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["personHeadshot"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["personHeadshot"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["personHeadshot"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
Hello! I have this validation script that seems to work great until I add the size validation. I'm ready to pull my hair out! Can someone tell me what I'm doing wrong? Code: [Select] if (isset($_POST['Submit'])) { $user_id = $userdata[user_id]; $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; $uploaded_files = array(); $max_filesize = 5242880; // Maximum filesize in BYTES (currently 5MB). $upload_directory = dirname(__file__) . '/'.$user_id.'/'; //set upload directory if (!is_dir($upload_directory)) { mkdir($upload_directory, 0777, true); } for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; if($_FILES['images']['size'] > $max_filesize){ echo "<b class='red'>Max file size is 5MB.</b><br/>"; $sz = true; } $ext = validate_extension($_FILES['images']['name'][$i]); if (($ext == true) && ($sz == true)){ $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } }else { echo "<b class='red'>File extention error. Only .doc, .pdf, .jpg and .gif files are allowed. </b><br/>"; } } } if ($number_of_uploaded_files >= 1){ echo "Number of files submitted:<b class='red>".$number_of_uploaded_files."</b><br/>"; echo "Number of successfully uploaded files:<b class='red>".$number_of_moved_files."</b><br/><br/>"; echo "Uploaded File Name(s):<br/>" . implode('<br/>', $uploaded_files); } } As of now it results in every uploaded file returning the error "Max file size is 5MB." Okay, so I am trying to make a play.php file connected to my database, this database got a table named "webclientcreate". When I go to play.php?id=1, it is showing the proper one (the 1st row wich got id 1 in it), however if I after that go to something random like play.php?fsfasd the ID 1s page still pops up.. I can also go to play.php?id=2 and still get the id 1's data. I want to make it that every row got its own information (well it does, but the php file doesnt seem to recieve it correctly). PHP version: 5.2.17 MySQL version: 5.1 Heres a picture of my table rows: I've censored the MySQL connection information, I know it is working properly. Code: [Select] <?php $connect = mysql_connect("mysql12.000webhost.com","****","******") or die(mysql_error()); mysql_select_db("***") or die(mysql_error()); $extract = mysql_query("SELECT * FROM webclientcreate"); $numrows = mysql_num_rows($extract); while ($row = mysql_fetch_assoc($extract)) { $id = $row['id']; $server = $row['name']; $ip = $row['ip']; $port = $row['port']; $background = $row['background']; } if (isset($ip)&&isset($port)&&!empty($ip)&&!empty($port)) { if (! $sock = @fsockopen($ip, $port, $num, $error, 1)) echo ""; else{ echo "<img src='fs/newyear/online.png'/>$ip on port $port is currently<B><FONT COLOR=lime> Online</b></FONT>"; fclose($sock); } } ?> <title>Playing <?php echo $server; ?> - ID <?php echo $id; ?> </title> <center> <body bgcolor="#000000"> <applet name=client width=765 height=503 archive='<?php echo $jars; ?>' code='client.class'> <PARAM name='java_arguments' value='-Xmx700m'> <PARAM name='server_name' value='<?php echo $server; ?>'> <PARAM name='detail' value='low'> <PARAM name='ip' value='<?php echo $ip; ?>'> <PARAM name='port' value='<?php echo $port; ?>'> <PARAM name='background_image' value='<?php echo $background; ?>'> <PARAM name='headicons' value=''> </applet> </center> Hi there, I have created an email script and i want it to email a different email depending on the subject chosen by raido boxes however the if's aren't doing what they should, If i select say recruitement it choses the last option and has the wrong subject here is my code: <html> <head> </head> <body> <form action="contact.php" method="post"> <fieldset> <legend>Contact Us</legend> Your Email:*<br> <input type="text" name="email"><br> Subject:*<br> Recruitment Enquiry:<input type="radio" name="subject" value="Recruitment"> Absense Notification:<input type="radio" name="subject" value="Absense"> General Enquiry<input type="radio" name="subject" value="Enquiry"> <br> Message:*<br> <textarea name="message" cols="50" rows="5"></textarea><br> <input type="submit" value="Send Email"> </form> Required fields are marked with a *<br><br> <?php if(isset($_POST)) { $email = $_POST['email']; $subject = $_POST['subject']; $message = $_POST['message']; //checcking that all relevent information is entered and correct if(!$email || !$message) { $errmessage ="Please fill in all required fields."; } if($subject="Recruitment") { $to="email1"; } if($subject="Notification") { $to="email2k"; } if($subject="Enquiry") { $to="email3"; } //Sending the email if nothing is wrong if(!$errmessage) { header("location:send.php?to=".$to."&subject=".$subject."&email=".$email."&message=".$message.""); }else{ echo $errmessage; } } ?> </body> </html> If anyone can help it would be greatly appriciated Thanks, blink359 Here's the code with the function that won't work! Code: [Select] $itemsRaw = explode(" ", $player['inventory']); foreach ($itemsRaw as $inv){ $contents = explode("-", $inv); if(strlen($contents[0]) > 0 && strlen($contents[1]) > 0 && $contents[1] > 0) echo getItemName($contents[0]) . " (" . number_format($contents[1]) . ")<br />"; } Here's my function: Code: [Select] function getItemName($id_raw){ $id = $id_raw - 1; $q = $db->query("SELECT * FROM items WHERE id = $id") or die(mysql_error()); $f = $db->fetch_assoc($q); return $f['name']; } It stops the page when it gets to that point and won't load anything else and the function doesn't even work with it :/ What's wrong with it? If anything.. Hi, I'm having problems with a PHP mail handler and everything seems to be working fine except I get slashes in the message body from the form. If my input is "Please don't delete this" I get "Please don/'t delete this" in the message body, however it is striping the other tags. I'm not sure what is wrong and was hoping for a bit of help to figure this out. Here is the code: Code: [Select] <?php $owner_email = $_POST["owner_email"]; $headers = 'From:' . $_POST["email"]; $subject = 'Website contact inquiry from ' . $_POST["name"]; $messageBody = ""; $messageBody .= '<p>------------------ Contact Details ------------------' . '</p>' . "\n"; $messageBody .= '<p>Name: ' . $_POST["name"] . '</p>' . "\n"; $messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n"; $messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n"; $messageBody .= '<p>----------------------------------------------------------' . '</p>' . "\n"; $messageBody .= '<br>' . "\n"; $messageBody .= '<p>' . $_POST['message'] . '</p>' . "\n"; if($_POST["stripHTML"] == 'true'){ $messageBody = strip_tags($messageBody); } try{ if(!mail($owner_email, $subject, $messageBody, $headers)){ throw new Exception('mail failed'); }else{ echo 'mail sent'; } }catch(Exception $e){ echo $e->getMessage() ."\n"; } ?> |