Jump to content

Search the Community

Showing results for tags 'php'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hello all. I have worked my head out but i cant seem to figure out why i am getting error/entering empty stings. I have tried different things but none seems to work as expected. i know the problem is from the array field validation but cant seem to figure out how to get it done. If i submit without entering any field, the error works fine. But if i fill only one field, it gives error and saves empty strings. Thanks if(isset($_POST['submit'])) { $test_score = $_POST['test_score'][0]; $exam_score = $_POST['exam_score'][0]; if(empty($test_score)) { $error['test_score'] = "Test Score Field is Required"; }if(empty($exam_score)) { $error['exam_score'] = "Exam Score Field is Required"; } if(empty($error)) { foreach ($_POST['subject'] as $key => $value) { $sql = "INSERT INTO $table_name( subject, test_score, exam_score ) VALUES( :subject, :test_score, :exam_score )"; $stmt = $pdo->prepare($sql); $stmt->execute([ 'subject' => $value, 'test_score' => $_POST['test_score'][$key], 'exam_score' => $_POST['exam_score'][$key] ]); } if($stmt->rowCount()){ echo '<div class="alert alert-success text-center">Data Saved</div>'; }else{ echo '<div class="alert alert-danger text-center">Data Not Saved</div>'; } }else{ echo '<br><div class="alert alert-danger text-center">Fields Empty!</div>'; } } //my form <table class="table table-borderless"> <thead> <tr> <th>SN</th> <th>Subject</th> <th>Continuous Assesment Score</th> <th>Examination Score</th> </tr> </thead> <tbody> <div> <form action="" method="post"> <?php $i = 1; $stmt=$pdo->query(" SELECT subjects FROM tbl_subjects_secondary "); WHILE($row = $stmt->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <th><?php echo $i++ ?></th> <td><input type="text" name="subject[]" class="form-control border-0" readonly value="<?php if(isset($row['subject_name'])) { echo $row['subject_name']; } ?>"></td> <td><input type="number" name="test_score[]" class="form-control"><span style="color: red; font-size: .8em;"><?php if(isset($error['test_score'])){ echo $error['test_score'];} ?></span></td> <td><input type="number" name="exam_score[]" class="form-control"><span style="color: red; font-size: .8em;"><?php if(isset($error['exam_score'])){ echo $error['exam_score'];} ?></span></td> </tr> <?php } ?> <tr> <td></td><td></td> <td colspan="2"><button type="submit" name="save" class="btn btn-primary w-50">Save</button></td> </tr> </form> </div> </tbody> </table>
  2. As long as it's SQL injection proof, would it be alright for me to let non-members add comments to a post and give the Author the ability to delete them?
  3. I get this message and not sure how to fix it...... Success... NULL Warning: mysqli_get_host_info() expects parameter 1 to be mysqli, null given in /www/zzl.org/o/t/t/ottawaglandorfems/htdocs/class-db.php on line 14 Success... NULL This is my form - <?php require_once('class-db.php'); /** * function to check the validity of the given string * $what = what you are checking (phone, email, etc) * $data = the string you want to check */ function isValid( $what, $data ) { switch( $what ) { // validate a phone number case 'phone': $pattern = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i"; break; // validate email address case 'email': $pattern = "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i"; break; default: return false; break; } return preg_match($pattern, $data) ? true : false; } $errors = array(); if( isset($_POST['btn_submit']) ) { if( !isValid( 'phone', $_POST['phone'] ) ) { $errors[] = 'Please enter a valid phone number'; } if( !isValid( 'email', $_POST['email'] ) ) { $errors[] = 'Please enter a valid email address'; } } if( !empty($errors) ) { foreach( $errors as $e ) echo "$e <br />"; } if ( !empty ( $_POST ) ) { $type = 'post'; $insert = insert($type, $values); } ?> <html> <head> <title>Registration form for Octoberfest With O-G EMS 2013</title> </head> <body> <form action="" method="post"> <p Registration /> <p>First Name:<input type="text" name="fname" > </p> <p>Last Name:<input type="text" name="lname" > </p> <p>Phone Number:<input type="text" name="phone" ></p> <p>Address:<input type="text" name="address" ></p> <p>Department:<input type="text" name="department" ></p> <p>Email Address:<input type="text" name="email" ></p> <p>Level of Training:<input type="text" name="level" ></p> <input type="submit" name="btn_submit" value="Register"> </form> </body> </html> and this is my script <?php require_once('config1.php'); function connect() { $sql = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if ($sql->connect_error) { die('Connect Error (' . $sql->connect_errno . ') ' . $sql->connect_error); }echo 'Success... ' . mysqli_get_host_info($link) . "\n"; return $sql; } function insert($type){ $sql=connect(); /* Set our params */ $fname = $_POST["fname"]; $lname = $_POST["lname"]; $phone = $_POST["phone"]; $address = $_POST["address"]; $department = $_POST["department"]; $email = $_POST["email"]; $level = $_POST["level"]; $query=("INSERT INTO Oktoberfest2013 (First_Name, Last_Name, Phone, Address, Department, Email_Address, Level_of_Traning) values (?, ?, ?, ?, ?, ?, ?)"); /* Create the prepared statement */ if ($stmt = $sql->prepare($query)); var_dump($qSelect); if ( !$sql->query($query) ) { return "Errormessage: $mysqli->error"; /* Bind our params */ $stmt->bind_param('sssssss', $fname, $lname, $phone, $address, $department, $email, $level); /* Execute the prepared Statement */ $stmt->execute(); } } function select($query) { $sql = connect(); $result = $sql->query($query); while ( $obj = $result->fetch_object() ) { $return[] = $obj; } } ?> Thanks in advance for the help.
  4. Hello. I'm a newbie so sorry if this isn't the best forum to post my problem. I am using a MySQL and PHP to create a web app. I have authentication, and I can register users. I also have a form that users provide information and it is successfully inserting data into a table in my database. I will use fictional fields for my database table called meal_info: username dateStartedDiet numberMealsPerDay costPerMeal Problem: Select user-specific data from the MySQL database, using Session username to select only the current user's data, then display it and do some calculations. Here is thecode at the top, and I am fairly sure it's working: session_start(); //execute commone code require("common.php"); //includes code to connect to database, etc. if(empty($_SESSION['user'])) { // If they are not, we redirect them to the login page. header("Location: login.php"); // Remember that this die statement is absolutely critical. Without it, // people can view your members-only content without logging in. die("Redirecting to login.php"); } Here is the part of the code that has to do with displaying user data: $userID = $_SESSION['user']['username']; //create a variable that is the session username which is identical to the field in our MySQL table $query = "SELECT * FROM meal_info WHERE username = $userID"; //our SELECT statement $result = db->query($query); //execute the query $row_count = $result->num_rows;//count the rows in the table and place in variable to use in incremental loop code for ($i = 0; $i < $row_count; $i++) : $row = $result->fetch_assoc(); //for each row in the table, fetch and create and array $dateStart = $row['dateStartedDiet']; $numberMeals = $row['numberMealsPerDay']; $costMeal = $row['costPerMeal']; echo $dateStart; echo $numberMeals; echo $costMeal;
  5. Hello to everybody, I need critiques and "website crawling help" about my website http://enginery.freecluster.eu . My crawling question was that: I tried google search console tools to add my website's sitemap and add it : http://enginery.freecluster.eu/sitemap.xml . It says my sitemap is ok and found 312 pages but not crawl all correctly! Three weeks have passed but nothing changed. I manually request indexing some pages(about 4 pages) and google search console, after than today it only shows some of them(not all 4) when I search using "site:http://enginery.freecluster.eu". My website's all files have php extensions. Did this prevent googlebot to reach the content of my websites' pages? My robots.txt file's content is : User-agent: Googlebot Allow: / User-agent: * Allow: / Sitemap: http://enginery.freecluster.eu/sitemapv1.xml Any critiques and help is appreciated. Thanks.
  6. Hey guys, i was trying to add google recaptcha to my login register system, for a spam defense and just to give it a more professional feel. i already have my own conditional in my own system to make sure an email is not already used or to make sure a password is a certain length, etc.... i now want to add the existing code from google and add an additional conditional to make it flow as one. my issue so i followed the directions from goodle developers and when implementing the code by itself on a test page, i encounter no problems. i get the proper pass and fail, depending on what security code is entered. when i move that same logic into my already created system i then get a consistent failure with no pass. i am utterly confused as to why this is happening, if you guys can give me any suggestions that would be great. my code TEST PAGE .. WORKS FINE <?php include('include/init.php'); include('include/header.php'); require_once 'recaptchalib.php'; $privatekey = "6Lf5AeASAAAAAO5DJ1GcIAiwd8kkNbVBgrDrandom"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { echo 'FAILURE'; } else { echo 'SUCCESS'; // Your code here to handle a successful verification } ?> <tr> <form method='post' action='test.php' id='test'> <td class="register_td_left2"><span class="">Security Code:</span></td> <td valign="middle" style="padding-left:2px"> <?php require_once 'recaptchalib.php'; $publickey = "6Lf5AeASAAAAAPue6LLdUDttmPDc-NbRHcnrandom"; // you got this from the signup page echo recaptcha_get_html($publickey); ?></td> <input type='submit' value='Submit'></input> </form> </tr> Register page i try to implement the same logic require_once 'recaptchalib.php'; $privatekey = "6Lf5AeASAAAAAO5DJ1GcIAiwd8kkNbVBgrandom"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (empty($_POST) === false) { $required_fields = array('register_email','register_username','password','confirm_pass','gender','month','date','year','country'); foreach($_POST as $key => $value){ if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = '* All fields are required!'; break 1; } } if (empty($errors) === true) { if (user_exists($_POST['register_username']) === true) { $errors[] = 'Sorry, the username \'' . $_POST['register_username'] . '\' has already been taken. Please choose another username.'; } if (preg_match("/\\s/", $_POST['register_username']) == true) { $errors[] = 'Sorry your username must not contain any spaces!'; } if (strlen($_POST['password']) < 6 ){ $errors[] = 'Your Password must be a minimal 6 characters long'; } if ($_POST['password'] !== $_POST['confirm_pass']) { $errors[] = 'Your Passwords do not match, please make sure both passwords are the same!'; } if (filter_var($_POST['register_email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = 'A valid email adress is required'; } if(email_exists($_POST['register_email']) === true){ $errors[] = 'The email you provided is already in use. If you are having trouble remembering your user info click <a href="#">here</a>'; } if (!$resp->is_valid) { $errors[] = 'You need to enter a valid security code'; } } } <form name="register" action="register.php" method="post"> <tr> <td class="register_td_left2"><span class="">Security Code:</span></td> <td valign="middle" style="padding-left:2px"> <?php require_once 'recaptchalib.php'; $publickey = "6Lf5AeASAAAAAPue6LLdUDttmPDc-NbRandom"; // you got this from the signup page echo recaptcha_get_html($publickey); ?></td> </tr> </form> i left out most of the form , just to save some reading time for you guys. figure its of no importance. again i am puzzled as to why this doesnt work for me on this page, yet on the test page it works fine. please i have been stuck on this for far to long for such a simple thing. thanks.
  7. Hey guys, im trying to create a 'captcha' image for registration security for my site. currently i have 2 separate pages working together, my captcha.php file & my register.php now, what i am doing is trying to get a generate code that will be random and create an image with this string. this image will then be linked in the registration form where the user will have to match that random string image. sounds simple except , for some reason the code i have supplied from the tutorial is not outputting the image in the form. i have GD's installed on my server, and i have the font file saved also in the directory/ my code is : captcha.php <?session_start(); header('Content-type: image/jpeg'); $text = $_SESSION['secure']; $font_size = 30; $image_height = 200; $image_width = 40; $image = imagecreate($image_width, $image_height); imagecolorallocate($image, 255, 255, 255); // white $text_color = imagecolorallocate($image, 0, 0, 0); //black imagettftext($image, $font_size, 0, 15, 30, $text_color, 'font.ttf', $text); imagejpeg($image); ?> so in this i have created the image captcha.php should now be a jpeg.. i then go to my register.php declare the $_SESSION and input the src="captcha.php'' register.php <?php include('include/init.php'); $_SESSION['secure'] = rand(1000,9999); ?> and the form : <tr> <td class="register_td_left2"><span class="">Security Code:</span></td> <td valign="middle" style="padding-left:2px"><input id="security_code" name="security_code" type="text" maxlength="4" size="5"></td> <td align="left" valign="middle"><img src="generate.php" alt="Your Security Code"></td> </tr> this is my first time adding a captcha and going through this process. the only thing i can think that would not be allowing it output the image, would be the 'font.tff' not properly working, or for some odd reason i dont have the GD functions installed correctly. any suggestions ? or ideas ?
  8. Hi everyone, I hope cyberRobot or Guru is reading this thread. I am trying to create a vertical table data in php from method of GET and POST. Is it possible? I succeed created the vertical table data from database (MySQL). I created the vertical table data on php that inside the form thathas method of GET or POST, that should allow any value in php go to another page by method of GET, but seem it doesn't work. Maybe I miss something in code? Help will be very appreciate. I am still learning, ready to get in interaction in php. Here my code: <!doctype html> <html> <head> <title>Test array attendence</title> </head> <body> <table> <?php $columns = 2; if(isset($_GET['member'])) { $display = $_GET['member']; $num_row = $display; $rows = ceil($num_row / $columns); <-- It is causing an error in code, line 14. while ($row = $display) { $data[] = $row; } echo "<table border='1'>"; for($i = 0; $i < $rows; $i++) { echo "<tr>"; for($j = 0; $j < $columns; $j++) { if(isset($data[$i + ($j * $row)])) { echo "<td>".$data[$i + ($j * $row)]."</td>"; $count = $count+1; } } echo "</tr>"; } } ?> </table> <table><tr><td><?php echo $count." are attending this meeting tonight." ?></td></tr></table> </body> </html> I get an error message - Fatal error: Unsupported operand types in /srv/disk10/1141650/www/sigmahokies.biz.ht/testarray3.php on line 14
  9. I have the complete website, and works fine on windows using XAMPP control panel accessing via localhost. Now I am having trouble accessing the table(s) via ubuntu after turning on mysql in ubuntu also I am receving no errors just a blank page. You can check the php but it might not make any difference. All assoicated files for linking with mysql are below if needed I will upload whole webiste without images. I have stopped mysql and restarted it, over and over again. Also tried using sudo /usr/sbin/mysqld --skip-grant-tables --skip networking & command and no luck. Website is running succesfully just mysql is not working any suggestion on what could be wrong. add-aboutme.php add-contactme.php add-guestbook.php delete-contact.php guestbook.php view-aboutme.php view-contactme.php view-guestbook.php
  10. Well, I am a total Python Newbie but know PHP very well, I wanted to create a website that would help people to generate Word crosswords, hence after a little web search I found this Python Code which I need help in converting to PHP> I tried myself but failed as I know nothing about Python, I also tried an online conversion tool, but without any luck, so if anyone here can help me convert the following code to PHP, it will be highly respected. Heres the code: import random, re, time, string from copy import copy as duplicate class Crossword(object): def __init__(self, cols, rows, empty = '-', maxloops = 2000, available_words=[]): self.cols = cols self.rows = rows self.empty = empty self.maxloops = maxloops self.available_words = available_words self.randomize_word_list() self.current_word_list = [] self.debug = 0 self.clear_grid() def clear_grid(self): # initialize grid and fill with empty character self.grid = [] for i in range(self.rows): ea_row = [] for j in range(self.cols): ea_row.append(self.empty) self.grid.append(ea_row) def randomize_word_list(self): # also resets words and sorts by length temp_list = [] for word in self.available_words: if isinstance(word, Word): temp_list.append(Word(word.word, word.clue)) else: temp_list.append(Word(word[0], word[1])) random.shuffle(temp_list) # randomize word list temp_list.sort(key=lambda i: len(i.word), reverse=True) # sort by length self.available_words = temp_list def compute_crossword(self, time_permitted = 1.00, spins=2): time_permitted = float(time_permitted) count = 0 copy = Crossword(self.cols, self.rows, self.empty, self.maxloops, self.available_words) start_full = float(time.time()) while (float(time.time()) - start_full) < time_permitted or count == 0: # only run for x seconds self.debug += 1 copy.current_word_list = [] copy.clear_grid() copy.randomize_word_list() x = 0 while x < spins: # spins; 2 seems to be plenty for word in copy.available_words: if word not in copy.current_word_list: copy.fit_and_add(word) x += 1 #print copy.solution() #print len(copy.current_word_list), len(self.current_word_list), self.debug # buffer the best crossword by comparing placed words if len(copy.current_word_list) > len(self.current_word_list): self.current_word_list = copy.current_word_list self.grid = copy.grid count += 1 return def suggest_coord(self, word): count = 0 coordlist = [] glc = -1 for given_letter in word.word: # cycle through letters in word glc += 1 rowc = 0 for row in self.grid: # cycle through rows rowc += 1 colc = 0 for cell in row: # cycle through letters in rows colc += 1 if given_letter == cell: # check match letter in word to letters in row try: # suggest vertical placement if rowc - glc > 0: # make sure we're not suggesting a starting point off the grid if ((rowc - glc) + word.length) <= self.rows: # make sure word doesn't go off of grid coordlist.append([colc, rowc - glc, 1, colc + (rowc - glc), 0]) except: pass try: # suggest horizontal placement if colc - glc > 0: # make sure we're not suggesting a starting point off the grid if ((colc - glc) + word.length) <= self.cols: # make sure word doesn't go off of grid coordlist.append([colc - glc, rowc, 0, rowc + (colc - glc), 0]) except: pass # example: coordlist[0] = [col, row, vertical, col + row, score] #print word.word #print coordlist new_coordlist = self.sort_coordlist(coordlist, word) #print new_coordlist return new_coordlist def sort_coordlist(self, coordlist, word): # give each coordinate a score, then sort new_coordlist = [] for coord in coordlist: col, row, vertical = coord[0], coord[1], coord[2] coord[4] = self.check_fit_score(col, row, vertical, word) # checking scores if coord[4]: # 0 scores are filtered new_coordlist.append(coord) random.shuffle(new_coordlist) # randomize coord list; why not? new_coordlist.sort(key=lambda i: i[4], reverse=True) # put the best scores first return new_coordlist def fit_and_add(self, word): # doesn't really check fit except for the first word; otherwise just adds if score is good fit = False count = 0 coordlist = self.suggest_coord(word) while not fit and count < self.maxloops: if len(self.current_word_list) == 0: # this is the first word: the seed # top left seed of longest word yields best results (maybe override) vertical, col, row = random.randrange(0, 2), 1, 1 ''' # optional center seed method, slower and less keyword placement if vertical: col = int(round((self.cols + 1)/2, 0)) row = int(round((self.rows + 1)/2, 0)) - int(round((word.length + 1)/2, 0)) else: col = int(round((self.cols + 1)/2, 0)) - int(round((word.length + 1)/2, 0)) row = int(round((self.rows + 1)/2, 0)) # completely random seed method col = random.randrange(1, self.cols + 1) row = random.randrange(1, self.rows + 1) ''' if self.check_fit_score(col, row, vertical, word): fit = True self.set_word(col, row, vertical, word, force=True) else: # a subsquent words have scores calculated try: col, row, vertical = coordlist[count][0], coordlist[count][1], coordlist[count][2] except IndexError: return # no more cordinates, stop trying to fit if coordlist[count][4]: # already filtered these out, but double check fit = True self.set_word(col, row, vertical, word, force=True) count += 1 return def check_fit_score(self, col, row, vertical, word): ''' And return score (0 signifies no fit). 1 means a fit, 2+ means a cross. The more crosses the better. ''' if col < 1 or row < 1: return 0 count, score = 1, 1 # give score a standard value of 1, will override with 0 if collisions detected for letter in word.word: try: active_cell = self.get_cell(col, row) except IndexError: return 0 if active_cell == self.empty or active_cell == letter: pass else: return 0 if active_cell == letter: score += 1 if vertical: # check surroundings if active_cell != letter: # don't check surroundings if cross point if not self.check_if_cell_clear(col+1, row): # check right cell return 0 if not self.check_if_cell_clear(col-1, row): # check left cell return 0 if count == 1: # check top cell only on first letter if not self.check_if_cell_clear(col, row-1): return 0 if count == len(word.word): # check bottom cell only on last letter if not self.check_if_cell_clear(col, row+1): return 0 else: # else horizontal # check surroundings if active_cell != letter: # don't check surroundings if cross point if not self.check_if_cell_clear(col, row-1): # check top cell return 0 if not self.check_if_cell_clear(col, row+1): # check bottom cell return 0 if count == 1: # check left cell only on first letter if not self.check_if_cell_clear(col-1, row): return 0 if count == len(word.word): # check right cell only on last letter if not self.check_if_cell_clear(col+1, row): return 0 if vertical: # progress to next letter and position row += 1 else: # else horizontal col += 1 count += 1 return score def set_word(self, col, row, vertical, word, force=False): # also adds word to word list if force: word.col = col word.row = row word.vertical = vertical self.current_word_list.append(word) for letter in word.word: self.set_cell(col, row, letter) if vertical: row += 1 else: col += 1 return def set_cell(self, col, row, value): self.grid[row-1][col-1] = value def get_cell(self, col, row): return self.grid[row-1][col-1] def check_if_cell_clear(self, col, row): try: cell = self.get_cell(col, row) if cell == self.empty: return True except IndexError: pass return False def solution(self): # return solution grid outStr = "" for r in range(self.rows): for c in self.grid[r]: outStr += '%s ' % c outStr += '\n' return outStr def word_find(self): # return solution grid outStr = "" for r in range(self.rows): for c in self.grid[r]: if c == self.empty: outStr += '%s ' % string.lowercase[random.randint(0,len(string.lowercase)-1)] else: outStr += '%s ' % c outStr += '\n' return outStr def order_number_words(self): # orders words and applies numbering system to them self.current_word_list.sort(key=lambda i: (i.col + i.row)) count, icount = 1, 1 for word in self.current_word_list: word.number = count if icount < len(self.current_word_list): if word.col == self.current_word_list[icount].col and word.row == self.current_word_list[icount].row: pass else: count += 1 icount += 1 def display(self, order=True): # return (and order/number wordlist) the grid minus the words adding the numbers outStr = "" if order: self.order_number_words() copy = self for word in self.current_word_list: copy.set_cell(word.col, word.row, word.number) for r in range(copy.rows): for c in copy.grid[r]: outStr += '%s ' % c outStr += '\n' outStr = re.sub(r'[a-z]', ' ', outStr) return outStr def word_bank(self): outStr = '' temp_list = duplicate(self.current_word_list) random.shuffle(temp_list) # randomize word list for word in temp_list: outStr += '%s\n' % word.word return outStr def legend(self): # must order first outStr = '' for word in self.current_word_list: outStr += '%d. (%d,%d) %s: %s\n' % (word.number, word.col, word.row, word.down_across(), word.clue ) return outStr class Word(object): def __init__(self, word=None, clue=None): self.word = re.sub(r'\s', '', word.lower()) self.clue = clue self.length = len(self.word) # the below are set when placed on board self.row = None self.col = None self.vertical = None self.number = None def down_across(self): # return down or across if self.vertical: return 'down' else: return 'across' def __repr__(self): return self.word ### end class, start execution #start_full = float(time.time()) word_list = ['saffron', 'The dried, orange yellow plant used to as dye and as a cooking spice.'], \ ['pumpernickel', 'Dark, sour bread made from coarse ground rye.'], \ ['leaven', 'An agent, such as yeast, that cause batter or dough to rise..'], \ ['coda', 'Musical conclusion of a movement or composition.'], \ ['paladin', 'A heroic champion or paragon of chivalry.'], \ ['syncopation', 'Shifting the emphasis of a beat to the normally weak beat.'], \ ['albatross', 'A large bird of the ocean having a hooked beek and long, narrow wings.'], \ ['harp', 'Musical instrument with 46 or more open strings played by plucking.'], \ ['piston', 'A solid cylinder or disk that fits snugly in a larger cylinder and moves under pressure as in an engine.'], \ ['caramel', 'A smooth chery candy made from suger, butter, cream or milk with flavoring.'], \ ['coral', 'A rock-like deposit of organism skeletons that make up reefs.'], \ ['dawn', 'The time of each morning at which daylight begins.'], \ ['pitch', 'A resin derived from the sap of various pine trees.'], \ ['fjord', 'A long, narrow, deep inlet of the sea between steep slopes.'], \ ['lip', 'Either of two fleshy folds surrounding the mouth.'], \ ['lime', 'The egg-shaped citrus fruit having a green coloring and acidic juice.'], \ ['mist', 'A mass of fine water droplets in the air near or in contact with the ground.'], \ ['plague', 'A widespread affliction or calamity.'], \ ['yarn', 'A strand of twisted threads or a long elaborate narrative.'], \ ['snicker', 'A snide, slightly stifled laugh.'] a = Crossword(13, 13, '-', 5000, word_list) a.compute_crossword(2) print a.word_bank() print a.solution() print a.word_find() print a.display() print a.legend() print len(a.current_word_list), 'out of', len(word_list) print a.debug #end_full = float(time.time()) #print end_full - start_full
  11. I am attempting to create a php AJAX contact form , however the email never seems to arrive in my outlook. /* Jquery Validation using jqBootstrapValidation example is taken from jqBootstrapValidation docs */ $(function() { $("input,textarea").jqBootstrapValidation( { preventSubmit: true, submitError: function($form, event, errors) { // something to have when submit produces an error ? // Not decided if I need it yet }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $.ajax({ url: "./bin/contact_me.php", type: "POST", data: {name: name,phone:phone, email: email, message: message}, cache: false, success: function() { // Success message $('#success').html("<div class='alert alert-success'>"); $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append( "</button>"); $('#success > .alert-success') .append("<strong>Your message has been sent. </strong>"); $('#success > .alert-success') .append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append( "</button>"); $('#success > .alert-danger').append("<strong>Sorry "+firstName+" it seems that my mail server is not responding...</strong> Could you please email me directly ? Sorry for the inconvenience!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); $("a[data-toggle=\"tab\"]").click(function(e) { e.preventDefault(); $(this).tab("show"); }); }); /*When clicking on Full hide fail/success boxes */ $('#name').focus(function() { $('#success').html(''); }); <?php require("../lib/phpmailer/PHPMailerAutoload.php"); if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $m = new PHPMailer(); $m->IsSMTP(); $m->SMTPAuth = true; $m->SMTPDebug = 2; $m->Host = "smtp-mail.outlook.com"; $m->Username = ""; $m->Password = ""; $m->SMTPSecure = 'tls'; $m->Port = 587; $m->addAddress('EXAMPLE@outlook.com', $name); $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; $m->Subject = "Contact Form has been submitted"; $m->Body = "You have received a new message. <br><br>". " Here are the details:<br> Name: $name <br> Phone Number: $phone <br>". "Email: $email_address<br> Message <br> $message"; if(!$m->Send()) { echo "Mailer Error: " . $m->ErrorInfo; exit; } ?>
  12. Hi everyone! I'm creating a blog for someone here: http://test4.neshayasmin.com/ I've used this theme as my foundation, but I'm making changes to its appearance: http://themeforest.net/item/novelty-retina-ready-responsive-wordpress-theme/4367335 I want to change the appearance of the older/newer buttons at the bottom. At the moment each page is numbered at the bottom of the blog, but I want to have an 'older posts' and a 'newer posts' link instead. I don't have very good knowledge of php. Any help would be wildly appreciated, friends. Let me know if you need any more info.
  13. Hello... I have a form to get some urls from users. Eg: Web Address, Facebook Address, Twitter Address, Google+ address etc... My problem is how I validate these urls when they submit the form. I tried to validate URL in PHP by using the FILTER_VALIDATE_URL or simply, using regular expression. Here, I would like to know what are the best methods to get such a urls from users. Is it always good to let them to enter protocol? sometimes they may not know it is http, https, ftp, ftps.. etc. I think it is something hard to do some users. I tried something like this using FILTER_VALIDATE_URL, But it always use protocol and sometime I am confusing how its work.. // validate url $url = 'http://example.com'; if (filter_var( $url, FILTER_VALIDATE_URL)){ echo "<br>valid"; } else { echo "<br>invalid"; } [b]OUTPUT[/b] : valid // validate url $url = 'http://example.com?id=32&name=kamalani'; if (filter_var( $url, FILTER_VALIDATE_URL)){ echo "<br>valid"; } else { echo "<br>invalid"; } [b]OUTPUT[/b] : valid Can you tell me what are the best ways to get urls from user and how those validate? Any comments are greatly appreciating.. Thank you.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.