Search Results

Search found 106 results on 5 pages for 'htmlspecialchars'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • highlighting search results in php/mysql

    - by fusion
    how do i highlight search results from mysql query using php? this is my code: $search_result = ""; $search_result = $_GET["q"]; $result = mysql_query('SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE "%' . $search_result .'%" ORDER BY idQuotes DESC', $conn) or die ('Error: '.mysql_error()); function h($s) { echo htmlspecialchars($s, ENT_QUOTES); } ?> <div class="center_div"> <table> <caption>Search Results</caption> <?php while ($row= mysql_fetch_array($result)) { ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']) ?></td> <td style="font-size:16px;"><?php h($row['cQuotes']) ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']) ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']) ?></td> </tr> <?php } ?> </table> </div>

    Read the article

  • uploading image & getting back from database

    - by Anup Prakash
    Putting a set of code which is pushing image to database and fetching back from database: <!-- <?php error_reporting(0); // Connect to database $errmsg = ""; if (! @mysql_connect("localhost","root","")) { $errmsg = "Cannot connect to database"; } @mysql_select_db("test"); $q = <<<CREATE create table image ( pid int primary key not null auto_increment, title text, imgdata longblob, friend text) CREATE; @mysql_query($q); // Insert any new image into database if (isset($_POST['submit'])) { move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img"); $instr = fopen("latest.img","rb"); $image = addslashes(fread($instr,filesize("latest.img"))); if (strlen($instr) < 149000) { $image_query="insert into image (title, imgdata,friend) values (\"". $_REQUEST['title']. "\", \"". $image. "\",'".$_REQUEST['friend']."')"; mysql_query ($image_query) or die("query error"); } else { $errmsg = "Too large!"; } $resultbytes=''; // Find out about latest image $query = "select * from image where pid=1"; $result = @mysql_query("$query"); $resultrow = @mysql_fetch_assoc($result); $gotten = @mysql_query("select * from image order by pid desc limit 1"); if ($row = @mysql_fetch_assoc($gotten)) { $title = htmlspecialchars($row[title]); $bytes = $row[imgdata]; $resultbytes = $row[imgdata]; $friend=$row[friend]; } else { $errmsg = "There is no image in the database yet"; $title = "no database image available"; // Put up a picture of our training centre $instr = fopen("../wellimg/ctco.jpg","rb"); $bytes = fread($instr,filesize("../wellimg/ctco.jpg")); } if ($resultbytes!='') { echo $resultbytes; } } ?> <html> <head> <title>Upload an image to a database</title> </head> <body bgcolor="#FFFF66"> <form enctype="multipart/form-data" name="file_upload" method="post"> <center> <div id="image" align="center"> <h2>Heres the latest picture</h2> <font color=red><?php echo $errmsg; ?></font> <b><?php echo $title ?></center> </div> <hr> <h2>Please upload a new picture and title</h2> <table align="center"> <tr> <td>Select image to upload: </td> <td><input type="file" name="imagefile"></td> </tr> <tr> <td>Enter the title for picture: </td> <td><input type="text" name="title"></td> </tr> <tr> <td>Enter your friend's name:</td> <td><input type="text" name="friend"></td> </tr> <tr> <td><input type="submit" name="submit" value="submit"></td> <td></td> </tr> </table> </form> </body> </html> --> Above set of code has one problem. The problem is whenever i pressing the "submit" button. It is just displaying the image on a page. But it is leaving all the html codes. even any new line message after the // Printing image on browser echo $resultbytes; //************************// So, for this i put this set of code in html tag: This is other sample code: <!-- <?php error_reporting(0); // Connect to database $errmsg = ""; if (! @mysql_connect("localhost","root","")) { $errmsg = "Cannot connect to database"; } @mysql_select_db("test"); $q = <<<CREATE create table image ( pid int primary key not null auto_increment, title text, imgdata longblob, friend text) CREATE; @mysql_query($q); // Insert any new image into database if (isset($_POST['submit'])) { move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img"); $instr = fopen("latest.img","rb"); $image = addslashes(fread($instr,filesize("latest.img"))); if (strlen($instr) < 149000) { $image_query="insert into image (title, imgdata,friend) values (\"". $_REQUEST['title']. "\", \"". $image. "\",'".$_REQUEST['friend']."')"; mysql_query ($image_query) or die("query error"); } else { $errmsg = "Too large!"; } $resultbytes=''; // Find out about latest image $query = "select * from image where pid=1"; $result = @mysql_query("$query"); $resultrow = @mysql_fetch_assoc($result); $gotten = @mysql_query("select * from image order by pid desc limit 1"); if ($row = @mysql_fetch_assoc($gotten)) { $title = htmlspecialchars($row[title]); $bytes = $row[imgdata]; $resultbytes = $row[imgdata]; $friend=$row[friend]; } else { $errmsg = "There is no image in the database yet"; $title = "no database image available"; // Put up a picture of our training centre $instr = fopen("../wellimg/ctco.jpg","rb"); $bytes = fread($instr,filesize("../wellimg/ctco.jpg")); } } ?> <html> <head> <title>Upload an image to a database</title> </head> <body bgcolor="#FFFF66"> <form enctype="multipart/form-data" name="file_upload" method="post"> <center> <div id="image" align="center"> <h2>Heres the latest picture</h2> <?php if ($resultbytes!='') { // Printing image on browser echo $resultbytes; } ?> <font color=red><?php echo $errmsg; ?></font> <b><?php echo $title ?></center> </div> <hr> <h2>Please upload a new picture and title</h2> <table align="center"> <tr> <td>Select image to upload: </td> <td><input type="file" name="imagefile"></td> </tr> <tr> <td>Enter the title for picture: </td> <td><input type="text" name="title"></td> </tr> <tr> <td>Enter your friend's name:</td> <td><input type="text" name="friend"></td> </tr> <tr> <td><input type="submit" name="submit" value="submit"></td> <td></td> </tr> </table> </form> </body> </html> --> ** But in this It is showing the image in format of special charaters and digits. 1) So, Please help me to print the image with some HTML code. So that i can print it in my form to display the image. 2) Is there any way to convert the database image into real image, so that i can store it into my hard-disk and call it from tag? Please help me.

    Read the article

  • why limxml2 quotes starting double slash in CDATA with javascript

    - by Vincenzo
    This is my code: <?php $data = <<<EOL <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <script type="text/javascript"> //<![CDATA[ var a = 123; // JS code //]]> </script> </html> EOL; $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = false; $dom->loadXml($data); echo '<pre>' . htmlspecialchars($dom->saveXML()) . '</pre>'; This is result: <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script type="text/javascript"><![CDATA[ //]]><![CDATA[ var a = 123; // JS code //]]><![CDATA[ ]]></script></html> If and when I remove the DOCTYPE notation from XML document, CDATA works properly and leading/trailing double slash is not turned into CDATA. What is the problem here? Bug in libxml2? PHP version is 5.2.13 on Linux. Thanks.

    Read the article

  • I need to sort php jquery gallery script alphabetically

    - by David Cahill
    know nothing about php, but I have this script that reads a folder and displays a thumbnail gallery, problem is it dosent display alphabetically. Have searched the net and seen that sort does this but have no idea where to start any help would be much appreciated. heres the script $sitename = $row_wigsites['id']; $directory = 'sites/'.$sitename.'/pans'; $allowed_types=array('jpg','jpeg','gif','png'); $file_parts=array(); $ext=''; $title=''; $i=0; $dir_handle = @opendir($directory) or die("There is an error with your image directory!"); while ($file = readdir($dir_handle)) { if($file=='.' || $file == '..') continue; $file_parts = explode('.',$file); $ext = strtolower(array_pop($file_parts)); $title = implode('.',$file_parts); $title = htmlspecialchars($title); $nomargin=''; if(in_array($ext,$allowed_types)) { if(($i+1)%4==0) $nomargin='nomargin'; echo ' <div class="pic '.$nomargin.'" style="background:url('.$directory.'/'.$file.') no-repeat 50% 50%;"> <a href="'.$directory.'/'.$file.'" title="Panoramic Stills taken at '.$title.'°" rel="pan1" target="_blank">'.$title.'</a> </div>'; $i++; } } closedir($dir_handle);

    Read the article

  • why libxml2 quotes starting double slash in CDATA with javascript

    - by Vincenzo
    This is my code: <?php $data = <<<EOL <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <script type="text/javascript"> //<![CDATA[ var a = 123; // JS code //]]> </script> </html> EOL; $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = false; $dom->loadXml($data); echo '<pre>' . htmlspecialchars($dom->saveXML()) . '</pre>'; This is result: <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script type="text/javascript"><![CDATA[ //]]><![CDATA[ var a = 123; // JS code //]]><![CDATA[ ]]></script></html> If and when I remove the DOCTYPE notation from XML document, CDATA works properly and leading/trailing double slash is not turned into CDATA. What is the problem here? Bug in libxml2? PHP version is 5.2.13 on Linux. Thanks.

    Read the article

  • Accettend letter and other graphic simbols PHP->JS

    - by Kreker
    I have to read a txt via file php. This file contains some normal so may contains this kind of symbols : € é ò à ° % etc I read the content in php with file_get_contents and transform these for inserenting in SQL database. $contFile = file_get_contents($pathFile); $testoCommento = htmlspecialchars($contFile,ENT_QUOTES); $testoCommento = addslashes($testoCommento); Now if I have this text for example : "l'attesa ?é cruciale fino a quando il topo non viene morso dall'?€" in the database I have this: l&#039;attesa è cruciale fino a quando il topo non veniene morso dall&#039;€ When I was GETTING the data from the database I use the php function for decode html entites $descrizione = htmlspecialchars_decode($risultato['descrizione'],ENT_QUOTES); $descrizione = addslashes($descrizione); Now I use jasvascript and AJAX for getting the table content and display to an HTML page In the browser instead of getting the correct text (€,è) I have square symbol. I think there is some mess with charset code/decode but never figured out. The SQL' table is in "utf8_unicode_ci" format and the column in "utf8_general_ci". The content-type of the page is <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> Thanks for help me!

    Read the article

  • How can I secure my $_GETs in PHP?

    - by ggfan
    My profile.php displays all the user's postings,comments,pictures. If the user wants to delete, it sends the posting's id to the remove.php so it's like remove.php?action=removeposting&posting_id=2. If they want to remove a picture, it's remove.php?action=removepicture&picture_id=1. Using the get data, I do a query to the database to display the info they want to delete and if they want to delete it, they click "yes". So the data is deleted via $POST NOT $GET to prevent cross-site request forgery. My question is how do I make sure the GETs are not some javascript code, sql injection that will mess me up. here is my remove.php //how do I make $action safe? //should I use mysqli_real_escape_string? //use strip_tags()? $action=trim($_GET['action']); if (($action != 'removeposting') && ($action != 'removefriend') && ($action != 'removecomment')) { echo "please don't change the action. go back and refresh"; header("Location: index.php"); exit(); } if ($action == 'removeposting') { //get the info and display it in a form. if user clicks "yes", deletes } if ($action =='removepicture') { //remove pic } I know I can't be 100% safe, but what are some common defenses I can use. EDIT Do this to prevent xss $action=trim($_GET['action']); htmlspecialchars(strip_tags($action)); Then when I am 'recalling' the data back via POST, I would use $posting_id = mysqli_real_escape_string($dbc, trim($_POST['posting_id']));

    Read the article

  • How to write this loop prettier?

    - by Tom
    I've just read this topic http://stackoverflow.com/questions/2930533/highlight-search-keywords-on-hover and actually I use pretty the same structure, but it looks awful. So can you give me an advice, how to write this loop prettier in one php file, I mean php and html at the same time? <table class="result"> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php echo $cQuote; ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?>

    Read the article

  • What are the weaknesses of this user authentication method?

    - by byronh
    I'm developing my own PHP framework. It seems all the security articles I have read use vastly different methods for user authentication than I do so I could use some help in finding security holes. Some information that might be useful before I start. I use mod_rewrite for my MVC url's. Passwords are sha1 and md5 encrypted with 24 character salt unique to each user. mysql_real_escape_string and/or variable typecasting on everything going in, and htmlspecialchars on everything coming out. Step-by step process: Top of every page: session_start(); session_regenerate_id(); If user logs in via login form, generate new random token to put in user's MySQL row. Hash is generated based on user's salt (from when they first registered) and the new token. Store the hash and plaintext username in session variables, and duplicate in cookies if 'Remember me' is checked. On every page, check for cookies. If cookies set, copy their values into session variables. Then compare $_SESSION['name'] and $_SESSION['hash'] against MySQL database. Destroy all cookies and session variables if they don't match so they have to log in again. If login is valid, some of the user's information from the MySQL database is stored in an array for easy access. So far, I've assumed that this array is clean so when limiting user access I refer to user.rank and deny access if it's below what's required for that page. I've tried to test all the common attacks like XSS and CSRF, but maybe I'm just not good enough at hacking my own site! My system seems way too simple for it to actually be secure (the security code is only 100 lines long). What am I missing? I've also spent alot of time searching for the vulnerabilities with mysql_real_escape string but I haven't found any information that is up-to-date (everything is from several years ago at least and has apparently been fixed). All I know is that the problem was something to do with encoding. If that problem still exists today, how can I avoid it? Any help will be much appreciated.

    Read the article

  • highlighting search results in php error

    - by fusion
    i'm trying to figure out what is wrong in this code. it either doesn't highlight the search result OR it outputs html tags surrounding the highlighted text. . $search_result = ""; $search_result = trim($search_result); $special_cases = array( '%', '_', '+' ); $search_result = str_replace( $special_cases, '', $_GET["q"] ); //Check if the string is empty if ($search_result == "") { echo "<p>Search Error</p><p>Please enter a search...</p>" ; exit(); } $result = mysql_query('SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE "%' . mysql_real_escape_string($search_result) .'%" ORDER BY idQuotes DESC', $conn) or die ('Error: '.mysql_error()); //eliminating special characters function h($s) { echo htmlspecialchars($s, ENT_QUOTES); } function highlightWords($string, $word) { $string = str_replace($word, "<span style='background-color: #FFE066;font-weight:bold;'>".$word."</span>", $string); /*** return the highlighted string ***/ return $string; } ?> <div class="caption">Search Results</div> <div class="center_div"> <table> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords($row['cQuotes'], $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php h($cQuote); ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> </div> on the browser, it is outputted as: A good <span style='background-color: #FFE066;font-weight:bold;'>action</span> is an ever-remaining store and a pure yield or if a div is used with class: A good <div class='highlight'>action</div> is an ever-remaining store and a pure yield

    Read the article

  • highlight search keywords on hover

    - by fusion
    i've a basic php search form which highlights the keywords using css. i was wondering if i could make the keywords in the results highlight only when the user hovers over the record. is this possible? this is the highlight code: function highlightWords($text, $words) { preg_match_all('~\w+~', $words, $m); if(!$m) return $text; $re = '~\\b(' . implode('|', $m[0]) . ')~i'; $string = preg_replace($re, '<span class="highlight">$0</span>', $text); return $string; } . . . <table class="result"> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php echo $cQuote; ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> css: table.result tr:hover { background:#F7F7F7; } .highlight { font-weight:bold; color: #DE2842; padding:5px; padding-right:2px; background: #FFFCDB; } i tried changing the color through highlight:hover, but this changed the color of the search keyword only when i hovered over the keyword itself, which is understandable since that's the way it is supposed to work, but i'd like the search keywords to be highlighted when i hover over the result as a whole.

    Read the article

  • Registration form validation not validating

    - by jgray
    I am a noob when it comes to web development. I am trying to validate a registration form and to me it looks right but it will not validate.. This is what i have so far and i am validating through a repository or database. Any help would be greatly appreciated. thanks <?php session_start(); $title = "User Registration"; $keywords = "Name, contact, phone, e-mail, registration"; $description = "user registration becoming a member."; require "partials/_html_header.php"; //require "partials/_header.php"; require "partials/_menu.php"; require "DataRepository.php"; // if all validation passed save user $db = new DataRepository(); // form validation goes here $first_nameErr = $emailErr = $passwordErr = $passwordConfirmErr = ""; $first_name = $last_name = $email = $password = $passwordConfirm = ""; if(isset($_POST['submit'])) { $valid = TRUE; // check if all fields are valid { if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["first_name"])) {$first_nameErr = "Name is required";} else { // $first_name = test_input($_POST["first_name"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) { $first_nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) {$emailErr = "Email is required";} else { // $email = test_input($_POST["email"]); // check if e-mail address syntax is valid if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format"; } } if (!preg_match("/(......)/",$password)) { $passwordErr = "Subject must contain THREE or more characters!"; } if ($_POST['password']!= $_POST['passwordConfirm']) { echo("Oops! Password did not match! Try again. "); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } } } if(!$db->isEmailUnique($_POST['email'])) { $valid = FALSE; //display errors in the correct places } // if still valid save the user if($valid) { $new_user = array( 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'email' => $_POST['email'], 'password' => $_POST['password'] ); $results = $db->saveUser($new_user); if($results == TRUE) { header("Location: login.php"); } else { echo "WTF!"; exit; } } } ?> <head> <style> .error {color: #FF0000;} </style> </head> <h1 class="center"> World Wide Web Creations' User Registration </h1> <p><span class="error"></span><p> <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return validate_form()" > First Name: <input type="text" name="first_name" id="first_name" value="<?php echo $first_name;?>" /> <span class="error"> <?php echo $first_nameErr;?></span> <br /> <br /> Last Name(Optional): <input type="text" name="last_name" id="last_name" value="<?php echo $last_name;?>" /> <br /> <br /> E-mail: <input type="email" name="email" id="email" value="<?php echo $email;?>" /> <span class="error"> <?php echo $emailErr;?></span> <br /> <br /> Password: <input type="password" name="password" id="password" value="" /> <span class="error"> <?php echo $passwordErr;?></span> <br /> <br /> Confirmation Password: <input type="password" name="passwordConfirm" id="passwordConfirm" value="" /> <span class="error"> <?php echo $passwordConfirmErr;?></span> <br /> <br /> <br /> <br /> <input type="submit" name="submit" id="submit" value="Submit Data" /> <input type="reset" name="reset" id="reset" value="Reset Form" /> </form> </body> </html> <?php require "partials/_footer.php"; require "partials/_html_footer.php"; ?> class DataRepository { // version number private $version = "1.0.3"; // turn on and off debugging private static $debug = FALSE; // flag to (re)initialize db on each call private static $initialize_db = FALSE; // insert test data on initialization private static $load_default_data = TRUE; const DATAFILE = "203data.txt"; private $data = NULL; private $errors = array(); private $user_fields = array( 'id' => array('required' => 0), 'created_at' => array('required' => 0), 'updated_at' => array('required' => 0), 'first_name' => array('required' => 1), 'last_name' => array('required' => 0), 'email' => array('required' => 1), 'password' => array('required' => 1), 'level' => array('required' => 0, 'default' => 2), ); private $post_fields = array( 'id' => array('required' => 0), 'created_at' => array('required' => 0), 'updated_at' => array('required' => 0), 'user_id' => array('required' => 1), 'title' => array('required' => 1), 'message' => array('required' => 1), 'private' => array('required' => 0, 'default' => 0), ); private $default_user = array( 'id' => 1, 'created_at' => '2013-01-01 00:00:00', 'updated_at' => '2013-01-01 00:00:00', 'first_name' => 'Admin Joe', 'last_name' => 'Tester', 'email' => '[email protected]', 'password' => 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 'level' => 1, ); private $default_post = array( 'id' => 1, 'created_at' => '2013-01-01 00:00:00', 'updated_at' => '2013-01-01 00:00:00', 'user_id' => 1, 'title' => 'My First Post', 'message' => 'This is the message of the first post.', 'private' => 0, ); // constructor will load existing data into memory // if it does not exist it will create it and initialize if desired public function __construct() { // check if need to reset if(DataRepository::$initialize_db AND file_exists(DataRepository::DATAFILE)) { unlink(DataRepository::DATAFILE); } // if file doesn't exist, create the initial datafile if(!file_exists(DataRepository::DATAFILE)) { $this->log("Data file does not exist. Attempting to create it... (".__FUNCTION__.":".__LINE__.")"); // create initial file $this->data = array( 'users' => array( ), 'posts' => array() ); // load default data if needed if(DataRepository::$load_default_data) { $this->data['users'][1] = $this->default_user; $this->data['posts'][1] = $this->default_post; } $this->writeTheData(); } // load the data into memory for use $this->loadTheData(); } private function showErrors($break = TRUE, $type = NULL) { if(count($this->errors) > 0) { echo "<div style=\"color:red;font-weight: bold;font-size: 1.3em\":<h3>$type Errors</h3><ol>"; foreach($this->errors AS $error) { echo "<li>$error</li>"; } echo "</ol></div>"; if($break) { "</br></br></br>Exiting because of errors!"; exit; } } } private function writeTheData() { $this->log("Attempting to write the datafile: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); file_put_contents(DataRepository::DATAFILE, json_encode($this->data)); $this->log("Datafile written: ".DataRepository::DATAFILE." (line: ".__LINE__.")"); } private function loadTheData() { $this->log("Attempting to load the datafile: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); $this->data = json_decode(file_get_contents(DataRepository::DATAFILE), true); $this->log("Datafile loaded: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $this->data); } private function validateFields(&$info, $fields, $pre_errors = NULL) { // merge in any pre_errors if($pre_errors != NULL) { $this->errors = array_merge($this->errors, $pre_errors); } // check all required fields foreach($fields AS $field => $reqs) { if(isset($reqs['required']) AND $reqs['required'] == 1) { if(!isset($info[$field]) OR strlen($info[$field]) == 0) { $this->errors[] = "$field is a REQUIRED field"; } } // set any default values if not present if(isset($reqs['default']) AND (!isset($info[$field]) OR $info[$field] == "")) { $info[$field] = $reqs['default']; } } $this->showErrors(); if(count($this->errors) == 0) { return TRUE; } else { return FALSE; } } private function validateUser(&$user_info) { // check if the email is already in use $this->log("About to check pre_errors: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $user_info); $pre_errors = NULL; if(isset($user_info['email'])) { if(!$this->isEmailUnique($user_info['email'])) { $pre_errors = array('The email: '.$user_info['email'].' is already used in our system'); } } $this->log("After pre_error check: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $pre_errors); return $this->validateFields($user_info, $this->user_fields, $pre_errors); } private function validatePost(&$post_info) { // check if the user_id in the post actually exists $this->log("About to check pre_errors: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $post_info); $pre_errors = NULL; if(isset($post_info['user_id'])) { if(!isset($this->data['users'][$post_info['user_id']])) { $pre_errors = array('The posts must belong to a valid user. (User '.$post_info['user_id'].' does not exist in the data'); } } $this->log("After pre_error check: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $pre_errors); return $this->validateFields($post_info, $this->post_fields, $pre_errors); } private function log($message, $data = NULL) { $style = "background-color: #F8F8F8; border: 1px solid #DDDDDD; border-radius: 3px; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px;"; if(DataRepository::$debug) { if($data != NULL) { $dump = "<div style=\"$style\"><pre>".json_encode($data, JSON_PRETTY_PRINT)."</pre></div>"; } else { $dump = NULL; } echo "<code><b>Debug:</b> $message</code>$dump<br />"; } } public function saveUser($user_info) { $this->log("Entering saveUser: (".__FUNCTION__.":".__LINE__.")", $user_info); $mydata = array(); $update = FALSE; // check for existing data if(isset($user_info['id']) AND $this->data['users'][$user_info['id']]) { $mydata = $this->data['users'][$user_info['id']]; $this->log("Loaded prior user: ".print_r($mydata, TRUE)." (".__FUNCTION__.":".__LINE__.")"); } // copy over existing values $this->log("Before copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata); foreach($user_info AS $k => $v) { $mydata[$k] = $user_info[$k]; } $this->log("After copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata); // check required fields if($this->validateUser($mydata)) { // hash password if new if(isset($mydata['password'])) { $mydata['password'] = sha1($mydata['password']); } // if no id, add the next available one if(!isset($mydata['id']) OR (int)$mydata['id'] < 1) { $this->log("No id set: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); if(count($this->data['users']) == 0) { $mydata['id'] = 1; $this->log("Setting id to 1: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); } else { $mydata['id'] = max(array_keys($this->data['users']))+1; $this->log("Found max id and added 1 [".$mydata['id']."]: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); } } // set created date if null if(!isset($mydata['created_at'])) { $mydata['created_at'] = date ("Y-m-d H:i:s", time()); } // update modified time $mydata['modified_at'] = date ("Y-m-d H:i:s", time()); // copy into data and save $this->log("Before data save: (".__FUNCTION__.":".__LINE__.")", $this->data); $this->data['users'][$mydata['id']] = $mydata; $this->writeTheData(); } return TRUE; } public function getUserById($id) { if(isset($this->data['users'][$id])) { return $this->data['users'][$id]; } else { return array(); } } public function isEmailUnique($email) { // find the user that has the right username/password foreach($this->data['users'] AS $k => $v) { $this->log("Checking unique email: {$v['email']} == $email (".__FUNCTION__.":".__LINE__.")", NULL); if($v['email'] == $email) { $this->log("FOUND NOT unique email: {$v['email']} == $email (".__FUNCTION__.":".__LINE__.")", NULL); return FALSE; break; } } $this->log("Email IS unique: $email (".__FUNCTION__.":".__LINE__.")", NULL); return TRUE; } public function login($username, $password) { // hash password for validation $password = sha1($password); $this->log("Attempting to login with $username / $password: (".__FUNCTION__.":".__LINE__.")", NULL); $user = NULL; // find the user that has the right username/password foreach($this->data['users'] AS $k => $v) { if($v['email'] == $username AND $v['password'] == $password) { $user = $v; break; } } $this->log("Exiting login: (".__FUNCTION__.":".__LINE__.")", $user); return $user; } public function savePost($post_info) { $this->log("Entering savePost: (".__FUNCTION__.":".__LINE__.")", $post_info); $mydata = array(); // check for existing data if(isset($post_info['id']) AND $this->data['posts'][$post_info['id']]) { $mydata = $this->data['posts'][$post_info['id']]; $this->log("Loaded prior posts: ".print_r($mydata, TRUE)." (".__FUNCTION__.":".__LINE__.")"); } $this->log("Before copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata); foreach($post_info AS $k => $v) { $mydata[$k] = $post_info[$k]; } $this->log("After copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata); // check required fields if($this->validatePost($mydata)) { // if no id, add the next available one if(!isset($mydata['id']) OR (int)$mydata['id'] < 1) { $this->log("No id set: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); if(count($this->data['posts']) == 0) { $mydata['id'] = 1; $this->log("Setting id to 1: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); } else { $mydata['id'] = max(array_keys($this->data['posts']))+1; $this->log("Found max id and added 1 [".$mydata['id']."]: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")"); } } // set created date if null if(!isset($mydata['created_at'])) { $mydata['created_at'] = date ("Y-m-d H:i:s", time()); } // update modified time $mydata['modified_at'] = date ("Y-m-d H:i:s", time()); // copy into data and save $this->data['posts'][$mydata['id']] = $mydata; $this->log("Before data save: (".__FUNCTION__.":".__LINE__.")", $this->data); $this->writeTheData(); } return TRUE; } public function getAllPosts() { return $this->loadPostsUsers($this->data['posts']); } public function loadPostsUsers($posts) { foreach($posts AS $id => $post) { $posts[$id]['user'] = $this->getUserById($post['user_id']); } return $posts; } public function dump($line_number, $temp = 'NO') { // if(DataRepository::$debug) { if($temp == 'NO') { $temp = $this->data; } echo "<pre>Dumping from line: $line_number\n"; echo json_encode($temp, JSON_PRETTY_PRINT); echo "</pre>"; } } } /* * Change Log * * 1.0.0 * - first version * 1.0.1 * - Added isEmailUnique() function for form validation and precheck on user save * 1.0.2 * - Fixed getAllPosts() to include the post's user info * - Added loadPostsUsers() to load one or more posts with their user info * 1.0.3 * - Added autoload to always add admin Joe. */

    Read the article

  • % _ in search form displays all results

    - by fusion
    if the search form is blank, it should display an error that something should be entered by the user. it should only show those results which contain the keywords the user has entered in the search textbox. however, if the user enters % or _ or +, it displays all results. how do i display an error when the user enters these wildcard characters? my search php code: $search_result = ""; $search_result = $_GET["q"]; $search_result = trim($search_result); if ($search_result == "") { echo "<p>Search Error</p><p>Please enter a search...</p>" ; exit(); } $result = mysql_query('SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE "%' . mysql_real_escape_string($search_result) .'%" ORDER BY idQuotes DESC', $conn) or die ('Error: '.mysql_error()); // there's either one or zero records. Again, no need for a while loop function h($s) { echo htmlspecialchars($s, ENT_QUOTES); } ?> <div class="caption">Search Results</div> <div class="center_div"> <table> <?php while ($row= mysql_fetch_array($result)) { ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php h($cQuotes); ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> <?php ?> </div>

    Read the article

  • Website Link Injection

    - by Ryan B
    I have a website that is fairly static. It has some forms on it to send in contact information, mailing list submissions, etc. Perhaps hours/days after an upload to the site I found that the main index page had new code in it that I had not placed there that contained a hidden bunch of links in a invisible div. I have the following code the handles the variables sent in from the form. <?php // PHP Mail Order to [email protected] w/ some error detection. $jamemail = "[email protected]"; function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { die($problem); } return $data; } $email = check_input($_POST['email'], "Please input email address."); $name = check_input($_POST['name'], "Please input name."); mail($jamemail, "Mailing List Submission", "Name: " . $name . " Email: " .$email); header('Location: index.php'); ?> I have the following code within the index page to present the form with some Javascript to do error detection on the content of the submission prior to submission. <form action="sendlist.php" method="post" onSubmit="return checkmaill(this);"> <label for="name"><strong>Name: </strong></label> <input type="text" name="name"/><br /> <label for="email"><strong>Email: </strong></label> <input type="text" name="email"/><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Subscribe" style="width: 100px;"/> </form> At the end of the day, the source code where the injected hyperlinks is as follows: </body> </html><!-- google --><font style="position: absolute;overflow: hidden;height: 0;width: 0"> xeex172901 <a href=http://menorca.caeb.com/od9c2/xjdmy/onondaga.php>onondaga</a> <a href=http://menorca.caeb.com/od9c2/xjdmy/tami.php>tami</a> <a href=http://menorca.caeb.com/od9c2/xjdmy/shotguns.php>shotguns</a> <a href=http://menorca.caeb.com/od9c2/xjdmy/weir.php>weir</a> <a href=http://menorca.caeb.com/od9c2/xjdmy/copperhead.php>copperhead</a> <a href=http://menorca.caeb.com/od9c2/xjdmy/mpv.php>mpv</a> <a href=http://menorca.caeb.com/od9c2/xjdmy/brunei.php>brunei</a> <a href=http://menorca.caeb.com/od9c2/xjdmy/doreen.php>doreen</a>

    Read the article

  • function fetch() on a non-object problem

    - by shin
    I have this url, http://webworks.net/ww.incs/forgotten-password-verification.php?verification_code=974bf747124c69f12ae3b36afcaccc68&[email protected]&redirect=/ww.admin/index.php And this gives the following error. Fatal error: Call to a member function fetch() on a non-object in /var/www/webworks/ww.incs/basics.php on line 23 Call Stack: 0.0005 338372 1. {main}() /var/www/webworks/ww.incs/forgotten-password-verification.php: 0 0.0020 363796 2. dbRow() /var/www/webworks/ww.incs/forgotten-password-verification.php:18 The forgotten-password-verification.php require 'login-libs.php'; login_check_is_email_provided(); // check that a verification code was provided if( !isset($_REQUEST['verification_code']) || $_REQUEST['verification_code']=='' ){ login_redirect($url,'novalidation'); } // check that the email/verification code combination matches a row in the user table // $password=md5($_REQUEST['email'].'|'.$_REQUEST['password']); $r=dbRow('select * from user_accounts where email="'.addslashes($_REQUEST['email']).'" and verification_code="'.$_REQUEST['verification_code'].'" and active' ); if($r==false){ login_redirect($url,'validationfailed'); } // success! set the session variable, then redirect $_SESSION['userdata']=$r; $groups=json_decode($r['groups']); $_SESSION['userdata']['groups']=array(); foreach($groups as $g)$_SESSION['userdata']['groups'][$g]=true; if($r['extras']=='')$r['extras']='[]'; $_SESSION['userdata']['extras']=json_decode($r['extras']); login_redirect($url); And login-libs, require 'basics.php'; $url='/'; $err=0; function login_redirect($url,$msg='success'){ if($msg)$url.='?login_msg='.$msg; header('Location: '.$url); echo '<a href="'.htmlspecialchars($url).'">redirect</a>'; exit; } // set up the redirect if(isset($_REQUEST['redirect'])){ $url=preg_replace('/[\?\&].*/','',$_REQUEST['redirect']); if($url=='')$url='/'; } // check that the email address is provided and valid function login_check_is_email_provided(){ if( !isset($_REQUEST['email']) || $_REQUEST['email']=='' || !filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL) ){ login_redirect($GLOBALS['url'],'noemail'); } } // check that the captcha is provided function login_check_is_captcha_provided(){ if( !isset($_REQUEST["recaptcha_challenge_field"]) || $_REQUEST["recaptcha_challenge_field"]=='' || !isset($_REQUEST["recaptcha_response_field"]) || $_REQUEST["recaptcha_response_field"]=='' ){ login_redirect($GLOBALS['url'],'nocaptcha'); } } // check that the captcha is valid function login_check_is_captcha_valid(){ require 'recaptcha.php'; $resp=recaptcha_check_answer( RECAPTCHA_PRIVATE, $_SERVER["REMOTE_ADDR"], $_REQUEST["recaptcha_challenge_field"], $_REQUEST["recaptcha_response_field"] ); if(!$resp->is_valid){ login_redirect($GLOBALS['url'],'invalidcaptcha'); } } basics.php is, session_start(); function __autoload($name) { require $name . '.php'; } function dbInit(){ if(isset($GLOBALS['db']))return $GLOBALS['db']; global $DBVARS; $db=new PDO('mysql:host='.$DBVARS['hostname'].';dbname='.$DBVARS['db_name'],$DBVARS['username'],$DBVARS['password']); $db->query('SET NAMES utf8'); $db->num_queries=0; $GLOBALS['db']=$db; return $db; } function dbQuery($query){ $db=dbInit(); $q=$db->query($query); $db->num_queries++; return $q; } function dbRow($query) { $q = dbQuery($query); return $q->fetch(PDO::FETCH_ASSOC); } define('SCRIPTBASE', $_SERVER['DOCUMENT_ROOT'] . '/'); require SCRIPTBASE . '.private/config.php'; if(!defined('CONFIG_FILE'))define('CONFIG_FILE',SCRIPTBASE.'.private/config.php'); set_include_path(SCRIPTBASE.'ww.php_classes'.PATH_SEPARATOR.get_include_path()); I am not sure how to solve the problem. Any help will be appreciated. Thanks in advance. UPDATE: My db CREATE TABLE IF NOT EXISTS `user_accounts` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `email` text, `password` char(32) DEFAULT NULL, `active` tinyint(4) DEFAULT '0', `groups` text, `activation_key` varchar(32) DEFAULT NULL, `extras` text, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ; INSERT INTO `user_accounts` (`id`, `email`, `password`, `active`, `groups`, `activation_key`, `extras`) VALUES (2, '[email protected]', '6d24dde9d56b9eab99a303a713df2891', 1, '["_superadministrators"]', '5d50e39420127d0bab44a56612f2d89b', NULL), (3, '[email protected]', 'e83052ab33df32b94da18f6ff2353e94', 1, '[]', NULL, NULL), (9, '[email protected]', '9ca3eee3c43384a575eb746eeae0f279', 1, '["_superadministrators"]', '974bf747124c69f12ae3b36afcaccc68', NULL);

    Read the article

  • Displaying unnecessary HTML when showing content from MySQL database.

    - by ThatMacLad
    My homepage pulls in content from my MySQL database to create a blog. I've got it so that it only displays an extract from the posts. For some reason it displays HTML tags as well rather than formatting it using the tags (See picture below). Any help is appreciated. Homepage: <html> <head> <title>Ultan Casey | Homepage</title> <link rel="stylesheet" href="css/style.css" type="text/css" /> </head> <body> <div class="wrapper"> <div id="upperbar"> <a href="#">Home</a> <a href="#">About Me</a> <a href="#">Contact Me</a> <a href="http://www.twitter.com/UltanKC">Twitter</a> <form id="search-form" action="/search" method="get"> <input type="text" id="textarea" size="33" name="q" value=""/> <input type="submit" id="submit" value="Search"/> </form> </div> <div id="banner"> <img src="images/banner.jpg"> </div> <div class="sidebar"></div> <div class="posts"> <?php mysql_connect ('localhost', 'root', 'root') ; mysql_select_db ('tmlblog'); $sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT 5"; $result = mysql_query($sql) or print ("Can't select entries from table php_blog.<br />" . $sql . "<br />" . mysql_error()); while($row = mysql_fetch_array($result)) { $date = date("l F d Y", $row['timestamp']); $title = stripslashes($row['title']); $entry = stripslashes($row['entry']); $id = $row['id']; ?> <?php echo "<p id='title'><strong><a href=\"post.php?id=". $id . "\">" . $title . "</a></strong></p>"; ?><br /> <div class="post-thumb"><img src="thumbs/<?php echo $id ?>.png"></div> <?php echo htmlspecialchars(substr($entry, 0, 1050)) ?>... <br> <hr><br /> Posted on <?php echo $date; ?> </p> </div> </div> </p <?php } ?> </div> </div> </div> </body> </html> Image:

    Read the article

  • ZF: Form array field - how to display values in the view correctly

    - by Wojciech Fracz
    Let's say I have a Zend_Form form that has a few text fields, e.g: $form = new Zend_Form(); $form->addElement('text', 'name', array( 'required' => true, 'isArray' => true, 'filters' => array( /* ... */ ), 'validators' => array( /* ... */ ), )); $form->addElement('text', 'surname', array( 'required' => true, 'isArray' => true, 'filters' => array( /* ... */ ), 'validators' => array( /* ... */ ), )); After rendering it I have following HTML markup (simplified): <div id="people"> <div class="person"> <input type="text" name="name[]" /> <input type="text" name="surname[]" /> </div> </div> Now I want to have the ability to add as many people as I want. I create a "+" button that in Javascript appends next div.person to the container. Before I submit the form, I have for example 5 names and 5 surnames, posted to the server as arrays. Everything is fine unless somebody puts the value in the field that does not validate. Then the whole form validation fails and when I want to display the form again (with errors) I see the PHP Warning: htmlspecialchars() expects parameter 1 to be string, array given Which is more or less described in ticket: http://framework.zend.com/issues/browse/ZF-8112 However, I came up with a not-very-elegant solution. What I wanted to achieve: have all fields and values rendered again in the view have error messages only next to the fields that contained bad values Here is my solution (view script): <div id="people"> <?php $names = $form->name->getValue(); // will have an array here if the form were submitted $surnames= $form->surname->getValue(); // only if the form were submitted we need to validate fields' values // and display errors next to them; otherwise when user enter the page // and render the form for the first time - he would see Required validator // errors $needsValidation = is_array($names) || is_array($surnames); // print empty fields when the form is displayed the first time if(!is_array($names))$names= array(''); if(!is_array($surnames))$surnames= array(''); // display all fields! foreach($names as $index => $name): $surname = $surnames[$index]; // validate value if needed if($needsValidation){ $form->name->isValid($name); $form->surname->isValid($surname); } ?> <div class="person"> <?=$form->name->setValue($name); // display field with error if did not pass the validation ?> <?=$form->surname->setValue($surname);?> </div> <?php endforeach; ?> </div> The code work, but I want to know if there is an appropriate, more comfortable way to do this? I often hit this problem when there is a need for a more dynamic - multivalue forms and have not find better solution for a long time.

    Read the article

  • php soapclient returns null but getPreviousResults has proper results

    - by Joseph.Chambers
    I've ran into trouble with SOAP, I've never had this issue before and can't find any information on line that helps me solve it. The following code $wsdl = "path/to/my/wsdl"; $client = new SoapClient($wsdl, array('trace' => true)); //$$textinput is passed in and is a very large string with rows in <item></item> tags $soapInput = new SoapVar($textinput, XSD_ANYXML); $res = $client->dataprofilingservice(array("contents" => $soapInput)); $response = $client->__getLastResponse(); var_dump($res);//outputs null var_dump($response);//provides the proper response as I would expect. I've tried passing params into the SoapClient constructor to define soap version but that didnt' help. I've also tried it with the trace param set to false and not present which as expected made $response null but $res was still null. I've tried the code on both a linux and windows install running Apache. The function definition in the WSDL is (xxxx is for security reasons) <portType name="xxxxServiceSoap"> <operation name="dataprofilingservice"> <input message="tns:dataprofilingserviceSoapIn"/> <output message="tns:dataprofilingserviceSoapOut"/> </operation> </portType> I have it working using the __getLastResponse() but its annoying me it will not work properly. I've put together a small testing script, does anyone see any issues here. //very simplifed dataset that would normally be //read in from a CSV file of about 1mb $soapInput = getSoapInput("asdf,qwer\r\nzzxvc,ewrwe\r\n23424,2113"); $wsdl = "path to wsdl"; try { $client = new SoapClient($wsdl,array('trace' => true,'exceptions' => true)); } catch (SoapFault $fault) { $error = 1; var_dump($fault); } try { $res = $client->dataprofilingservice(array("contents" => $soapInput)); $response = $client->__getLastResponse(); echo htmlentities($client->__getLastRequest()); echo '<hr>'; var_dump($res); echo "<hr>"; echo(htmlentities($response)); } catch (SoapFault $fault) { $error = 1; var_dump($fault); } function getSoapInput($input){ $rows = array(); $userInputs = explode("\r\n", $input); $userInputs = array_filter($userInputs); // $inputTemplate = " <contents>%s</contents>"; $rowTemplate = "<Item>%s</Item>"; // $soapString = ""; foreach ($userInputs as $row) { // sanitize $row = htmlspecialchars(addslashes($row)); $xmlStr = sprintf($rowTemplate, $row); $rows[] = $xmlStr; } $textinput = sprintf($inputTemplate, implode(PHP_EOL, $rows)); $soapInput = new SoapVar($textinput, XSD_ANYXML); return $soapInput; }

    Read the article

  • C/PHP: How do I convert the following PHP JSON API script into a C plugin for apache?

    - by TeddyB
    I have a JSON API that I need to provide super fast access to my data through. The JSON API makes a simply query against the database based on the GET parameters provided. I've already optimized my database, so please don't recommend that as an answer. I'm using PHP-APC, which helps PHP by saving the bytecode, BUT - for a JSON API that is being called literally dozens of times per second (as indicated by my logs), I need to reduce the massive RAM consumption PHP is consuming ... as well as rewrite my JSON API in a language that execute much faster than PHP. My code is below. As you can see, is fairly straight forward. <?php define(ALLOWED_HTTP_REFERER, 'example.com'); if ( stristr($_SERVER['HTTP_REFERER'], ALLOWED_HTTP_REFERER) ) { try { $conn_str = DB . ':host=' . DB_HOST . ';dbname=' . DB_NAME; $dbh = new PDO($conn_str, DB_USERNAME, DB_PASSWORD); $params = array(); $sql = 'SELECT homes.home_id, address, city, state, zip FROM homes WHERE homes.display_status = true AND homes.geolat BETWEEN :geolatLowBound AND :geolatHighBound AND homes.geolng BETWEEN :geolngLowBound AND :geolngHighBound'; $params[':geolatLowBound'] = $_GET['geolatLowBound']; $params[':geolatHighBound'] = $_GET['geolatHighBound']; $params[':geolngLowBound'] =$_GET['geolngLowBound']; $params[':geolngHighBound'] = $_GET['geolngHighBound']; if ( isset($_GET['min_price']) && isset($_GET['max_price']) ) { $sql = $sql . ' AND homes.price BETWEEN :min_price AND :max_price '; $params[':min_price'] = $_GET['min_price']; $params[':max_price'] = $_GET['max_price']; } if ( isset($_GET['min_beds']) && isset($_GET['max_beds']) ) { $sql = $sql . ' AND homes.num_of_beds BETWEEN :min_beds AND :max_beds '; $params['min_beds'] = $_GET['min_beds']; $params['max_beds'] = $_GET['max_beds']; } if ( isset($_GET['min_sqft']) && isset($_GET['max_sqft']) ) { $sql = $sql . ' AND homes.sqft BETWEEN :min_sqft AND :max_sqft '; $params['min_sqft'] = $_GET['min_sqft']; $params['max_sqft'] = $_GET['max_sqft']; } $stmt = $dbh->prepare($sql); $stmt->execute($params); $result_set = $stmt->fetchAll(PDO::FETCH_ASSOC); /* output a JSON representation of the home listing data retrieved */ ob_start("ob_gzhandler"); // compress the output header('Content-type: text/javascript'); print "{'homes' : "; array_walk_recursive($result_set, "cleanOutputFromXSS"); print json_encode( $result_set ); print '}'; $dbh = null; } catch (PDOException $e) { die('Unable to retreive home listing information'); } } function cleanOutputFromXSS(&$value) { $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); } ?> How would I begin converting this PHP code over to C, since C is both better on memory management (since you do it yourself) and much, much faster to execute?

    Read the article

  • how to change php functions send result to jquery ajax

    - by OpenCode
    I have many codes for user notifications, it do many mysql works, so it needs waiting times. jquery ajax works for php files. how can i use jquery for send php result to web page? current code : <? echo db_cache("main_top_naver_cache", 300, "naver_popular('naver_popular', 4)"))?> wanted code : but it shows errors... <div id='a'> <div id='b'> <script type="text/javascript"> $("#test1").html( " <? echo htmlspecialchars(db_cache("main_top_naver_cache", 300, "naver_popular('naver_popular', 4)"))?> " ); </script> IE debuger shows error ... SCRIPT1015:... <script type="text/javascript"> $("#test1").html( " &lt;style&gt; /* http://html.nhncorp.com/uio_factory/ui_pattern/list/3 */ .section_ol3{position:relative;border:1px solid #ddd;background:#fff;font-size:12px;font-family:Tahoma, Geneva, sans-serif;line-height:normal;*zoom:1} .section_ol3 a{color:#666;text-decoration:none} .section_ol3 a:hover, .section_ol3 a:active, .section_ol3 a:focus{text-decoration:underline} .section_ol3 em{font-style:normal} .section_ol3 h2{margin:0;padding:10px 0 8px 13px;border-bottom:1px solid #ddd;font-size:12px;color:#333} .section_ol3 h2 em{color:#cf3292} .section_ol3 ol{margin:13px;padding:0;list-style:none} .section_ol3 li{position:relative;margin:0 0 10px 0;*zoom:1} .section_ol3 li:after{display:block;clear:both;content:&quot;&quot;} .section_ol3 li .ranking{display:inline-block;width:14px;height:11px;margin:0 5px 0 0;border-top:1px solid #fff;border-bottom:1px solid #d1d1d1;background:#d1d1d1;text-align:center;vertical-align:top;font:bold 10px Tahoma;color:#fff} .section_ol3 li.best .ranking{border-bottom:1px solid #6e87a5;background:#6e87a5} .section_ol3 li.best a{color:#7189a7} .section_ol3 li .num{position:absolute;top:0;right:0;font-size:11px;color:#a8a8a8;white-space:nowrap} .section_ol3 li.best .num{font-weight:bold;color:#7189a7} .section_ol3 .more{position:absolute;top:10px;right:13px;font:11px Dotum, ??;text-decoration:none !important} .section_ol3 .more span{margin:0 2px 0 0;font-weight:bold;font-size:16px;color:#d76ea9;vertical-align:middle} &lt;/style&gt; &lt;div class=&quot;section_ol3&quot;&gt; &lt;ol style='text-align:left;'&gt; &lt;li class='best'&gt;&lt;span class='ranking'&gt;1&lt;/span&gt;&lt;a href='http://search.naver.com/search.naver?where=nexearch&amp;query=%B9%AB%C7%D1%B5%B5%C0%FC&amp;sm=top_lve' onfocus='this.blur()' title='????' target=new&gt;????&lt;/a&gt;&lt;span class='num'&gt;+42&lt;/span&gt;&lt;/li&gt;&lt;li class='best'&gt;&lt;span class='ranking'&gt;2&lt;/span&gt;&lt;a href='http://search.naver.com/search.naver?where=nexearch&amp;query=%B1%E8%C0%E7%BF%AC&amp;sm=top_lve' onfocus='this.blur()' title='???' target=new&gt;???&lt;/a&gt;&lt;span class='num'&gt;+123&lt;/span&gt;&lt;/li&gt;&lt;li class='best'&gt;&lt;span class='ranking'&gt;3&lt;/span&gt;&lt;a href='http://search.naver.com/search.naver?where=nexearch&amp;query=%C0%CC%C7%CF%C0%CC&amp;sm=top_lve' onfocus='this.blur()' title='???' target=new&gt;???&lt;/a&gt;&lt;span class='num'&gt;+90&lt;/span&gt;&lt;/li&gt;&lt;li &gt;&lt;span class='ranking'&gt;4&lt;/span&gt;&lt;a href='http://search.naver.com/search.naver?where=nexearch&amp;query=%BA%D2%C8%C4%C0%C7%B8%ED%B0%EE2&amp;sm=top_lve' onfocus='this.blur()' title='?????2' target=new&gt;?????2&lt;/a&gt;&lt;span class='num'&gt;+87&lt;/span&gt;&lt;/li&gt; &lt;/ol&gt; </div> " );

    Read the article

  • My form php is not working and I can't figure out where I went wrong

    - by user1081524
    I'm fairly new to all this, but I've created a form, and this is what I've written to send it. I've used "[email protected]" here instead of the real address <?php /* Set e-mail recipient */ $myemail = "[email protected]"; /* Check all form inputs using check_input function */ $names = check_input($_POST['names'], "Please return to our Application Form and enter your and your future spouse's names."); $weddingtype = check_input($_POST['weddingtype'], "Please return to our Application Form and fill in what kind of wedding you will be having."); $religioussect = check_input($_POST['religioussect'], "Please return to our Application Form and tell us about your religion and wedding traditions."); $dateone = check_input($_POST['dateone'], "Please return to our Application Form and give us the date for at least one event."); $eventone = check_input($_POST['eventone'], "Please return to our Application Form and list at least one event."); $locationone = check_input($_POST['locationone'], "Please return to our Application Form and give us the location for at least one event."); $durationone = check_input($_POST['durationone'], "Please return to our Application Form and give us the duration of at least one event."); $typeone = check_input($_POST['typeone'], "Please return to our Application Form and tell us whether you would like video, photo or both for at least one event."); $datetwo = $_POST['datetwo']; $eventtwo = $_POST['eventtwo']; $locationtwo = $_POST['locationtwo']; $durationtwo = $_POST['durationtwo']; $typetwo = $_POST['typetwo']; $datethree = $_POST['datethree']; $eventthree = $_POST['eventthree']; $locationthree = $_POST['locationthree']; $durationthree = $_POST['durationthree']; $typethree = $_POST['typethree']; $datefour = $_POST['datefour']; $eventfour = $_POST['eventfour']; $locationfour = $_POST['locationfour']; $durationfour = $_POST['durationfour']; $typefour = $_POST['typefour']; $guests1 = check_input($_POST['guests1'], "Please return to our Application Form and tell us how many guests will attend at least one event."); $guests2 = $_POST['guests2']; $guests3 = $_POST['guests3']; $guests4 = $_POST['guests4']; $concerns = $_POST['concerns']; if(!isset($_POST['submit'])){ $subject = "Quote Application"; /*Message for the e-mail */ $message = "Hello! Another happy couple has filled out a Quote Application Form :D Hooray! Their names are $names. What sort of wedding are they having? '$weddingtype'. What religious sect and wedding traditions are they following? '$religioussect'. Now for their wedding events... Ooh boy! 1. $dateone $eventone $durationone $typeone Estimated guests: $guests1 $locationone 2. $datetwo $eventtwo $durationtwo $typetwo Estimated guests: $guests2 $locationtwo 3. $datethree $eventthree $durationthree $typethree Estimated guests: $guests3 $locationthree 4. $datefour $eventfour $durationfour $typefour Estimated guests: $guests4 $locationfour Any concerns the couple have follow here: '$concerns' You better be ready to get to work now! And also, have a really good day :) "; /* Functions used */ function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <b>We apologize for the inconvenience, an error occurred.</b><br /> <?php echo $myError; ?> <?php exit(); } /* Send the message using mail() function */ mail($myemail, $subject, $message); /* Redirect visitor to the thank you page */ header('Location: thanks.html'); exit(); ?> Please help me find what I'm doing wrong, I'm barely a beginner here. Thanks in advance!

    Read the article

  • pagination in css/php

    - by fusion
    two questions: --1-- it displays all the number of pages. but i'd like it to display as: << Prev . . 3 4 [5] 6 7 . . Next --2-- when i hover on the current page no, it should change color or increase the font-size, but when i modify the css of a:hover, all the page nos change color or size instead of the one which i'm pointing to. also, when modifying a:active, nothing happens. this is my paging code in php: $self = $_SERVER['PHP_SELF']; $limit = 2; //Number of results per page $numpages=ceil($totalrows/$limit); $query = $query." ORDER BY idQuotes LIMIT " . ($page-1)*$limit . ",$limit"; $result = mysql_query($query, $conn) or die('Error:' .mysql_error()); ?> <div class="caption">Search Results</div> <div class="center_div"> <table> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php echo $cQuote; ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> </div> <div class="searchmain"> <?php //Create and print the Navigation bar $nav=""; $next = $page+1; $prev = $page-1; if($page > 1) { $nav .= "<span class=\"searchpage\"><a onclick=\"showPage('','$prev'); return false;\" href=\"$self?page=" . $prev . "&q=" .urlencode($search_result) . "\">< Prev</a></span>"; $first = "<span class=\"searchpage\"><a onclick=\"showPage('','1'); return false;\" href=\"$self?page=1&q=" .urlencode($search_result) . "\"> << </a></span>" ; } else { $nav .= "&nbsp;"; $first = "&nbsp;"; } for($i = 1 ; $i <= $numpages ; $i++) { if($i == $page) { $nav .= "<span class=\"searchpage\">$i</span>"; }else{ $nav .= "<span class=\"searchpage\"><a onclick=\"showPage('',$i); return false;\" href=\"$self?page=" . $i . "&q=" .urlencode($search_result) . "\">$i</a></span>"; } } if($page < $numpages) { $nav .= "<span class=\"searchpage\"><a onclick=\"showPage('','$next'); return false;\" href=\"$self?page=" . $next . "&q=" .urlencode($search_result) . "\">Next ></a></span>"; $last = "<span class=\"searchpage\"><a onclick=\"showPage('','$numpages'); return false;\" href=\"$self?page=$numpages&q=" .urlencode($search_result) . "\"> >> </a></span>"; } else { $nav .= "&nbsp;"; $last = "&nbsp;"; } echo $first . $nav . $last; ?> </div> and this is how it displays currently: css: .searchmain { margin:30px; text-align: center; } .searchpage { border: solid 1px #ddd; background: #fff; text-align:left; font-size: 16px; padding:9px 12px; color: #FEBE33; margin-left:2px; } .searchpage a{ text-decoration: none; color: #808080; } .searchpage a:hover { color: #FEBE33; border-color: #036; text-decoration: none; } .searchpage a:visited { color: #808080; }

    Read the article

  • textbox disappears in paging - php

    - by fusion
    i'm calling the search.php page via ajax to search.html. the problem is, since i've implemented paging, the textbox with the search keyword from search.html 'disappears' when the user clicks the 'Next' button [because the page goes to search.php which has no textbox element] i'd like the textbox with the search keyword to be there, when the user goes through the records via paging. how'd i achieve this? search.html: <body> <form name="myform" class="wrapper"> <input type="text" name="q" onkeyup="showPage();" class="txt_search"/> <input type="button" name="button" onclick="showPage();" class="button"/> <p> <div id="txtHint"></div> <div id="page"></div> </form> </body> search.php [the relevant part]: $self = $_SERVER['PHP_SELF']; $limit = 5; //Number of results per page $numpages=ceil($totalrows/$limit); $query = $query." ORDER BY idQuotes LIMIT " . ($page-1)*$limit . ",$limit"; $result = mysql_query($query, $conn) or die('Error:' .mysql_error()); ?> <div class="caption">Search Results</div> <div class="center_div"> <table> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php echo $cQuote; ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> </div> <?php //Create and print the Navigation bar $nav=""; if($page > 1) { $nav .= "<a href=\"$self?page=" . ($page-1) . "&q=" .urlencode($search_result) . "\">< Prev</a>"; $first = "<a href=\"$self?page=1&q=" .urlencode($search_result) . "\"><< First</a>" ; } else { $nav .= "&nbsp;"; $first = "&nbsp;"; } for($i = 1 ; $i <= $numpages ; $i++) { if($i == $page) { $nav .= "<B>$i</B>"; }else{ $nav .= "<a href=\"$self?page=" . $i . "&q=" .urlencode($search_result) . "\">$i</a>"; } } if($page < $numpages) { $nav .= "<a href=\"$self?page=" . ($page+1) . "&q=" .urlencode($search_result) . "\">Next ></a>"; $last = "<a href=\"$self?page=$numpages&q=" .urlencode($search_result) . "\">Last >></a> "; } else { $nav .= "&nbsp;"; $last = "&nbsp;"; } echo "<br /><br />" . $first . $nav . $last; }

    Read the article

  • paging php error - undefined index

    - by fusion
    i've a search form with paging. when the user enters the keyword initially, it works fine and displays the required output; however, it also shows this error: Notice: Undefined index: page in C:\Users\user\Documents\Projects\Pro\search.php on line 21 Call Stack: 0.0011 372344 1. {main}() C:\Users\user\Documents\Projects\Pro\search.php:0 . .and if the user clicks on the 'next' page, it shows no output with this error thrown: Notice: Undefined index: q in C:\Users\user\Documents\Projects\Pro\search.php on line 19 Call Stack: 0.0016 372048 1. {main}() C:\Users\user\Documents\Projects\Pro\search.php:0 this is my code: <?php ini_set('display_errors',1); error_reporting(E_ALL|E_STRICT); include 'config.php'; $search_result = ""; $search_result = trim($_GET["q"]); $page= $_GET["page"]; //Get the page number to show if($page == "") $page=1; $search_result = mysql_real_escape_string($search_result); //Check if the string is empty if ($search_result == "") { echo "<p class='error'>Search Error. Please Enter Your Search Query.</p>" ; exit(); } if ($search_result == "%" || $search_result == "_" || $search_result == "+" ) { echo "<p class='error1'>Search Error. Please Enter a Valid Search Query.</p>" ; exit(); } if(!empty($search_result)) { // the table to search $table = "thquotes"; // explode search words into an array $arraySearch = explode(" ", $search_result); // table fields to search $arrayFields = array(0 => "cQuotes"); $countSearch = count($arraySearch); $a = 0; $b = 0; $query = "SELECT cQuotes, vAuthor, cArabic, vReference FROM ".$table." WHERE ("; $countFields = count($arrayFields); while ($a < $countFields) { while ($b < $countSearch) { $query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'"; $b++; if ($b < $countSearch) { $query = $query." AND "; } } $b = 0; $a++; if ($a < $countFields) { $query = $query.") OR ("; } } $query = $query.")"; $result = mysql_query($query, $conn) or die ('Error: '.mysql_error()); $totalrows = mysql_num_rows($result); if($totalrows < 1) { echo '<span class="error2">No matches found for "'.$search_result.'"</span>'; } else { $limit = 3; //Number of results per page $numpages=ceil($totalrows/$limit); $query = $query." ORDER BY idQuotes LIMIT " . ($page-1)*$limit . ",$limit"; $result = mysql_query($query, $conn) or die('Error:' .mysql_error()); ?> <div class="caption">Search Results</div> <div class="center_div"> <table> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php echo $cQuote; ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> </div> <?php //Create and print the Navigation bar $nav=""; if($page > 1) { $nav .= "<a href=\"search.php?page=" . ($page-1) . "&string=" .urlencode($search_result) . "\"><< Prev</a>"; } for($i = 1 ; $i <= $numpages ; $i++) { if($i == $page) { $nav .= "<B>$i</B>"; }else{ $nav .= "<a href=\"search.php?page=" . $i . "&string=" .urlencode($search_result) . "\">$i</a>"; } } if($page < $numpages) { $nav .= "<a href=\"search.php?page=" . ($page+1) . "&searchstring=" .urlencode($search_result) . "\">Next >></a>"; } echo "<br /><br />" . $nav; } } else { exit(); } ?>

    Read the article

  • pagination in php error

    - by fusion
    i've implemented this pagination class for my webpage in a separate file called class.pagination.php, but when i execute the page, nothing happens. it just displays a blank page. this is my search.php file, where i'm calling this class: <?php include 'config.php'; require ('class.pagination.php'); $search_result = ""; $search_result = $_GET["q"]; $search_result = trim($search_result); //Check if the string is empty if ($search_result == "") { echo "<p class='error'>Search Error. Please Enter Your Search Query.</p>" ; exit(); } //search query for multiple keywords if(!empty($search_result)) { // the table to search $table = "thquotes"; // explode search words into an array $arraySearch = explode(" ", $search_result); // table fields to search $arrayFields = array(0 => "cQuotes"); $countSearch = count($arraySearch); $a = 0; $b = 0; $query = "SELECT cQuotes, vAuthor, cArabic, vReference FROM ".$table." WHERE ("; $countFields = count($arrayFields); while ($a < $countFields) { while ($b < $countSearch) { $query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'"; $b++; if ($b < $countSearch) { $query = $query." AND "; } } $b = 0; $a++; if ($a < $countFields) { $query = $query.") OR ("; } } $query = $query.")"; $result = mysql_query($query, $conn) or die ('Error: '.mysql_error()); $totalrows = mysql_num_rows($result); if($totalrows < 1) { echo '<span class="error2">No matches found for "'.$search_result.'"</span>'; } else { ?> <div class="caption">Search Results</div> <div class="center_div"> <table> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php echo $cQuote; ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> </div> <?php } } else { exit(); } //Setting Pagination $pagination = new pagination(); $pagination->byPage = 5; $pagination->rows = $totalrows; // number of records in a table-back mysql_num_rows () instance or another, you have to play $from = $pagination->fromPagination(); // sql used for applications such LIMIT $ from, $ pagination-> byPage $pages = $pagination->pages(); if(isset($pages)) {?> <div class="pagination"> <?foreach ($pages as $key){?> <?if($key['current'] == 1) {?> <a href="?p=<?=$key['p']?>" class="active"><?=$key['page']?></a> <?} else {?> <a href="?p=<?=$key['p']?>" class="inactive"><?=$key['page']?></a> <?}?> <?}?> </div> <?} //End Pagination ?>

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >