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. I have a pdo prepared statement that fetches records from mysql database. The records show up on the page. However if there are no records on a page, I get this error message. "QLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10' at line 4" Here is my statement $getCategoryId = $_GET['id']; $limit = 10; $offset = ($page - 1) * $limit; $statement = $db->prepare("SELECT records.*, categories.* FROM records LEFT JOIN categories ON records.category_id = categories.category_id WHERE records.category_id = :category_id ORDER BY record_id DESC LIMIT {$limit} OFFSET ".$offset); $statement->bindParam('category_id', $getCategoryId); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_ASSOC); If I remove try and catch block, it'll tell me exactly which line is giving the issue. So from the above code, the error has to do with "$statement->execute();". This is where the error occurs. As far as I know, the above pdo statement is correct. Can you tell me if something is wrong with it?
  2. I have created a add-login.php and add-reg.php. I'm trying to figure out why it doesn't say to my table in mysql. Add login below. <!DOCTYPE html> <html> <head> <title>Home Page</title> <style type="text/css"> @import url("templatemo_style.css"); </style> </head> <body> <div id="page"> <div id="logo"> </div> <html> <body> <p align="center"><a href="add-reg.php">Register</a>, or enter your user name and password:</p> <form action="index.html" method="post"> <p align="center"> Username: <input type = "text" name="User"><br> <p align="center"> Password: <input type = "password" name="Pass"><br> <br> </br> <input type="submit" value="Login"/> <input type="reset"> </form> </body> </html> </body> </html> add-reg.php <!DOCTYPE html> <html> <head> <title>Home Page</title> <style type="text/css"> @import url("templatemo_style.css"); </style> </head> <body> <div id="page"> <div id="logo"></div> <?php $host= "localhost"; $user = "root"; $passwd = ""; $database = "test"; $tbl_name = "PASS"; mysql_connect($host, $user, $passwd) or die(mysql_error()); mysql_select_db("test") or die(mysql_error()); //This code runs if the form has been submitted if (isset($_POST['submit'])) { //This makes sure they did not leave any fields blank if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) { die('You did not complete all of the required fields, please go back, and complete the missing fields!'); } // checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM PASS WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { die('Sorry, the username '.$_POST['username'].' is already in use.'); } // this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { die('Your passwords did not match. '); } // here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); } // now we insert it into the database $insert = "INSERT INTO PASS (username, password) VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); ?> <h1>Registered</h1> <p>Thank you very much, you have registered - you may now <a href="add-login.php">login</a>.</p> <?php } else { ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table border="0"> <tr><td colspan=2><h1>Register to access the website.</h1></td></tr> <tr><td>Username:</td><td><br> <input type="text" name="username" maxlength="60"> </td></tr> <tr><td>Password:</td><td><br> <input type="password" name="pass" maxlength="10"> </td></tr> <tr><td>Confirm Password:</td><td><br> <input type="password" name="pass2" maxlength="10"> </td></tr> <tr><th colspan=0><input type="submit" name="submit" value="Register"></th></tr> </table> </form> <?php } ?>
  3. I have the following three links in same page. http://localhost/folder/file.php?x=link1 http://localhost/folder/file.php?x=link2 http://localhost/folder/file.php?x=link3 i want to show URLs as they are... link1 is to include a file named "x.php" link2 is to include a file named "y.php" link3 is to include a file named "z.php" Can it be done in php only? PS: its not about creating hash ids. and i want to do it without any sql db connection.
  4. I still have little knowledge of php, I asked a question earlier but that gave me so as it is now my help please. I'm looking for an easy script that sends the info and send a confirmation. but everyone says something different. Have you a script that I only need to change what data? before hand thanks now use this script but does not work also completely leak, I understood for spammmers <?php error_reporting(E_ALL); $ontvanger = "info@mijnemailadres.nl"; $onderwerp = "Contactformulier"; // Controleren of er een formulier is verzonden if ($_SERVER['REQUEST_METHOD'] == "POST") { // body voor de email opmaken $body = ""; $body .= "Naam: ". $_POST['naam'] ."\n"; $body .= "Telefoon: ". $_POST['telefoon'] ."\n"; $body .= "Email: ". $_POST['email'] ."\n"; $body .= "Onderwerp: ". $_POST['onderwerp'] ."\n"; $body .= "Bericht: ". $_POST['bericht'] ."\n"; $formsent = mail($ontvanger, $onderwerp, $body, "From: <". $_POST['email'] .">"); if ($formsent) { $onderwerp2 = "Bedankt voor uw reactie"; $bericht2 = "Beste ". $_POST['naam'] .",Bedankt voor uw reactie! Ik neem zo spoedig mogelijk contact met u op via uw e-mailadres, Met vriendelijke groet, rene"; // Bevestiging verzenden $formsent = mail($onderwerp2, $bericht2, "From: <'$ontvanger'>"); } } form.php
  5. I want to iterate through each element on an html page and echo each element's name. I thought this should work: $tags = $doc->getElementsByTagName('*'); foreach ($tags as $tag) { echo $tag->tagname; } but I am getting the error: Notice: Undefined property: DOMElement::$tagname in C:\...\ on line 51
  6. All I am trying to do is add a record on a page without the page refreshing. For that ajax is used. Here is the code. It does not add the record to mysql table. Can anyone tell me what I am doing wrong? record.php <!DOCTYPE HTML> <html lang="en"> <head> <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" > $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var name = $("#name").val(); var dataString = 'content='+ textcontent + '&name='+name; if(textcontent=='') { alert("Enter some text.."); $("#content").focus(); } else { $("#flash").show(); $("#flash").fadeIn(400).html('<span class="load">Loading..</span>'); $.ajax({ type: "POST", url: "action.php", data: dataString, cache: true, success: function(html){ $("#show").after(html); document.getElementById('content').value=''; $("#flash").hide(); $("#content").focus(); } }); } return false; }); }); </script> </head> <body> <?php $record_id = $_GET['id']; // getting ID of current page record ?> <form action="" method="post" enctype="multipart/form-data"> <div class="field"> <label for="title">Name *</label> <input type="text" name="name" id="name" value="" maxlength="20" placeholder="Your name"> </div> <div class="field"> <label for="content">content *</label> <textarea id="content" name="content" maxlength="500" placeholder="Details..."></textarea> </div> <input type="submit" name="submit" value="submit" class="submit_button"> </form> <div id="flash"></div> <div id="show"></div> </body> </html> action.php if(isset($_POST['submit'])) { if(empty($_POST['name']) || empty($_POST['content'])) { $error = 'Please fill in the required fields!'; } else { try { $name = trim($_POST['name']); $content = trim($_POST['content']); $stmt = $db->prepare("INSERT INTO records(record_id, name, content) VALUES(:recordid, :name, :content"); $stmt->execute(array( 'recordid' => $record_id, 'name' => $name, 'content' => $content )); if(!$stmt){ $error = 'Please fill in the required fields.'; } else { $success = 'Your post has been submitted.'; } } catch(Exception $e) { die($e->getMessage()); } } }
  7. Hi Little Help Needed I have created a new website In the index.php file i want to show records from database Now, here is how the problem arise I want to import codes from github intead of hosting those files on my server because i want to keep it opensource Below is the code I am using <?php // connect to the database include('connect-db.php'); // get results from database $sql = "SELECT id, upadhi, name FROM munishri"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["upadhi"]. " " . $row["name"]. "<br>"; } } else { echo "0 results"; } // close connection $conn->close(); ?> Can i host the code to show result in another file and use something like <?php // connect to the database include('connect-db.php'); // get results from database include('http://rawgit.com/thehitechpanky/jainmunilocator/master/database.php'); ?>
  8. hi everyone, first time in the forum, english is not my first language so i apologize for the spelling... i manage a website i did some years ago for a car sell place.. in the website i have to upload the new cars and download the ones that have been sold every month... now that takes a lot of time, i have to send them a list and they tell me wich ones add to the list and wich ones remove, for every car i have a litle box with picture and some data, whenyou clik it it sends you to a small page with some more pictures of that car and some more text.. so every time i have to create a new page for every car and put the pictures on it... i would like to have some sort of database with the list of all the active cars that i can get with one clik... then... i would like to have some sort of form where i can drag the pictures and it takes one of them with some of the information and creates the small post of the car and the other biger one with the other pictures and the rest of the info... i dont know if im expressing my self welll any ideas? this is the site: www.laradialautomoviles.com its the first site i ever did about 5 years ago, i never studied webdesign dont have the money to do it... so please dont criticize XD
  9. Hey guys, I am stuck on this preg_match if statement. I want to allow ' and " in the variable string but for some reason it keeps reporting invalid characters when I add ' or " to the string. Any help would be appreciated as I have tried tons of combinations after searching google. Thanks! if(preg_match("/[^a-zA-Z0-9\-\_\,\!\?\.\'\"\ \/]+/i",$_POST['article_title'])) { $err[]='<p class="error" style="color: #ed1c24;">Your Title contains invalid characters!</p>'; }
  10. Hello, Im designing a website and have a contact form, what is the best way of managing that and monitor it as just getting that contact form information sent to an email address they may end up having more and more people sending information will get all messy and will surely cause havoc. The only way at the moment i can think of is to store the first piece of information in a database table then store the reply's in a separate table but linked to the original first question by the id. What do you guys things?
  11. Hello I am looking for a way to log all incoming requests to a nusoap web service to a file.. any suggestions? Thanks
  12. Hello everyone! I am trying to insert a student into a table (with TIMESTAMP; works with VARCHAR, not TIMESTAMP). Can anyone help? Variable $time_stamp = date("D M j G:i:s T Y"); Populate DB Query ("DROP TABLE IF EXISTS enrolled") || !$link->query("CREATE TABLE enrolled(course_id VARCHAR(50), student_id VARCHAR(50), user_ip VARCHAR(50), time_stamp TIMESTAMP(6)) Insert Query INSERT INTO enrolled(course_id,student_id,user_ip,time_stamp) VALUES('$course','$number','$user_ip','$time_stamp')
  13. Hi all, I am using foreach statement to gather records and program levenshtein to detect any misspellings and suggesting the correct words. The thing is i am unable to convert all those strings into a single array. After trying to correct this issue so many times, i wonder if it is really possible to convert strings into a single array? Any input is welcome
  14. Hi, I've got a "data.txt" file with the following content: One1:One2:One3:One4:One5:One6 Two1:Two2:Two3:Two4:Two5:Two6 Three1:Three2:Three3:Three4:Three5:Three6 Now I want to be able to take each data and put on a specific location of a htlm code. Each line for its own. So for the first line, it should look something like this: <html> <head> <title></title> <head> <body> <h1>One2</h1> <h2>One4 some other Text One5</h2> <img src="One6.jpg"> </body> </html> Unforturtunately I don't have a clue how to do that. Can anybody help me out or does someone know a good and easy tutorial? Thanks a lot
  15. I'm looking to order my upload files in a specific order. I believe the default is a random upload order, but I would like to change this based on the file name, which I'm having difficulty with. The file names would be for example; '01 smiley' '02 dog' '03 cat' Currently I used a 'Drag & Drop' multiple file upload although this just uploads in any random order to my database table, I'd like to upload it by numeric order as above. Code so far (upload code works, just the order needs work)... $count = count($_FILES['upload']['name']); $in=0; while($in<$count) { //upload here $in++; } I think I need to sort()? before my while loop, but having difficulty getting this correct. How would I be able to sort each file into a correct order. Many thanks.
  16. I am quite new to php and the mvc setup, I am developing a library app however starting at the very basics so as not to become overwhelmed! I am trying to do a basic insert to my book table, this is the code I have so far alsong with the error I am presented with. Model (models > adminarea_model.php) adminarea_model.php public function create($title_text) { $title_text = strip_tags($title_text); $sql = "INSERT INTO book (title) VALUES (:title)"; $query = $this->db->prepare($sql); $query->execute(array(':title' => $title_text)); $count = $query->rowCount(); if ($count == 1) { return true; } else { $_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED; } return false; } View (views > admin > addBook.php) addBook.php <form method="post" action="<?php echo URL;?>admin/create"> <label>Text of new note: </label><input type="text" name="title" /> <input type="submit" value='Create this note' autocomplete="off" /> </form> Controller (controllers > admin.php) admin.php public function create() { if (isset($_POST['title']) AND !empty($_POST['title'])) { $book_model = $this->loadModel('Admin'); $book_model->create($_POST['title']); } header('location: ' . URL . 'admin/addBook'); } When I am on admin/addBook and I try to submit the form I receive the following error; Fatal error: Call to a member function create() on a non-object in C:\xampp\htdocs\logintest\application\controllers\admin.php on line 43 Any ideas where I am going wrong? Line 43 contains the following $book_model->create($_POST['title']); Thanks J
  17. Hi there, what I have been trying to do is add some additional logic.. My problem is I want to stop displaying the month and day after the year 2000? I know I need to add an if and else statement but this is my first actual project and I am a little stuck.. here is the page, it's a plugin for a timeline http://www.llandoveryheritage.org/project-timeline/ And the file is attached below.. any help would be appreciated. The plugin code was too long to just post in here, didn't want to cause any slow loading issues for people on a slow connection.. Thanks and I appreciate any help. annual_archive.php
  18. I am trying to implement the new version of captcha on my website. What i did so far: Inside the FORM: echo '<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXXXXX"></div>'; Inside PHP: $recaptcha = $_POST['g-recaptcha-response']; if(!empty($recaptcha)) { $google_url = "https://www.google.com/recaptcha/api/siteverify"; $secret = 'YYYYYYYYYYYYYYYYYYYYYYYYYYY'; $ip = $_SERVER['REMOTE_ADDR']; $url = $google_url."?secret=".$secret."&response=".$recaptcha."&remoteip=".$ip; $res = getCurlData($url); $res = json_decode($res, true); if($res['success'] == 'false') { $captcha_error = "Please re-enter your reCAPTCHA."; } } The getCurlData function: function getCurlData($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16"); $curlData = curl_exec($curl); curl_close($curl); return $curlData; } What i want to achieve is to know when the no-Captcha box is checked. I want to throw an error to the user if he/she did not check that box. So far i only throw an error if the response from Google is "We are not sure if you are human, please proceed to our second level of verification" [if($res['success'] == 'false')]. PS: most of the code is written by Srinivas Tamada. You can find it here. Thanks in advance.
  19. Can anyone help by shedding some light with a little problem I encounter using JSON endpoint requests. I'm not very good with PHP. When the endpoint is called and finds no data, I want to replace it with a local image source. In this case, I am calling brewery->logo_url. Most entries have endpoints, but some don't. When an image link is found at the endpoint, it throws off my layout. You can see the ones that look off. They align to the left. I want to replace with a logo default image each time this happens, with hopes to set the layout adjust back to normal. Here's my working document http://graintoglass.com/fb/tap-menu-test.php and here's the JSON. http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short Code Effort <?php $url = 'http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short&servingtype=bottlecan'; $curl_session = curl_init($url); curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 4); curl_setopt($curl_session, CURLOPT_TIMEOUT, 10); $data = curl_exec($curl_session); curl_close($curl_session); $beer_list = json_decode($data); echo '<p class="last-updated">Last Updated: ' . date("m/d/Y") . '</p>'; echo '<h1 class="page-title">Bottle List</h1>'; echo '<p class="page-intro">Not only do we serve a hefty list of brews on tap, we also offer an exclusive list of beers in bottle. Our bottle list is constantly changing so the occasional return visits to browse this list is the best way to stay up to date. Take a look!</p>'; foreach ($beer_list as $beer) { echo '<article class="beer-entry"> <div class="beer-image"><img src="'.$beer->brewery->logo_url.'" /></div> <div class="beer-info"> <p class="brewery-name">'.$beer->brewery->name.' — '.$beer->brewery->origin.'</p> <h2 class="beer-name">'.$beer->beer->name.'</h2> <p class="beer-style">Beer Style: '.$beer->beer->style.'</p> <p class="beer-description">'.$beer->descriptions->short_description.'</p> <p class="beer-abv">ABV: '.$beer->beer->abv.' / IBU: '.$beer->beer->ibu.'</p> <p class="beer-ibu"></p> </div> <div class="clearfix"></div> </article> '; } echo '<p class="page-bottom">If you would like to see more of our food and beer options, <a href="https://www.graintoglass.com" target="_blank">visit our website</a>.</p>'; ?>
  20. Hi guys, does anybody know of any good libraries to handle and validate file uploading including Zipped folders. Also I was needing some tips, so my website developers can come and upload zipped folders, files etc. but eventually would'nt this start taking up a lot of space especially the zipped folders?
  21. I am trying to create a CMS management website, but I can't seem to get the update function to work. Everything else works fine but not the update function. Can anyone please tell me why or what the problem is? I have spent too long trying to fix it and have failed. It is correctly linked to the database when I hit the edit button all i get is UPDATE_CONTENT_FORM($_GET['ID'])?>where the text boxes should be is . Please help, I am really stuck. (sorry about spelling ) code in CMS_Class.php Class modernCMS{ var $host='localhost'; var $username='lmcmanus13'; var $password='k0gl0zfh3g1ccm4v'; var $db='lmcmanus13'; function connect(){ $con = mysql_connect($this->host, $this->username, $this->password); mysql_select_db($this->db,$con); } function get_content($id =''){ if ($id != ""): $id = mysql_real_escape_string($id);//helps to protect database from beening hacked $sql = "SELECT * FROM `CMS_Content` WHERE id ='$id'"; else: $sql = 'SELECT * FROM `CMS_Content` WHERE 1'; endif; //$query = 'SELECT * FROM `CMS_Content` WHERE 1'; $result = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($result)!=0): while($row= mysql_fetch_assoc($result)){ echo '<h1><a href="Animals.php?id=' . $row['id'] . '">' . $row['Title'] . '</h1>'; echo '<p>' . $row['Body'] . '</p>'; } else: echo '<p> we are sorry there seems to be a problem with your request</p>'; endif; echo $return='<p><a href ="Animals.php">Back</a></p>'; } function add_content($_POST){ $Title= mysql_real_escape_string($_POST['Title']); $Body= mysql_real_escape_string($_POST['Body']); if(! $Title || ! $Body): if(!$Title=""): echo"<p>The Title is required<p>"; endif; if(!$Body=""): echo"<p>The Body is required<p>"; echo '<a href="add-content.php">Try Again</a>'; endif; else: $sql="INSERT INTO `CMS_Content`(`id`, `Title`, `Body`) VALUES ('null','$_POST[Title]','$_POST[Body]')"; $result = mysql_query($sql) or die(mysql_error()); echo "<meta http-equiv='refresh' content='0;url=added.php'>"; endif; } function manage_content (){ echo '<div id ="manage">'; $sql = 'SELECT * FROM `CMS_Content`'; $result = mysql_query($sql) or die(mysql_error()); while ($row = mysql_fetch_assoc($result)): echo '<h1><a id=' . $row['id'] . '">' . $row['Title'] . '</h1>' ?> <div> <span ><a href="update-content.php?id=<?php= echo= $row['id']?>">Edit</a>|<a href="?delete=<?php echo $row['id']; ?>">Delete</a></a></span> </div> <?php endwhile; echo '</div>';//closes the manages div } Function delete_content($id){ if(!$id){ return false; }else{ $id=mysql_real_escape_string($id); $sql="DELETE FROM CMS_Content WHERE id='$id'"; $result = mysql_query($sql) or die(mysql_error()); echo "<meta http-equiv='refresh' content='0;url=deleted.php'>"; } function update_content_form($id) { $id = mysql_real_escape_string($id); $sql = "SELECT * FROM CMS_Content WHERE id = '$id'"; $res = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_assoc($res) ?> <form action="Animals.php" method="post" > <input type="hidden" name="update" value="true" /> <input type="hidden" name="id" value="<?php=$row['id']?>" /> <div> <label for="title">Title:</label> <input type="text" name="Title" id="Title" value="<?php=$row['Title']?>" /> </div> <div> <label for="body">Body:</label> <textarea name="body" id="body" rows="8" cols="40"><?php=$row['Body']?></textarea> </div> <input type="submit" name="submit" value="Update content" /> </form> <?php function update_content($p) { $title = mysql_real_escape_string($s['title']); $body = mysql_real_escape_string($s['body']); $id = mysql_real_escape_string($p['id']); if(!$title | !$body): if(!$title): echo "<p>The Title is Required</p>"; endif; if(!$body): echo "<p>The body is Required</p>"; endif; echo '<p><a href=" update_content.php?id=' . $id . '">Try Again</a></p>'; else: $sql = "UPDATE CMS_Content SET title = '$title', body = '$body' WHERE id = '$id'"; $res = mysql_query($sql) or die(mysql_error()); echo "Updated Successfully!"; endif; } } }//end of class } ?> code in Animals.php <h1> Our Animals </h1> <ul> <li><a href="manage-content.php">Manage Content</a></li> <li><a href="add-content.php">Add Content</a></li> </ul> <?php if(isset($_POST['add'])): $obj->add_content($_POST); elseif(isset($_POST['update'])): $obj->update_content_form($_POST); endif; ?> Code in update-content.php <h1> Our Animals j,j</h1> <h1> Update Content </h1> <?=$obj->update_content_form($_GET['id']) ?>
  22. Good morning, I am doing a small project including google charts API but I am having trouble getting my results into the json format that is required. Google's documentation states the json format should be: { "cols": [ {"id":"","label":"Topping","pattern":"","type":"string"}, {"id":"","label":"Slices","pattern":"","type":"number"} ], "rows": [ {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]}, {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]} ] } the query works perfectly fine thats not the problem but getting it into the above format is proving hard than I expected. The below is what I am trying to do to populate the json data in the correct format. function graphdata() { $array['cols'][] = array('type' => 'string'); $array['cols'][] = array('type' => 'string'); $array['cols'][] = array('type' => 'string'); $result = sqlsrv_query($conn, $query); while($row = sqlsrv_fetch_object($result)){ $array['rows'][] = array('c' => array( array('v'=>'$row->DateCreated->format('d-m-Y')'), array('v'=>$row->UnitPrice)) ); } return $array; } print json_encode(graphdata()); I am using MSSQL and not the normal mysql hence the above code, i am a starter when it comes to php so I may be doing something basic totally wrong but I cannot seem to get it to work. Thanks
  23. Hi All! This is my first post here, so if there are some things I miss or something more I need to do please let me know. I tried searching the forum for the answer first but could not find anything. So here is the thing; I followed a tutorial I found about building a login system for my website. The tutorial worked perfectly, except I needed it to redirect to a user specific page instead of a static page on login. I made the necessary changes to the script, and now it redirects to the user specific page, but does not recognize that I am logged in so it will not show me the content. In the interest of full disclosure, I am not very good at PHP and lack a fundamental understanding of it. I am enrolled in some Udemy courses to try to rectify that, but I needed the login system ASAP, so copy and paste programming was my only option. I know, I know. I am a terrible human being and should be thrown into the sun. I agree. I am in counseling to try to deal with it. The tutorial I used can be found here: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL. Here is the relevant code: process_login.php: <?php include_once 'db_connect.php'; include_once 'functions.php'; sec_session_start(); // Our custom secure way of starting a PHP session. if (isset($_POST['email'], $_POST['p'])) { $email = $_POST['email']; $password = $_POST['p']; // The hashed password. $page = login($email, $password, $mysqli); if ($page == true) { // Login success header('Location: '. $page); exit(); } else { // Login failed header('Location: ../error.php?error=1'); } } else { // The correct POST variables were not sent to this page. echo 'Invalid Request'; } functions.php: <?php include_once 'psl-config.php'; function sec_session_start() { $session_name = 'sec_session_id'; // Set a custom session name $secure = SECURE; // This stops JavaScript being able to access the session id. $httponly = true; // Forces sessions to only use cookies. if (ini_set('session.use_only_cookies', 1) === FALSE) { header("Location: ../error.php?err=Could not initiate a safe session (ini_set)"); exit(); } // Gets current cookies params. $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); // Sets the session name to the one set above. session_name($session_name); session_start(); // Start the PHP session session_regenerate_id(); // regenerated the session, delete the old one. } function login($email, $password, $mysqli) { // Using prepared statements means that SQL injection is not possible. if ($stmt = $mysqli->prepare("SELECT id, username, password, salt, page FROM members WHERE email = ? LIMIT 1")) { $stmt->bind_param('s', $email); // Bind "$email" to parameter. $stmt->execute(); // Execute the prepared query. $stmt->store_result(); // get variables from result. $stmt->bind_result($user_id, $username, $db_password, $salt, $page); $stmt->fetch(); // hash the password with the unique salt. $password = hash('sha512', $password . $salt); if ($stmt->num_rows == 1) { // If the user exists we check if the account is locked // from too many login attempts if (checkbrute($user_id, $mysqli) == true) { // Account is locked // Send an email to user saying their account is locked return false; } else { // Check if the password in the database matches // the password the user submitted. if ($db_password == $password) { // Password is correct! // Get the user-agent string of the user. $user_browser = $_SERVER['HTTP_USER_AGENT']; // XSS protection as we might print this value $user_id = preg_replace("/[^0-9]+/", "", $user_id); $_SESSION['user_id'] = $user_id; // XSS protection as we might print this value $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); $_SESSION['username'] = $username; $_SESSION['login_string'] = hash('sha512', $password . $user_browser); // Login successful. return $page; } else { // Password is not correct // We record this attempt in the database $now = time(); $mysqli->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')"); return false; } } } else { // No user exists. return false; } } } function checkbrute($user_id, $mysqli) { // Get timestamp of current time $now = time(); // All login attempts are counted from the past 2 hours. $valid_attempts = $now - (2 * 60 * 60); if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$valid_attempts'")) { $stmt->bind_param('i', $user_id); // Execute the prepared query. $stmt->execute(); $stmt->store_result(); // If there have been more than 5 failed logins if ($stmt->num_rows > 5) { return true; } else { return false; } } } function login_check($mysqli) { // Check if all session variables are set if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) { $user_id = $_SESSION['user_id']; $login_string = $_SESSION['login_string']; $username = $_SESSION['username']; // Get the user-agent string of the user. $user_browser = $_SERVER['HTTP_USER_AGENT']; if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) { // Bind "$user_id" to parameter. $stmt->bind_param('i', $user_id); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($password); $stmt->fetch(); $login_check = hash('sha512', $password . $user_browser); if ($login_check == $login_string) { // Logged In!!!! return true; } else { // Not logged in return false; } } else { // Not logged in return false; } } else { // Not logged in return false; } } else { // Not logged in return false; } } function esc_url($url) { if ('' == $url) { return $url; } $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url); $strip = array('%0d', '%0a', '%0D', '%0A'); $url = (string) $url; $count = 1; while ($count) { $url = str_replace($strip, '', $url, $count); } $url = str_replace(';//', '://', $url); $url = htmlentities($url); $url = str_replace('&', '&', $url); $url = str_replace("'", ''', $url); if ($url[0] !== '/') { // We're only interested in relative links from $_SERVER['PHP_SELF'] return ''; } else { return $url; } }
  24. Hi guys so for my website I want to add a feature where a user can upload a zipped folder and send that folder to another user through my Private message system, so I am wondering how this would work, would I need to upload the folder to my database, upload it to a separate folder and use some php code to display a download link to download it?
  25. Is it a good practice to store error and success messages in SESSION? Folder pages/giftCards ->index.php ->viewGiftCardCodes.php ->redeemGiftCard.php ->giftCards.php index.php <?php if(defined('script') === FALSE){ exit('Hacking attempt...'); } if(loginCheck($userInfo) === FALSE){ redirect('index.php?do=login&returnUrl='.$_SERVER['REQUEST_URI'], FALSE, TRUE); } if($configs['giftCardEnabled'] == 'no'){ alert('This page is currently disabled.', 'index.php?do=home'); } $action = isset($_GET['action']) ? $_GET['action'] : ''; switch($action){ case 'redeemGiftCard'; include 'pages/giftCards/redeemGiftCard.php'; break; case 'viewGiftCardCodes'; include 'pages/giftCards/viewGiftCardCodes.php'; break; default: include 'pages/giftCards/giftCards.php'; break; } ?> Default action giftCards REDEEM BUTTON ................. <?php $action = '<input type="button" value="Redeem" onclick="location.href=\'index.php?do=giftCards&action=redeemGiftCard&id='.$row['id'].'&currency='.$row['currency'].'&amount='.$row['amount'].'&csrfKey='.$csrf->csrfKey().'&csrfToken='.$csrf->csrfToken().'\'">'; ?> ................. Action redeemGiftCard ................. If success <?php $_SESSION['message']['1'] = 'You have successfully redeemed a gift card worth '.$row['currency'].$row['amount'].''; redirect('index.php?do=testPage1', FALSE, TRUE);// Page, Refresh, Exit // ?> If error <?php $_SESSION['message']['2'] = 'Database error. Please try again later!'; redirect('index.php?do=testPage1', FALSE, TRUE);// Page, Refresh, Exit // ?> ................. Default action giftCards ................. <?php if(!empty($_SESSION['message']['1'])){ $success = $_SESSION['message']['1']; unset($_SESSION['message']); } if(!empty($_SESSION['message']['2'])){ $error = $_SESSION['message']['2']; unset($_SESSION['message']); } if(!empty($success)){ print success($success);// HTML and success var // } if(!empty($error)){ print error($error);// HTML and error var // } ?> .................
×
×
  • 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.