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. Hi guys, I am trying to handle a html form that users are copying and pasting to a form on my website that contains their schedule for a particular day. Generally the format is the same so I am trying to handle the data with a preg_match however sometimes white spaces or blank fields do not upload to my mysql db correctly. An example of the html code from the html table is below: <tr class="row-border-top marked-row "> <td>13 Dec 15, Sun</td> // always the same format <td>OFF(Z)</td> // can vary to contain [a-zA-Z], numericals, brackets, forward slash and possible whitespaces (no guarantee of how many if they are present) <td>DOZ</td> // only three letter characters, empty, or white spaces <td>: </td> // generally contains a time in format hh:mm however could be a) blank, b) only contain ':', c) contain just blank spaces <td>: </td> // generally contains a time in format hh:mm however could be a) blank, b) only contain ':', c) contain just blank spaces <td></td> // only three letter characters or blank </tr> <tr class="row-border-top marked-row "> <td>12 Dec 15, Sat</td> // another row example <td>B/HOL(Z)</td> <td>DOZ</td> <td>: </td> <td>: </td> <td></td> </tr> <tr class="marked-row "> // another row example <td>8 Dec 15, Tue</td> <td>3329</td> <td>RZS</td> <td>17:20</td> <td>21:55</td> <td>DOZ</td> </tr> so far I have the code as follows: else { if (preg_match("#([^,]+), \w{3}[\s]+(.+?)[\s]+(\w{3})[\s]+(\d\d:\d\d) Z[\s]+(\d\d:\d\d) Z[\s]+(.*)#", $line, $match)) { $code = $_SESSION['Code']; $date = date('d/m/Y', strtotime($match[1])); $sectordate = date('Y/m/d', strtotime($match[1])); $duty = $match[2]; $dep = $match[3]; $begin = $match[4]; $end = $match[5]; $arr = $match[6]; $output .= "<tr><td>{$date}</td><td>{$duty}</td><td>{$dep}</td><td>{$begin}</td><td>{$end}</td><td>{$arr}</td></tr>\n"; $addedon = date('Y-m-d H:i:s'); $today = date('Y-m-d'); $sql= "INSERT INTO table (RostersID,Code,Ffname,Fuid,SectorDate,Duty,Dep,BeginTime,EndTime,Arr,AddedOn,Random) VALUES('','$code','{$_SESSION['FULLNAME']}','{$_SESSION['FBID']}','$sectordate','$duty','$dep','$begin','$end','$arr','$addedon','$random')"; $result = mysqli_query($cxn,$sql) or die ("Can not upload the new roster!"); $sql = "SELECT * FROM table WHERE Code = '$code' AND Random !='$random'"; $result = mysqli_query($cxn,$sql) or die ("Can not find the old roster duties to delete then update with the new."); while($row=mysqli_fetch_assoc($result)) { $sql1 = "DELETE FROM table WHERE SectorDate='$sectordate' AND Code='$code' AND Random !='$random'"; $result1 = mysqli_query($cxn,$sql1) or die ("Can't execute!"); } } }
  2. Say I have this loop. foreach($record as $row) { <div class="hello">Hello World!</div> } I want to loop through and add a letter alongside the "Hello World!" above. To do that, I found this code. $azRange = range('A', 'Z'); foreach ($azRange as $letter) { print("$letter\n"); } How can I combine the two loops so that I get a result like this? A Hello World! B Hello World! C Hello World! D Hello World! E Hello World! F Hello World!
  3. Sorry to have to ask questions again... but I'm having serious hindrance in regards to an assignment. I have to create a Calculator using PHP (which I have completed - see code below), but I have to do this whilst using a query string to provide two numbers and an operator? Moreover, I have to show the URL - showing the following: yourscript.php?n1=5$n2=7&op=m It then says validate that 'n1' and 'n2' are both numbers and that 'op' contains only allowed values???? If everything validates I have to print the result of the equation? My code has two parts and shows two numbers and an operator and prints like this: 5 + 7 = 12. But... I also have to add http_build_query in my code to show the url? <?php require_once 'big.php'; $number1 = 5; $number2 = 7; $operator = "+"; $calculator = new Calculator(); $calculator->setNumbers($number1, $number2); $calculator->setOperator($operator); $calculator->calculate(); echo $number1." ". $operator." ".$number2." = ". $calculator->getOutput(); <?php class Calculator { private $number1, $number2, $operator, $output; public function setNumbers($number1, $number2) { $this->number1 = $number1; $this->number2 = $number2; } public function setOperator($operator) { $this->operator= $operator; } public function calculate() { if($this->operator == "+") $this->output = $this->number1 + $this->number2; elseif($this->operator == "-") $this->output = $this->number1 - $this->number2; elseif($this->operator == "*") $this->output = $this->number1 * $this->number2; elseif($this->operator == "/") $this->output = $this->number1 / $this->number2; else $this->output = "An Error Has Materialize!"; } public function getOutput() { return $this->output; } }
  4. Hi I got 3 tables Table 1 id room pin creator mxitid time Table 2 id roomid user message time mxitid Table 3 id user mxitid room roomid rank kick unid Each room I create I place the new epoch time of when the room expire in Table 1 time field. But now im trying to create a script to check if my current time is bigger than the time in the Table 1 time field and if it is so it should delete the row in table 1, the rows in table 2 with the same roomid as the id of table 1 and the rows in table 3 with the same roomid as the id of table 1 How can I loop through all the records to delete the expired rooms info using PDO mysql?
  5. I have two questions relating to each other which are regarding - both function __autoload and adding products to a class? Code for an autoload function (please see code #1), the output prints - but also gives an error message? Moreover, I also receive the notification in my php editor "class 'ooo' not found"? If I may ask a silly question I have noticed some autoload fucctions have implode and explode - how would I write one of these? The output and error: My Antonia: Willa Cather (5.99) Fatal error: Class 'ooo' not found in C:\ Code#1: <?php // we've writen this code where we need function __autoload($classname) { $filename = "./". $classname .".php"; include_once($filename); } // we've called a class *** $obj = new ooo(); ?> ------------------------------------------------------------------------------------------------------------------------------ How would I add more products to this product class? code#2: <?php class shopProduct { public $title; protected $producer = []; public $price; public function __construct($title, $producerName1, $producerName2, $price) { $this->title = $title; $this->producer[] = $producerName1; $this->producer[] = $producerName2; $this->price = $price; } public function getProducer() { return implode(' ', $this->producer); } } class ShopProductWriter { public function write ($shopProduct) { $str = "{$shopProduct ->title}: " . $shopProduct -> getProducer() . " ({$shopProduct -> price})\n"; print $str; } } $product1 = new ShopProduct("My Antonia", "Willa", "Cather", 5.99); $writer = new ShopProductWriter(); $writer -> write($product1); ?>
  6. Hi guys, I'm trying to calculate where a future date runs in a 15 day cycle pattern, and then if the day lands on day 13 or 15 of the cycle pattern I want to do something with the result. For example: $pattern = 15; $start_date = strtotime("2015-12-14"); // day 1 // Day 15 = 2015-12-29 $chosen_date = strtotime("2016-03-30"); $difference = ($chosen_date - $start_date) / 83400; // Find which Day the 'chosen_date' comes in the sequence and... If($chosen_date == 13 || $chosen_date == 15) { Echo 'possible outcome. Day $chosen_date."; } Else { Echo 'not possible, day $chosen_date'; } Hope it makes sense! Cheers
  7. hey guys, i am trying to auto generate an email. i have a function that calls for the following use of : <?php $emailSub = 'Test Subject'; $emailTo = 'myemail@gmail.com'; $emailMsg = 'You have a new email that must be read below:<br> '; mail($emailTo,$emailSub,$emailMsg); ?> i dont seem to get any email. any suggestions as to why ?
  8. I have to write small segment of PHP code to print the word(s) 'Hello, World!' in uppercase letters, I have thus far wrote a small section of code that prints the output 'Hello, World!'. But, I'm completely stuck on how to make the letters all uppercase?!?? Moreover; that strtoupper goes somewhere in there right? <?php class TextFunctions { public static $string = 'Hello, World!'; static public function strtoupper() { } } echo TextFunctions::$string; ?>
  9. I have been tasked with attempting to recreate a web app that allows a user to upload a photo and then cut out a specific part of an image that will be saved as a transparent PNG, with the main use being removing backgrounds from an image (i.e. cutting out a face to use as an avatar, etc) I found two online tools that already do this in different ways: 1. Smart Scissors: Quick video shows how you can drop anchor points with your mouse and it will try to auto find the border and "snap to". Pretty slick but doesn't work perfectly when I played with it. And requires a separate "invert" option to handle all scenarios. http://fotoflexer.com/demos.php 2. Clipping Magic: This one is very cool and surprisingly accurate. You basically paint rough green lines over the stuff you want to keep and red lines over the stuff you want to cut out and a live preview lets you see the result. https://clippingmagic.com/tutorials/basics I am not asking for anyone to give me any code whatsoever, just curious, do you think both of these types of things are doable strictly using PHP (using GD and maybe some other custom PHP classes floating around the web)? Are you able to tell what they both use now? Actually looks like Smart Scissors uses Flash, but not sure about Clipping Magic. I ideally would make something more like Clipping Magic. I just don't want to start building in PHP if there are things that some of you smarter people on this site can tell I will never be able to accomplish using solely PHP, even if I was the best PHP developer ever. Any info, direction, advice would be greatly appreciated. Thanks!
  10. Hey guys, i am trying to create a contact form that by passes the page refresh and uses Jquery and Ajax to direct to a php file server side. So far i have everything work fine. until the final part where i pass the json data type into PHP and look to catch an error, success, or completion value. Currently i have an error coming back with the following: SyntaxError: Unexpected token < error due to a parsererror condition I do not see any errors in the console of of chrome, and i have no idea why i am getting this syntax error. These does not seem to be any conflicting data going into the json or out to php. really been stuck on this for a day now This is my .js file $(document).ready(function(){ $('form #alertMessage').hide(); $('#submit').click(function(e){ e.preventDefault(); var valid = ''; var name = $('form #name').val(); var email = $('form #email').val(); var subject = $('form #subject').val(); var message = $('form #message').val(); var honeypot = $('form #honeypot').val(); var humancheck = $('form #humancheck').val(); if(name = '' || name.length <= 5 ){ valid += '<p>Sorry, Your name is required!</p> '; } if(!email.match( /^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/ )){ valid += '<p>A Valid Email is required</p> '; } if(subject = '' || subject.length <= 2 ){ valid += '<p>A Valid name is required</p> '; } if(message = '' || message.length <= 5 ){ valid += '<p>A brief description of you is required.</p> '; } if(honeypot != 'http://'){ valid += '<p>Sorry spambots not allowed.</p> '; } if(humancheck != ''){ valid += '<p>Sorry only humans allowed past this point.</p> '; } if(valid != ""){ $('form #alertMessage').removeClass().addClass('error') .html('<br><br>' + valid).fadeIn('fast') }else{ $('form #alertMessage').removeClass().addClass('processing') .html('<br><br>We are processing your form now...').fadeIn('fast') var formData = $('form').serialize(); submitForm(formData); } }); }); function submitForm(formData){ $.ajax({ type: 'POST', url: 'feedback.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data){ $('form #alertMessage').removeClass().addClass((data.error === true) ? 'error' : 'success' ) .html(data.msg).fadeIn('fast'); if($('form #alertMessage').hasClass('success')){ setTimeout("$('form $alertMessage').fadeOut('fast')", 5000); } }, error: function(XMLHttpRequest, testStatus, errorThrown){ $('form #alertMessage').removeClass().addClass('error') .html(' <p>There was an ' + errorThrown + ' error due to a ' + testStatus + ' condition.</p>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status){ $('form')[0].reset(); } }); }; Here is the php script. <? sleep(3); $name = trim($_POST['name']); $name = trim($_POST['email']); $name = trim($_POST['subject']); $name = trim($_POST['message']); $name = $_POST['honeypot']; $name = $_POST['humancheck']; if ($honeypot == 'http://' && empty($humancheck)){ $errorMsg = ''; $reg_exp = "/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$/ "; if(!preg_match($reg_exp, $email)){ $errorMsg .= "<p>A valid email is required</p>"; } if(empty($name)]){ $errorMsg .= '<p>Please provide your name</p>'; } if(empty($message)]){ $errorMsg .= '<p>Please provide a message</p>'; } if(!empty($errorMsg)){ $return['error'] = true; $return['msg'] = 'Sorry the request was successful but your form was not correctly filled.' . $errorMsg; echo json_encode($return); exit(); }else{ $return['error'] = false; $return['msg'] = 'Thank you for your feedback ' .$name . ' ' . $errorMsg; echo json_encode($return); } } else { $return['error'] = true; $return['msg'] = 'Oops...there was a problem with your submission. Please try again' ; echo json_encode($return); } ?> HTML side. <form id="contact_us" class="contact-form" action="feedback.php" enctype="multipart/form-data" method="post"> <div id="alertMessage"> </div> <div class="row"> <div class="col-md-6"> <input type="text" name='name' class="form-control" id="name" placeholder="Full Name"> <input type="email" name='email' class="form-control" id="email" placeholder="Your Email"> <input type="text" name='subject' class="form-control" id="subject" placeholder="Company or Project name"> </div> <div class="col-md-6"> <textarea class="form-control" name="text" id="message" rows="25" cols="10" placeholder=" Brief Description"></textarea> <input id='submit' name='submit' type="submit" class="btn btn-default submit-btn form_submit"> </div> <input type="hidden" name="honeypot" id="honeypot" value="http://" /> <input type="hidden" name="humancheck" id="humancheck" value="" /> </div> </form> Image of the error output
  11. Hi Guys I've across an issue With my project im working on and I cannot solve it When accessing my reports page I get this: Warning: Cannot modify header information - headers already sent by (output started at /var/www/virtual/crmtech.co.uk/minicrm/htdocs/header.php:104) in I have eliminated the issues down to my javascript scripts in the header :| but I just cannot work out why it would be causing the issue. here is the header.php <?php require ('secure/session.php'); require ('Functions/functions.php'); error_reporting(E_ALL); ini_set('display_errors', 1); ?> <!DOCTYPE html> <html> <head> <!--favicon--> <link rel="icon" href="<?php echo url();?>Images/favicon.ico" type="image/x-icon" /> <!--Style Sheets--> <link rel="stylesheet" type="text/css" href="<?php echo url();?>bootstrap/css/style.css"> <link rel="stylesheet" type="text/css" href="<?php echo url();?>bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?php echo url();?>bootstrap/css/custom.css"> <!--Script Links--> <script src="<?php echo url();?>bootstrap/js/jquery/jquery.js"></script> <script src="<?php echo url();?>bootstrap/js/bootstrap.min.js"></script> <script src="<?php echo url();?>bootstrap/js/typeahead/typeahead.js"></script> <script src="<?php echo url();?>bootstrap/js/bootstrap-datepicker/bootstrap-datepicker.js"></script> <!-- For Displaying Modals--> <script type="text/javascript"> $(".btn-group").find(':input:checked').parent('.btn').addClass('active'); </script> <!--This is the datepicker --> <script type="text/javascript"> $('.datepicker').datepicker({ format: 'mm/dd/yyyy', startDate: '-3d' }) </script> <!--lets use the better to typeahead for search forms --> <script type="text/javascript"> $(function (){ $("#typeaheadCust").typeahead({ source: function(customer, process) { $.ajax({ url: '<?php echo url();?>Functions/Getter.php', type: 'POST', data: 'customer=' + customer, dataType: 'JSON', async: true, success: function(data) { process(data); } }); } }); }); </script> and here is the my reporting/main.php page <?php //this is going to be the main section for reporting include('../header.php'); //lets check the user is authorised to be here! if ($userLevel > 3){ echo "you are authorised to be here!"; } else { echo "you are not allowed here naughty!"; //sleep(10); echo "lets send you here ". SERVER_PATH; header('Location: ../index.php'); } ?> here is the page result, sorry i had to delete the server path Any help would be massively appreciated Thanks!
  12. Hi, I'm recalling information from my database to show all the birthdays of the specific day but today the 30th of November 2015 I get a list of everyone who is stored in my database showing as if its their birthday. Somewhere I made a mistake my database field is DateTime $querybd = "SELECT Username, pdob FROM Users2"; $resultbd = mysql_query($querybd) or die(mysql_error()); $users = array(); while($rowbd = mysql_fetch_array($resultbd)){ if (date('m-d', strtotime($rowbd['pdob'])) == date('m-d')) $users[] = $rowbd['Username']; } $list = implode('; ', $users); if($list == ""){}else{ echo "<br><b>Todays Birthdays: </b>" . $list . "<br>"; } It worked fine till today
  13. Hello I Googled Responsive vs Adaptive design , and almost all results recommend using Responsive design and say that Adaptive design has a lots Cons. But... I noticed that famous websites like Google, Facebook, Yahoo, Youtube and many more use Adaptive Design, so I'm wandering Why they use Adaptive design if the majority say that responsive is better ? Thanks !
  14. I am trying out a new script that lets me resize an image before uploading. It is based on this script. http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html Basically what happens is, it resizes and makes 3 thumbnails and puts them in their relative folder. That works. The part that's giving me the problem is when inserting it into the database. Error says the "image_path" cannot be null. Since it's creating an array of 3 different thumbnails, should I create 2 more fields in the database tabel to account for that? If so, how would I insert the 3 different thumbnail paths into the query? What would it look like? Below is my code. <?php $db_userid = intval($row['user_id']); $get_item_id = intval($row['item_id']); // settings $max_file_size = 5242880; // 5mb $valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // thumbnail sizes $sizes = array(100 => 100, 150 => 150, 250 => 250); // dir paths $target_dir = 'images/'.$db_userid.'/items/'.$get_item_id.'/'; if ($_SERVER['REQUEST_METHOD'] == 'POST' AND isset($_FILES['image'])) { if(!empty($_FILES['image']['name'])) { if($_FILES['image']['size'] < $max_file_size ){ // get file extension $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); if(in_array($ext, $valid_exts)) { function resize($width, $height){ global $db_userid; global $get_item_id; /* Get original image x y*/ list($w, $h) = getimagesize($_FILES['image']['tmp_name']); /* calculate new image size with ratio */ $ratio = max($width/$w, $height/$h); $h = ceil($height / $ratio); $x = ($w - $width / $ratio) / 2; $w = ceil($width / $ratio); /* new file name */ $path = 'images/'.$db_userid.'/items/'.$get_item_id.'/'.$width.'x'.$height.'_'.$_FILES['image']['name']; /* read binary data from image file */ $imgString = file_get_contents($_FILES['image']['tmp_name']); /* create image from string */ $image = imagecreatefromstring($imgString); $tmp = imagecreatetruecolor($width, $height); imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h); /* Save image */ switch ($_FILES['image']['type']) { case 'image/jpeg': imagejpeg($tmp, $path, 100); break; case 'image/png': imagepng($tmp, $path, 0); break; case 'image/gif': imagegif($tmp, $path); break; default: exit; break; } return $path; /* cleanup memory */ imagedestroy($image); imagedestroy($tmp); } /* resize image */ foreach($sizes as $w => $h) { if(!is_dir($target_dir)){ mkdir($target_dir, 0775, true); } $files[] = resize($w, $h); } $insert_image = $db->prepare("INSERT INTO images(user_id, item_id, image_path, date_added) VALUES(:user_id, :item_id, :image_path, :date_added)"); $insert_image->bindParam(':user_id', $db_userid); $insert_image->bindParam(':item_id', $get_item_id); $insert_image->bindParam(':image_path', $path); $insert_image->bindParam(':date_added', $item_date_added); if(!$insert_image->execute()) { $errors[] = 'There was a problem uploading the image!'; } else { if(empty($errors)) { $db->commit(); $success = 'Your item has been saved.'; } else { $db->rollBack(); } } } else { $errors[] = 'Unsupported file'; } } else{ $errors[] = 'Please upload image smaller than 5mb'; } } else { $errors[] = 'An image is required!'; } }
  15. I do have 3 mysql tables "users", "banks", and "user_bank". Every users must have at least one bank and maximum is two. When users signup to system I need to insert bank details to `user_bank` table also. This is how I tried it: $success=FALSE; if($success == FALSE) { $query = "INSERT INTO user_bank ( beneficiary_id , beneficiary_bank_id , branch_id ) VALUES (?, ?, ?)"; $stmt = $mysqli->prepare($query); $stmt->bind_param('iii', $lastInsertId , $bank_one , $branchId_one ); $stmt->execute(); if ($stmt->affected_rows == 1) { $success=TRUE; if(!empty($bank_two) && !empty($branchId_two)) { $query = "INSERT INTO user_bank ( id , bank_id , branch_id ) VALUES (?, ?, ?)"; $stmt = $mysqli->prepare($query); $stmt->bind_param('iii', $lastInsertId , $bank_two , $branchId_two ); $stmt->execute(); $success=TRUE; } } } if ($success == TRUE) { $messages = array('success'=>true, 'message'=>'You successfully registered.'); } My question is, can anybody tell me I there a way to use a single query for this? If so how its doing? Thank you.
  16. Hi Everyone So I've been recently working on a script which will store login IP's and ban them on failed attempts Although I have a little problem, for some reason it doesnt redirect to the banned page when they should be, unless there is a successful login or if they come off of the login page so they can keep bruteforcing as much as they like all the time they stay on that page. Have i got something wrong? please bear in mind I haven't put in place when login successful remove the warnings count. here is the login.php <!DOCTYPE html> <?php require ('../Functions/functions.php'); require('../database/pdo_connection.php'); //first lets get the IP that logged in $login_ip = $_SERVER['REMOTE_ADDR']; securityBanCheck($login_ip); if (isset($_POST['Login'])) { //Set session timeout to 2 weeks session_set_cookie_params(1*7*24*60*60); session_start(); $error=''; // Currently A Blank Error Message $username=$_POST['userName']; //Grab the hash $selectPasswordHash = "SELECT username,secret FROM MC_users WHERE email=email=:username OR username=:username"; $hashresult= $pdo->prepare($selectPasswordHash); $hashresult->bindParam(':username', $username); $hashresult->execute(); $row = $hashresult->fetch(PDO::FETCH_ASSOC); $hash = $row['secret']; //got the hash //lets verify it if (password_verify($_POST['password'],$hash) === true){ //login correct $login_user = $row['username']; //Set the Session $_SESSION['login_user']=$login_user; // Redirect to dashboard.php header ("Location: ../dashboard.php"); } else { $error = 'Username or Password in invalid'; $error2 = 'Try Logging in with your email instead'; //Bruteforce Detection //lets check if there is already warnings $checkWarnings = "SELECT Warning_count FROM MC_login_security WHERE Warning_count > 0 AND Login_IP=:loginIP ORDER BY Timestamp DESC"; $warningsResult = $pdo->prepare($checkWarnings); $warningsResult->bindParam(':loginIP',$login_ip); $warningsResult->execute(); $warningAmount = 1; $banTime = 0; if ($warningsResult->rowCount() > 0){ $warningRow = $warningsResult->fetch(PDO::FETCH_ASSOC); $warningRowCount = $warningRow['Warning_count']; $warningAmount = $warningRowCount + 1; securityBanCheck($login_ip); } //Lets log this in the DB $insertWarning = "INSERT INTO MC_login_security (Login_user_name,Login_IP,Warning_count,timestamp) VALUES (:loginUser,:Login_ip,:warningAmount,:dateToday)"; $insertResult = $pdo->prepare($insertWarning); $insertResult->execute(array(':loginUser'=>$username, ':Login_ip'=>$login_ip, ':warningAmount'=>$warningAmount, ':dateToday'=>date('Y-m-d H:i:s'))); } } //Lastly if the user is logged in, point them back to the Dashboard if(isset($_SESSION['login_user'])){ header("location: ../dashboard.php");} ?> the security check function which is called at the start of the login page AND if the password is entered incorrectly function securityBanCheck($login_ip){ //call the url function for redirects url(); $todaysDate = date('Y-m-d H:i:s'); require (PHP_PATH .'/database/pdo_connection.php'); $checkBan = "SELECT Warning_count,Timestamp,Ban_time FROM MC_login_security WHERE Warning_count > 4 AND Login_IP=:loginIP ORDER BY Timestamp DESC"; $checkResult = $pdo->prepare($checkBan); $checkResult->bindParam(':loginIP',$login_ip); $checkResult->execute(); if ($checkResult->rowCount() > 0){ $banRow = $checkResult->fetch(PDO::FETCH_ASSOC); $warningCount = $banRow['Warning_count']; $timeStamp = $banRow['Timestamp']; $bantime = $banRow['Ban_time']; echo "did we get here?"; //if theyre banned direct them to the banned page and stop this script from going any further if ($bantime > $todaysDate){ header('Location: '. SERVER_PATH .'banned.php'); die(); } //if theyre currently not banned check their warnings and if needed add a ban. if ($warningCount == 4){ $bantime = date('Y-m-d H:i:s', strtotime($timeStamp . '+1 hour')); echo $bantime; }elseif ($warningCount == 9){ $bantime = date('Y-m-d H:i:s', strtotime($timeStamp . '+1 day')); }elseif ($warningCount == 14){ $bantime = date('Y-m-d H:i:s', strtotime($timeStamp . '+1 month')); } //ultimately if we got to this stage we would be adding a ban $insertBanTime = "UPDATE MC_login_security SET Ban_time = :banTime WHERE Login_IP = :loginIP ORDER BY Timestamp DESC"; $banResult = $pdo->prepare($insertBanTime); $banResult->execute(array(':banTime'=>$bantime, ':loginIP'=>$login_ip));; } } Any help given is greatly appreciated and i thank everyone in advance for all the support I get form this amazing forum. thanks Mooseh
  17. Hi guys, I am trying to make a quick code to find a route between two Place A and Place Z on 2015-11-23 that starts to leave after 6am. Example table rows: DATE DEPARTURE LEAVE ARRIVE ARRIVAL 2015-11-23 Place A 04:00 Place Z 06:00 (this direct route leaves too early.) 2015-11-23 Place U 13:30 Place Z 14:20 2015-11-23 Place A 07:00 Place T 08:00 2015-11-23 Place A 09:00 Place U 12:00 2015-11-23 Place T 09:00 Place B 12:00 2015-11-23 Place B 13:00 Place Z 15:00 The output will show all routes available such as: OPTION 1: Place A to Place U (09:00-12:00) **01:30 wait** Place U to Place Z (13:30-14:20) OPTION 2: Place A to Place T (07:00-08:00) **01:00 wait** Place T to Place B (09:00-12:00) **00:45 wait** Place B to Place Z (12:45-15:00) Thanks for the help
  18. links in header looks like.. <link rel="icon" href="images/favicon.ico"> <link rel="shortcut icon" href="images/favicon.ico" /> <link rel="stylesheet" href="css/style.css"> <script src="js/jquery.js"></script> <script src="js/jquery-migrate-1.1.1.js"></script> <script src="js/jquery.easing.1.3.js"></script> <script src="js/script.js"></script> <script src="js/superfish.js"></script> <script src="js/jquery.equalheights.js"></script> <script src="js/jquery.mobilemenu.js"></script> <script src="js/tmStickUp.js"></script> <script src="js/jquery.ui.totop.js"></script> <script src="js/validjs.js"></script> <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <link rel="stylesheet" href="css/homestyle.css"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link href="css/side-slider.css" rel="stylesheet" type="text/css" media="screen"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="js/jquery.side-slider.js"></script> if i comment the below jq library.. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> then my stuck-container works on scroll down the page.. but my "username checker" plugin does not work.. and... VICE-VERSA... Please help me to get out of this prob...
  19. Hi Im creating a countdown timer to show a result but I only want to show the result for x time then I want it to disappear, but seems like Somewhere I'm going wrong with my if functions any help... <html> <?php define('TIMEZONE', 'Africa/Harare'); date_default_timezone_set(TIMEZONE); $targetDate = new DateTime('2015-11-24 11:57:00'); $runningDate = new DateTime('2015-11-24 12:08:00'); $time = new DateTime(); $remaining = $targetDate->diff(new DateTime()); // not done if( $time < $targetDate ) { echo $remaining->format('%a D - %H:%I:%S'); //--> 86 D - 19:44:24 } // done elseif($targetDate < $runningDate ) { print "The time has been reached show this messagt till runningdate is reached"; } elseif($time > $runningDate ) { print ""; }else{ print ""; } ?> </html>
  20. Hi guys, I have this code here http://pastebin.com/WK36Jx0G It works as it should for the first loop but for each re-loop though I get the output 'Array' echoing from line 41's output. Example shown below.. From: MAN STR DUB 12:15 - 20:05 From: MANArray DUB SNN 17:30 - 23:15 Anyone understand why? Thanks
  21. Hi there, I have an issue that drives me nuts for some days now. I used php.ini to store the sessions to a folder outside root directory: session.save_path = "/home/castos/SESSIONS" As long as the file i call is in the public_html directory (root), session data are OK. If for any reason i use AJAX to call data from a sub-directory (lets say public_html/ajax/test.php), then SESSION data are no longer there (but the session_id is still the same). If i move the same file inside root (public_html/test.php) and call it using AJAX then it works just fine. I feel that the problem could be inside the configuration of the SESSION in php.ini so i am posting the rest of the session configuration: session.save_handler = files session.use_cookies = 1 session.use_only_cookies = 1 session.name = CUSTSESSID session.cookie_httponly = 1 session.cookie_secure = 1 session.hash_function = sha512 session.hash_bits_per_character = 5 session.auto_start = 0 session.cookie_lifetime = 0 session.cookie_path = "/" session.cookie_domain = session.serialize_handler = php session.gc_probability = 1 session.gc_divisor = 100 session.gc_maxlifetime = 1440; session.referer_check = session.entropy_length = 256 session.entropy_file = "/dev/urandom" session.cache_limiter = nocache session.cache_expire = 180 session.use_trans_sid = 0 Any help will be much appreciated! Thanks!
  22. I am using a simple image upload. http://www.w3schools.com/php/php_file_upload.asp It gives me 2 errors like this. Warning: move_uploaded_file(C:/xampp/htdocs/home/upload/images/grandpix 2.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\home\upload\post.php on line 174 Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpF915.tmp' to 'C:/xampp/htdocs/home/upload/images/grandpix 2.jpg' in C:\xampp\htdocs\home\upload\post.php on line 174 This is my code. Post.php . I see that it's the "$target_dir" issue. How can I fix it? if(isset($_FILES['fileToUpload'])){ if(!empty($_FILES['fileToUpload']['name'])) { $target_dir = $_SERVER['DOCUMENT_ROOT'].'/home/upload/images/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { $errors[] = 'File is not an image.'; $uploadOk = 0; } // Check if file already exists if (file_exists($target_file)) { $errors[] = 'Sorry, file already exists.'; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { $errors[] = 'Sorry, your file is too large.'; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.'; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $errors[] = '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 { $errors[] = 'Sorry, there was an error uploading your file.'; } } $insert_image = $db->prepare("INSERT INTO images(user_id, item_id, image_path, date_added) VALUES(:user_id, :item_id, :image_path, :date_added)"); $insert_image->bindParam(':user_id', $userid); $insert_image->bindParam(':item_id', $item_id); $insert_image->bindParam(':image_path', $target_file); $insert_image->bindParam(':date_added', $date_added); if(!$insert_image->execute()) { $errors[] = 'There was a problem uploading the image!'; } else { if(empty($errors)) { $db->commit(); $success = 'Your post has been saved.'; } else { $db->rollBack(); } } } else { $errors[] = 'An image is required!'; } }
  23. Hello Guys, I have an interesting issue in Magento. After a site backup and transfer onto a new domain the front-end of my website loads fine, however when I try to navigate to: domain.com/index.php/admin I get a white page. I have enabled debugging mode and it displays this error: 1 Array ( [type] => 64 [message] => Cannot redeclare class Mage_Admin_Model_Session [file] => /var/www/vhosts/domain.co.uk/sub-domain.co.uk/includes/src/__adminhtml.php [line] => 504 ) Since finding this new error, I've tried to comment/remove every class that it cannot redeclare in the __adminhtml.php file, one by one.. Only to find that by the time I've commented them all out and refreshed the admin page, it gives no error whatsoever. Just a white page. Any ideas? Any help is much appreciated.
  24. Hello How can I create a user friendly timezone select menu using PHP, like the one in General account setting of PHPFreaks. thanks !
  25. I am trying out a new script for image upload and resize using ajax method. All the ones I've found so far process the php file through the form action="". Since I am inserting other data into the database and calling the other php code directly on the same page as a the html form, I would like to know if there is another way I can run that specific image upload php code through ajax. This is one the scripts I have looked at . http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php This is what their html form looks like. <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"> <input name="image_file" id="imageInput" type="file" /> <input type="submit" id="submit-btn" value="Upload" /> <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/> </form> <div id="output"></div> I would like to process the "processupload.php" above through the ajax code below and leave the form action="" empty, as I am running other php code on the same page to insert other data as well. How would you do that? <script> $(document).ready(function() { var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforeSubmit, // pre-submit callback success: afterSuccess, // post-submit callback resetForm: true // reset the form after successful submit }; $('#MyUploadForm').submit(function() { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); }); function afterSuccess() { $('#submit-btn').show(); //hide submit button $('#loading-img').hide(); //hide submit button } //function to check file size before uploading. function beforeSubmit(){ //check whether browser fully supports all File API if (window.File && window.FileReader && window.FileList && window.Blob) { if( !$('#imageInput').val()) //check empty input filed { $("#output").html("Are you kidding me?"); return false } var fsize = $('#imageInput')[0].files[0].size; //get file size var ftype = $('#imageInput')[0].files[0].type; // get file type //allow only valid image file types switch(ftype) { case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': break; default: $("#output").html("<b>"+ftype+"</b> Unsupported file type!"); return false } //Allowed file size is less than 1 MB (1048576) if(fsize>1048576) { $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor."); return false } $('#submit-btn').hide(); //hide submit button $('#loading-img').show(); //hide submit button $("#output").html(""); } else { //Output error to older browsers that do not support HTML5 File API $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!"); return false; } } //function to format bites bit.ly/19yoIPO function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return '0 Bytes'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; } </script>
×
×
  • 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.