PHP - Php In Windows Returning A \r\n When Processing Download Handler.
Here's a very interesting conundrum that I think will stump quite a few of you.
Here's the setup: I was put in charge of the project of maintaining and developing a database application for one of my company's customers. The application has been evolving ever since. One of the more recent changes we've been working on is to add file upload functionality to catalog forms, letters, etc. I had this application working before by uploading the file directly to the server, giving it a random name, putting it in a /forms directory, and entering a hyperlink in a log line, which was then entered into the MySQL database. It's a pretty straightforward procedure. BUT my customer doesn't always have net access so he has a laptop running the application with its own MySQL and PHP installation, and he has a script that synchronizes the database with the one on our server. Not very practical or efficient, I know, but I inherited this project and had no choice in the matter. Since the client needs to upload and catalog files, and needs those files to be in sync with our server, I figured instead of just having a folder full of files that also has to be synched, why not throw binary data into the database and have the files in the database? Well I quickly developed a set of scripts to handle this task, and all of them worked flawlessly on our Linux server. It worked, that is, until I tried to install the same code on our client's Windows crapbox. At this point, I'd like to convey the download script that I wrote: Code: [Select] require_once('includes/application.inc.php'); if($_REQUEST['id']) { $id = mysql_real_escape_string($_REQUEST['id']); } else die("Error"); $result = mysql_fetch_assoc(mysql_query("SELECT * FROM Files WHERE id = $id")); header("Content-type: ".$result['type']); header("Content-length: ".$result['size']); header("Content-Disposition: attachment; filename=".$result['filename']); echo $result['data']; You see? Very simple and to the point. This script is called from a hyperlink elsewhere in the application, it queries for the file and downloads it. The problem is that when I'm running this download script on the laptop's Windows server, the browser echoes a \r\n as well as the binary data. As you can imagine, this wreaks havoc with files downloaded. Here's what I've determined: The data IS being stored properly in the database This only happens with certain files and not with others. The most egregious offenders are .odt files. The data is not being returned from the database corrupted. I verified this using various regex's and by dumping the data right out of the database into hex in the browser. Apache is not inserting that line break as seen by testing with static html files From these things, I have determined that PHP is the most likely culprit. My limited knowledge of the entire library of functions notwithstanding, is there anything I'm missing? Is there a more "safe" way to echo binary data? Does anyone have any sort of clue as to what could be causing this? I've scoured Google and this forum and haven't found anything. Thanks in advance for your insight. Similar TutorialsHi I am new to php, I am trying to capture the url and place into a variable but I only get the 1st digit to show, I just cant see what I am doing wrong. Sorry to ask such a basic question but I just can't work it out, I have attached a screen shot of all me code, your help would be very very much appreciated.
Basically I would like to place a link on my website and have the user download a file, but rather than just right clicking and choosing save target as, the link must be clicked, on the next page the file is fetched and then the client can download the file. How would I go about setting this up please? Hi Y'all I have a contact form page with a contact-handler.php for emailing the details to my email address. I have the site uploaded on the net for the php and submission of the message fields to work and it seems to submit the message fine (simple contact form... name, email and message) but i never receive the email of the users message?? I have searched this forum before i posted this and there was one message on this topic however i could not make sense of the reply.. guy typs lke this lnguage wit misn words? madness. Anyways i know a guy mentioned gmail and yahoo might be backlist but surely not for days? the email is not in my spam folder either.. heres the snippet of my code, massively appreciate any help. <?php $errors = ''; $myemail = 'croz27@gmail.com'; if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) { $errors .= "\n Error: all fields are required"; } $name = $_POST['name']; $email_address = $_POST['email']; $message = $_POST['message']; if (!eregi( "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email_address)) { $errors .= "\n Error: Invalid email address"; } if( empty($errors)) { $to = $myemail; $email_subject = "Contact form submission: $name"; $email_body = "You have received a new message. ". " Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message"; $headers = "From: $myemail"; $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); //redirect to the 'thank you' page header('Location: contact-form-thank-you.html'); } ?> Thanks for any input. ps. I have left in my real email address incase gmail has any conflicts with this ... croz27 Hi, I have been trying to find an up-to-date bounce mail handler for PHP but so far everything I've found seems to be extremely dated. Two common suggestions are the bounce handler at http://www.phpclasses.org/package/2691-PHP-Parse-bounced-e-mail-message-reports.html , or the PHP Mailer-BMH, http://phpmailer.worxware.com/index.php?pg=bmh . I know for certain that PHP Mailer-BMH is dated and no longer a viable solution, and I believe the PHP classes solution is also dated. Does anyone know of a current bounce mail handler? Preferably it would include the functionality to connect to a remote mailbox so I won't have to do this myself. Thanks for any help. This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=358574.0 Hi guys, first time on forum, and in desperate need of help. I asked my co workers and they don't have a single clue into what is going wrong. I built a PHP image handler to secure images down to the user too see. When I integrate this into the ajax however, the images only load on the page after all the ajax requests finish. In this case there are 4 ajax requests. I have attached screenshots of the problem before all the ajax requests finish and after. NOTE: This works fine with images that are not being generated PHP. At first I thought it might be a header problem with the image handler but I cant seem to find any people who have seen this problem. Here is the code. class SecureImage { public $user_img_dir; public $db_img_dir; public $temp_img_dir; public $main_img_dir; function __construct(){ global $SESSION; //set the class vars $this->temp_img_dir = BASE_PATH.'webdocs/images/_temp/'; $this->main_img_dir = '/var/images/'; //now check to see if there is a directory for this file //build the directory for the image $user_id = $SESSION->getUserid(); $db_name = $GLOBALS['Config']->db['db_name']; $user_img_dir = "{$this->main_img_dir}{$db_name}/{$user_id}/"; $db_img_dir = $this->main_img_dir.$db_name."/"; //set the class vars $this->user_img_dir = $user_img_dir; $this->db_img_dir = $db_img_dir; //now check to see if the directory is there if(!is_dir($user_img_dir)){ //check to see if the db_name is a dir if(!is_dir($db_img_dir)){ //make the directory mkdir($db_img_dir); } //now make the user id dir mkdir($user_img_dir); } } public function getImage($img){ $img_array = explode('.', $img); switch($img_array[1]){ case 'jpg': case 'jpeg': header('Content-Type: image/jpeg'); break; case 'png': header('Content-Type: image/png'); break; case 'gif': header('Content-Type: image/gif'); break; } header('Content-Disposition: inline;'); //get the file size $img_size = filesize($this->user_img_dir.$img); header('Content-Length: '.$img_size); echo readfile($this->user_img_dir.$img); } } If anyone has any ideas, much appreciated. I have a click handler that is causing some problem. I am using hammer.js for a slider.
This is the link http://ingrub.com/iphone/
When you hit the last slide the text of next changes to let's grub, but the problem is that if you swipe back to an earlier screen and you try to go next it automatically goes to the link instead of going to the next slide these are some of the functions that i am using
this.showPane = function(index, animate) { // between the bounds index = Math.max(0, Math.min(index, pane_count-1)); current_pane = index; var offset = -((100/pane_count)*current_pane); setContainerOffset(offset, animate); if(current_pane == 2){ $(".next2").text("Let's Grub"); $(".navigation2").addClass('linkMe'); } else { $(".next2").text("Next"); $(".navigation2").removeClass('linkMe'); } }; $( ".next2" ).click(function() { carousel.next(); $('.linkMe').click(function() { window.location = "discover.html"; }); return false; });I am not sure what to do to fix this bug. I have made a Php program that downloads an Inno setup installation file for installing a program. However, if I for one or another reason want to make a new download of the same Inno setup installation file, the previous file will still be found in the Download folder. Each of the downloads get a number in parenthesis, setup(1), setup(2), setup(3) etc. However, I wondered if it is posible to erase the previous file in the same process as I download a new one, so that however many downloads I do, there will all the time only be one occurence of this file in the Download folder. The download code is as follows: $exe = "Inno script/Test_setup.exe"; header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"Test_setup.exe\""); header("Content-Length: " . filesize($exe)); readfile($exe); Thanks in advance. Sincerely
Good Day, I'm using the following example script from http://php.net/manual/en/function.session-set-save-handler.php which I have placed in session-handler.php and is included at the top of my index.php file. I have multiple domain names for the same website, so naturally when a person logs into the site, I would like the session to be active across all the domains instead of them having to login again if say they go from mysite.com to mysite2.com. session-handler.php <?php function open($save_path, $session_name) { global $sess_save_path; $sess_save_path = $save_path; return(true); } function close() { return(true); } function read($id) { global $sess_save_path; $sess_file = "$sess_save_path/sess_$id"; return (string) @file_get_contents($sess_file); } function write($id, $sess_data) { global $sess_save_path; $sess_file = "$sess_save_path/sess_$id"; if ($fp = @fopen($sess_file, "w")) { $return = fwrite($fp, $sess_data); fclose($fp); return $return; } else { return(false); } } function destroy($id) { global $sess_save_path; $sess_file = "$sess_save_path/sess_$id"; return(@unlink($sess_file)); } function gc($maxlifetime) { global $sess_save_path; foreach (glob("$sess_save_path/sess_*") as $filename) { if (filemtime($filename) + $maxlifetime < time()) { @unlink($filename); } } return true; } session_set_save_handler("open", "close", "read", "write", "destroy", "gc"); session_start(); ?> The script above doesn't appear to be throwing any errors, and I can login like normal but it doesn't seem to be saving the sessions at all. So I still have to login to each separate domain. Any ideas? Thanks, Ace This is my first post on your forums. I've some problems with a registration form that I've been trying to work out for 2+ days now, asking about it here is a last resort - I have a config.php file located at config/config.php there's a register.php file in the sites root directory and a includes/form_handlers/register.php
My config.php file is: <?php ob_start(); session_start(); $timezone = date_default_timezone_set("America/Cancun"); $servername = "localhost"; $username = "root"; $password = ""; $database = "social"; $conn = mysqli_connect($servername, $username, $password, $database); if (mysqli_connect_error()) { echo "Failed to connect: " . mysqli_connect_error(); } ?> This is my register.php file: <?php require 'config/config.php'; require 'includes/form_handlers/register.php'; ?> <!-- REMOVED THE <HEAD> SECTION --> <body class="login-img3-body"> <div class="container"> <form class="login-form" action="includes/form_handlers/register.php" method="POST"> <div class="login-wrap"> <p class="login-img"><i class="icon_lock_alt"></i></p> <div class="input-group"> <span class="input-group-addon"><i class="icon_profile"></i></span> <input type="text" class="form-control" name="fname" placeholder="First Name" value="<?php if(isset($_SESSION['fname'])) { echo $_SESSION['fname']; } ?>" required> <br> <?php if(in_array("Your first name must be 2-50 characters long.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your first name must be 2-50 characters long.</span><br>"; ?> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_profile"></i></span> <input type="text" class="form-control" name="lname" placeholder="Last Name" value="<?php if(isset($_SESSION['lname'])) { echo $_SESSION['lname']; } ?>" required> <br> <?php if(in_array("Your last name must be 2-50 characters long.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your last name must be 2-50 characters long.</span><br>"; ?> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_mail_alt"></i></span> <input type="text" class="form-control" name="email" placeholder="Email" value="<?php if(isset($_SESSION['email'])) { echo $_SESSION['email']; } ?>" required> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_mail_alt"></i></span> <input type="text" class="form-control" name="email2" placeholder="Confirm Email" value="<?php if(isset($_SESSION['email2'])) { echo $_SESSION['email2']; } ?>" required> <br> <?php if(in_array("Email already in use<br>", $error_array)) echo "<span style='color: #AD0303;'>Email already in use</span><br>"; else if(in_array("Invalid Email<br>", $error_array)) echo "<span style='color: #AD0303;'>Invalid Email</span><br>"; else if(in_array("Emails don't match<br>", $error_array)) echo "<span style='color: #AD0303;'>Emails don't match</span><br>"; ?> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_key_alt"></i></span> <input type="password" class="form-control" name="pwd" placeholder="Password" required> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon_key_alt"></i></span> <input type="password" class="form-control" name="pwd2" placeholder="Confirm Password" required> <br> <?php if(in_array("Your passwords don't match.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your passwords don't match.</span><br>"; else if(in_array("Your password must contain English characters or numbers.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your password must contain English characters or numbers.</span><br>"; else if(in_array("Your password must be 5-30 characters long.<br>", $error_array)) echo "<span style='color: #AD0303;'>Your password must be 5-30 characters long.</span><br>"; ?> </div> <input class="btn btn-info btn-lg btn-block" type="submit" name="register" value="Register"> </div> <?php if(in_array("<span style='color: #14C800;'>You're all set! Go ahead and login!</span><br>", $error_array)) echo "<span style='color: #14C800;'>You're all set! Go ahead and login!</span><br>"; ?> </form> </div> </body> </html> and my includes/form_handlers/register.php file: <?php //error variables $fname = ""; $lname = ""; $email = ""; $email2 = ""; $pwd = ""; $pwd2 = ""; $date = ""; $error_array = array(); if(isset($_POST['register'])) { //form values $fname = clean($_POST['fname']); $_SESSION['fname'] = $fname; $lname = clean($_POST['lname']); $_SESSION['lname'] = $lname; $email = clean($_POST['email']); $_SESSION['email'] = $email; $email2 = clean($_POST['email2']); $_SESSION['email2'] = $email2; $pwd = strip_tags($_POST['pwd']); $pwd2 = strip_tags($_POST['pwd2']); $date = date('Y-m-d'); //signup date if($email == $email2) { //validate email format if(filter_var($email, FILTER_VALIDATE_EMAIL)) { $email = filter_var($email, FILTER_VALIDATE_EMAIL); //does email exist?? $email_check = mysqli_query($conn, "SELECT email FROM users WHERE email='$email'"); //number of rows returned $num_rows = mysqli_num_rows($email_check); if($num_rows > 0) { array_push($error_array, "Email already in use<br>"); } } else { array_push($error_array, "Invalid Email<br>"); } } else { array_push($error_array, "Emails don't match<br>"); } //first name length if(strlen($fname) > 50 || strlen($fname) < 2) { array_push($error_array, "Your first name must be 2-50 characters long.<br>"); } //last name length if(strlen($lname) > 50 || strlen($lname) < 2) { array_push($error_array, "Your last name must be 2-50 characters long.<br>"); } if($pwd != $pwd2) { array_push($error_array, "Your passwords don't match.<br>"); } else { if(preg_match('/[^A-Za-z0-9]/', $pwd)) { array_push($error_array, "Your password must contain English characters or numbers.<br>"); } } if(strlen($pwd) > 30 || strlen($pwd) < 2) { array_push($error_array, "Your password must be 5-30 characters long.<br>"); } if(empty($error_array)) { $pwd = md5($pwd); //encrypts password $username = strtolower($fname . "_" . $lname); $check_username = mysqli_query($conn, "SELECT username FROM users WHERE username='$username'"); //assign unique username if original is taken $snum = 0; while(mysqli_num_rows($check_username) != 0) { $snum++; $username = $username . "00" . $snum; $check_username = mysqli_query($conn, "SELECT username FROM users WHERE username='$username'"); } //assign a random profile pic $rand = rand(1,3); switch ($rand) { case '1': $profile_pic = "assets/images/profile_pics/default/01.jpeg"; break; case '2': $profile_pic = "assets/images/profile_pics/default/02.jpeg"; break; case '3': $profile_pic = "assets/images/profile_pics/default/03.jpeg"; break; } $query = mysqli_query($conn, "INSERT INTO users VALUES (NULL, '$fname', '$lname', '$username', '$email', '$pwd', '$date', '$profile_pic', '0', '0', 'no', ',')"); array_push($error_array, "<span style='color: #14C800;'>You're all set! Go ahead and login!</span><br>"); //clear session variables $_SESSION['fname'] = ""; $_SESSION['lname'] = ""; $_SESSION['email'] = ""; $_SESSION['email2'] = ""; } } //polish user imput function clean($data) { $data = str_replace(" ","", $data); $data = htmlspecialchars($data); $data = stripslashes($data); $data = strip_tags($data); $data = trim($data); return $data; } ?> I can't get the reg. form handler to recognize the $conn variable from the config.php file. if I add require '../../config/config.php'; to it I get this error:
Warning: require(../../config/config.php): failed to open stream: No such file or directory in /opt/lampp/htdocs/qcicnews/includes/form_handlers/register.php on line 3 I don't know why it can't find that file, but the way I understand PHP is that I don't need that line because it's in the register.php. When I don't use it I get a party of errors all connected to it not recognizing the $conn variable:
Notice: Undefined variable: conn in /opt/lampp/htdocs/qcicnews/includes/form_handlers/register.php on line 43
There's about 6 more that look like the ones above but from different lines where $conn is referenced, I just deleted them for brevity sake. I'm pretty new to PHP and this is the most difficult situation I've encountered so far, can someone help me find the way here?
I've made a custom error handler, but it doesn't seem to work the same way on the dev and prod environments. Dev is windows/xampp, and prod is a standard LAMP install. Sometimes on prod I get a blank white screen and dev shows no errors. If I remove the error handler, everything goes back to normal. Just wondering if anyone sees something wrong he Code: [Select] <?php function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) { // email address to email errors to on the production environment $email_address = 'myemailaddress@gmail.com'; switch ($e_number) { case E_USER_ERROR: $error_type = 'E_USER_ERROR'; break; case E_USER_WARNING: $error_type = 'E_USER_WARNING'; break; case E_USER_NOTICE: $error_type = 'E_USER_NOTICE'; break; case E_WARNING: $error_type = 'E_WARNING'; break; case E_NOTICE: $error_type = 'E_NOTICE'; break; case E_STRICT: $error_type = 'E_STRICT'; break; default: $error_type = 'UNKNOWN ERROR TYPE'; break; } $message = '<hr />PHP ' . $error_type . ' #' . $e_number . ' - Date/Time: ' . date('n/j/Y H:i:s') . "\n" . '<br />File: <b>' . $e_file . "</b>\n" . '<br />Line: <b>' . $e_line . "</b>\n" . '<br /><b>' . $e_message . '</b><hr />'; // Output for development environment if (stristr($_SERVER['HTTP_HOST'], 'localhost' )) { echo $message; } // Email for production environment else { error_log($message, 1, $email_address ); if ( $e_number != E_NOTICE && $e_number < E_STRICT) { die('A system error occurred. We apologize for the inconvenience.'); } } // Don't execute PHP internal error handler return true; } function my_error_handling() { set_error_handler('my_error_handler', E_ALL); } Is it possible to find out what line of code a PHP script was processing immediately before it is interrupted upon receiving a POSIX signal? A bit of background - I've got a PHP script which runs (from the command line) hundreds of thousands of times a day and usually it's just fine. Every so often (less than once a week) it gets into a muddle and freezes until I kill it. I've written a signal handler (using the posix_signal() function) into the script which catches SIGABRT signals. When it gets one, it dumps $GLOBALS to a file, cleanly releases the data its working on then exits. That gives me a nice 'get out of jail free' card, but I'd really like to identify where (and then why) it's freezing. I could insert loads of debugging code which sets some variable with what stage it's up to, but it's a fairly complicated script and I'd rather not. There's got to be a better way! __LINE__ and __FUNCTION__ unfortunately just point to my signal handler function. So, is there anyway that the function which is invoked by the SIGABRT signal can report what line of code the script was on at the time the SIGABRT was received? Or alternatively, is there a way to figure out what a running PHP script is doing if you know its PID? Maybe there's something in /proc/<PID> which might help me... I have an SQL table such as this: Pairing1 Pairing2 Week 6 1 1 5 2 1 4 3 1 1 3 2 5 4 2 3 6 2 and another with teams such as: teamid teamname 1 Teamname 1 2 Teamname 2 3 Teamname 3 The numbers in the pairing are numbers of teams, which is in another SQL table. What would be the most efficient way... of displaying the information in the form of pairngs such as Week 1: Team 6 vs Team 1 Team 5 vs Team 2 etc .... What is the best way for me to sort my results? 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> <? } ?> Hello everyone, I have a datatbase containing fields id, question, answer, and type. The questions are in true/false format, multiple choice and fill in the blank(text). At the moment, I am only trying to get the true and false questions to work. My code is as follows Code: [Select] <?php $connection = mysql_connect("localhost","root","root") or die("couldn't connect"); $select = mysql_select_db("login") or die ("cannot select database!"); $query = mysql_query("SELECT * FROM questions"); $numrows = mysql_num_rows($query); if ($numrows!=0) { //code to login while($row = mysql_fetch_assoc($query)) { $dbquestion = $row['question']; $dbanswer = $row['answer']; $dbtype = $row['type']; $dbid = $row['id']; $correctanswer = explode('|',"$dbanswer"); switch($dbtype){ case "mchoice": echo"<br/>"; echo $dbquestion; echo"<br/>"; break; case "boolean": echo"<br/>"; echo $dbquestion; echo"<br/>"; echo $correctanswer[0]; //display radio buttons ?> <form name="boolean" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> True <input name="question" type="radio" value= "True" /> False <input name="question" type="radio" value= "False" /> <input name="id" input type="hidden" value="<?php $dbid ?>" /> <input type="submit" name="submit" id="submit" value="Submit" /> <?php echo "The answer submitted was "; echo $_POST['question']; ?> <?php break; case "text": echo"<br/>"; echo $dbquestion; echo"<br/>"; //display text box break; } } } ?> The problem I'm having is that this creates a submit button for each question. When choosing true or false for the answer and pressing submit, the answer is selected for every question. I need the code to look at what the user has entered, check the answer against correctanswer[0]. I'm really in a bit of a hole here and if anyone can help me it would be greatly appreciated. Many thanks in advance James Hi, I am just looking for some input on how I could make this form processing script more secure. In fact extremely secure. Like the most secure server side filtering can get! Code: [Select] <?php // Mail header removal function remove_headers($string) { $headers = array( "/to\:/i", "/from\:/i", "/bcc\:/i", "/cc\:/i", "/Content\-Transfer\-Encoding\:/i", "/Content\-Type\:/i", "/Mime\-Version\:/i" ); if (preg_replace($headers, '', $string) == $string) { return $string; } else { die('Spam much?'); } } // Build the email $to = 'info@example.com'; $subject = "Secure contact form message from: $subject"; $message = "$name said: $message"; $headers = "From: $email"; // field validation if ($subject=="" || $message=="" || $name=="") { print ("All form fields are required. Please go back and try again."); } else { // email validation if(!eregi('^([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9-]+)(\.[a-z]{2,3})?)$', $email)) { print ("Your email address does not appear to be valid. Please go back and try again."); exit; } // Send the mail mail($to, $subject, $message, $headers); // Redirect header('Location: ../submitted.php'); } ?> Okay after correcting the issues with the jQuery side of things I'm having a small error with the php processing side. I'm getting a response back in firebug that there is an undefined index "name" and undefined index "value". Now I'm not sure on a fix but I know I'll have to do some sort of foreach I think because on the jquery dataString is a each so there's going to be more than name and value coming in at one time. Code: [Select] <?php error_reporting(E_ALL); // Include the database page include ('../inc/dbconfig.php'); $styleID = $_GET['id']; $query = "SELECT fields.ID, fields.fullName, fields.enabled FROM fields INNER JOIN styles ON styles.ID = fields.styleID WHERE styles.ID = '" . $styleID . "'"; $result = mysqli_query ( $dbc, $query ); // Run The Query ?> <script> $(document).ready(function() { $('div.message-error').hide(); $('div.message-success').hide(); $("input.submit").click(function() { $('div.message-error').hide(); var dataString = '&submitBioFields=True'; $('#bioConfigForm .field').each(function() { dataString += '&'+$(this).find('input:first').attr('name')+'='; dataString += ($(this).find('input[value|=0]').is(':checked')) ? '0' : '1'; }); alert(dataString); $.ajax({ type: "POST", url: "processes/bioconfig.php", data: dataString, success: function() { $('div.message-error').hide(); $("div.message-success").html("<h6>Operation successful</h6><p>Bio fields saved successfully.</p>"); $("div.message-success").show().delay(10000).hide("slow", function() { $('#content').load('mods/bioconfiguration.php'); }); } }); return false; }); }); </script> <!-- Title --> <div id="title" class="b2"> <h2>Bio Configuration</h2> <!-- TitleActions --> <div id="titleActions"> <!-- ListSearch --> <div class="listSearch actionBlock"> <div class="search"> <label for="search">Recherche</label> <input type="text" name="search" id="search" class="text" /> </div> <div class="submit"> <button type="submit" id="search-button" class="button"><strong><img src="img/icons/search_48.png" alt="comments" class="icon "/></strong></button> </div> </div> <!-- /ListSearch --> </div> <!-- /TitleActions --> </div> <!-- Title --> <!-- Inner Content --> <div id="innerContent"> <!-- Form --> <form action="#" id="bioConfigForm" > <fieldset> <legend>Bio Config</legend> <?php while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { ?> <div class="field"> <label for="<?php '' . $row['ID'] . '' ?>"><?php echo '' . $row['fullName'] . ''?></label> <input type="radio" value="0" name="<?php echo $row['ID']; ?>" class="status" <?php if($row['enabled'] == 0) echo ' checked="checked"'; ?> />Enabled <input type="radio" value="1" name="<?php echo $row['ID']; ?>" class="status" <?php if($row['enabled'] == 1) echo ' checked="checked"'; ?> />Disabled </div> <?php } ?> <input type="submit" class="submit" name="submitBioFields" id="SubmitBioFields" title="Submit Bio Fields" value="Submit Bio Fields"/> </fieldset> </form> <!-- /Form --> <!-- Messages --> <div class="message message-error"> <h6>Required field missing</h6> <p>Please fill in all required fields. </p> </div> <div class="message message-success"> <h6>Operation succesful</h6> <p>Bio configuraton was eddited to the database.</p> </div> <!-- /Messages --> <?php error_reporting(E_ALL); // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['submitBioFields'])) { $fieldID = (int)$_POST['name']; $value = (int)$_POST['value']; $query = "UPDATE `fields` SET `enabled` = '".$value."' WHERE `ID` = '".$fieldID."'"; mysqli_query($dbc,$query); $result = "good"; } //Output the result echo $result; ?> 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()); } ?> What I'm wanting to do for the UPDATE statement is have it update the current value of answer_votes for that answer in that form to have it increase its value + 1 and increase the value of totalVotes for the specific poll +1 but not sure how that's accomplished. My table scheme is below. Code: [Select] if (isset($_POST['vote_poll'])) { $poll_quetion_id = mysqli_real_escape_string($dbc, $_POST['poll_question_id']); $poll_answer_id = (int) $_POST['id']; $voter_ip_address = $_SERVER["REMOTE_ADDR"]; $voter_ip_host = $_SERVER['HTTP_HOST']; $query = "SELECT * FROM `poll_answer_votes` WHERE ((`voter_ip_addess` = '".$voter_ip_address."') AND (`voter_ip_host` = '".$voter_ip_host."'))"; $Qresult = mysqli_query ( $dbc, $query ); // Run The Query if (mysqli_num_rows($Qresult) == 0) { $query = "INSERT INTO `poll_answer_votes` (poll_question_id, poll_answer_id, voter_ip_address, voter_ip_host, vote_time_stamp) VALUES ('".$poll_question_id."','".$poll_answer_id."','".$voter_ip_addres."','".$voter_ip_host."', NOW())"; mysqli_query($dbc, $query); $query = "UDPATE `poll_answers` SET "; mysqli_query($dbc, $query); $result = "good"; } else { } } Table: polls Fields: id, poll_question, total_votes Table: poll_answers Fields: id, poll_id, poll_answer, answer_votes Table: poll_answer_votes Fields: id, poll_question_id, poll_answer_id, voter_ip_address, voter_ip_host, vote_time_stamp. |