-
Posts
3,584 -
Joined
-
Last visited
-
Days Won
3
Everything posted by JonnoTheDev
-
Advice needed: Display image gallery and allow user to choose one
JonnoTheDev replied to Karny's topic in PHP Coding Help
That is fairly simple to do with javascript. Try this little example I have written. <html> <head> <title>Test</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('.image_select').click(function() { $('input[name="image"]').val($(this).attr('data-url')); return false; }); }); </script> </head> <body> <p> <img src="http://www.publicdomainpictures.net/pictures/10000/nahled/red-rose-28061277749457y4Rq.jpg" width="150"> <br> <a class="image_select" href="#" data-url="http://www.publicdomainpictures.net/pictures/10000/nahled/red-rose-28061277749457y4Rq.jpg">Select Image</a> </p> <p> <img src="http://www.publicdomainpictures.net/pictures/20000/nahled/beaches.jpg" width="150"> <br> <a class="image_select" href="#" data-url="http://www.publicdomainpictures.net/pictures/20000/nahled/beaches.jpg">Select Image</a> </p> <p> <img src="http://www.publicdomainpictures.net/pictures/10000/nahled/1-1229635950dOuv.jpg" width="150"> <br> <a class="image_select" href="#" data-url="http://www.publicdomainpictures.net/pictures/10000/nahled/1-1229635950dOuv.jpg">Select Image</a> </p> <form> <p>Selected Image</p> <p><input type="text" name="image" size="100" readonly></p> </form> </body> </html> Just save it as test.html or whatever -
If you are using Bootstrap for your front-end development the I recommend Font Awesome. I use this all the time for CMS systems, etc http://fontawesome.io/ http://getbootstrap.com/
-
Avoid global variables. You have just discovered the pitfall of using them!
-
The [L] means it is the last rule that the web server should observe if it matches the URL pattern. You may have additional rules for other URLs, so it basically says, "don't bother reading any of the other rules if this one matches". You can change the regex to whatever you like. I like to keep URLs consistent by making everything lowercase. You can download a program like Regexbuddy to make sure you get it correct http://www.regexbuddy.com/ It is a useful tool. In terms of the slug in the URL you have 2 options IMO. You can either add another field to one of your database tables to store it and run a little program that will create it from the data you have and update your database. Or, use the query you are using to get the page title to create the slug for the links. You will obviously have to run it through a little function to make sure any non alphanumeric characters are stripped out, and any spaces are converted to hyphens (it has to match the rewrite rule). Then when a user clicks on the link you can run the same query & function on the landing page to make sure that the URL parameter matches. If it doesn't, redirect the user to a 404 page using the header() function. In terms of using the database table primary key in the URL, this is a viable option. A URL such as: mysite.com/article/a-page-about-php/2 would require the following rewrite rule: RewriteEngine On RewriteBase / # only a-z 0-9 and the - character can be in the slug RewriteRule ^article/([a-z0-9-]+)/([0-9]+)$ article.php?slug=$1&article_id=$2 [L] In this case we now have both $_GET['slug'] & $_GET['article_id'] available to us. We can use the article_id to quickly get the correct database record, run the slug creation function on the page title and compare it to the value of $_GET['slug']. If it matches all is good, if not, redirect to a 404 page.
-
I think the issue here is some of the responses posted are a little direct in assuming they expect you to understand what they are talking about. When you use the term, 'Pretty URL' you are actually referring to, 'SEO Friendly URLs'. SEO is Search Engine Optimisation. So, URLs in this clean format are more friendly to search engines, like Google, as opposed to a URL that reads xyz.com?x=13&y=foobar. To use URLs like this you need to use a module on the web server calls Mod Rewrite. This allows a URL in a clean format (rewritten) to be translated to the non-clean format. To create the Mod Rewrite rules you need to put things into a .htaccess file in the document root of your website folder. Now, where I think you are getting confused is how you implement rewritten URLs. You do not take the page title from a static html page and then redirect to a different URL. If you want the link to www.mysite.com/somepage.html to be www.mysite.com/this-page-is-awesome/ Then you would put the following in a .htaccess file: RewriteEngine On RewriteBase / RewriteRule ^somepage.html /this-page-is-awesome [R=301,L] Try it. Now, If the data i.e. the page title, content, etc is coming from a MySQL database, lets say in a table called, 'articles'. You may have the following fields: article_id, title, body, slug. So, some example data may look like: 1 | This Page is Awesome | This is the page copy | this-page-is-awesome 2 | A Page About PHP | PHP is a great language | a-page-about-php When we display this data we are going to use the file article.php. To get the correct article the page needs a parameter i.e article.php?param=xyz. This is where the slug field comes in. So when we want article 1 the url is article.php?slug=this-page-is-awesome You may now be getting the idea of where we are going. The URL obviously isn't friendly. We want our URLs to contain just alphanumeric characters i.e mysite.com/article/this-page-is-awesome mysite.com/article/a-page-about-php This is where we add the rewrite rules to our .htaccess file i.e RewriteEngine On RewriteBase / # only a-z 0-9 and the - character can be in the slug RewriteRule ^article/([a-z0-9-]+)$ article.php?slug=$1 [L] Job done. All we have to do is change the links on our website to use the data in the slug field. i.e <a href="/article/<?php print $row['slug']; ?>"><?php print $row['title']; ?></a> Remember, the article.php file takes the parameter, 'slug' and uses it to get the article from the database. i.e $mysqli = new mysqli("localhost", "my_user", "my_password", "my_database"); $mysqli->query("SELECT * FROM articles WHERE slug='" . $mysqli->real_escape_string($_GET['slug']); . "'");
-
Trying to print total number of rows returned...
JonnoTheDev replied to Jim R's topic in PHP Coding Help
It is the mysql functions that shouldn't be used as they are depreciated. You should use mysqli. The i stands for improved. Basically just add an i to the end of the function name as they are mostly the same, although just double check on php.net before using them. Your code would look as follows using the mysqli functions $link = mysqli_connect('host','user','pass','db_name') or die(mysqli_error($link)); $query = "SELECT * FROM a_playerRank WHERE YEAR=\"2014\" AND commit=\"1\" AND state=\"IN\" ORDER BY nameLast"; if($results = mysqli_query($link, $query)) { $count = mysqli_num_rows($results); echo '<div class="commit_list">'; echo 'There are '.$count.' kids committed.'; } -
Trying to print total number of rows returned...
JonnoTheDev replied to Jim R's topic in PHP Coding Help
$results = mysql_query($query); $count = mysql_num_rows($results); -
My question is, Do you even need to use a Framework for this project in it's current state? From what you have stated here it seems that a framework may be overkill for adding a bit of logic to pull some content from a database or a simple CMS to add content. You could put that together in a few hours. If your project specification is complex, then yes, I would use a framework. I would definitely not reinvent the wheel and write my own. IMO this will take longer to do as opposed to starting with a framework that has good documentation such as CodeIgniter. It seems to me that you are wanting to learn how to put a framework together. This is good, however I would do this as an exercise after working on this project. If you use a current framework you will get an idea of what needs to go into it. It will be a good exercise to improve your skillset, but it will take a bit of time. This is not an issue. Frameworks are adaptable and extendable. If you have never used a framework I think you are just assuming that you won't be able to do something.
-
CURL seems to ignore "Connection: close"
JonnoTheDev replied to RuleBritannia's topic in PHP Coding Help
In the CLI there is no $_GET. The equivalent is $argv http://php.net/manual/en/reserved.variables.argv.php However, this does not work using name, value pairs as URL parameters do i.e script.php?x=1&y=2 To get the value of x and y I would use $_GET['x'], $_GET['y'] In the command line I cannot define x or y as parameter names. I can only supply values i.e /path/to/script.php 1 2 To get the parameters in a command line script I would use $argv[0], $argv[1] So to put it in a nutshell, the function I have given you allows you to pass parameters to a script in the command line using name, value pairs. You can see that the function is taking $argv as its parameter. It is totally up to you how you want to deal with parameters on the command line. Here is a bit more explanation http://stackoverflow.com/questions/9612166/passing-command-line-arguments-to-a-php-script -
I have integrated Paypal Website Payments Pro (Direct Payments & Express Checkout), including Cardinal Commerce (used for 3D secure transactions i.e Verified by Visa, MasterCard SecureCode) many times. This is used for taking card payments on your own website so you will need an SSL certificate. There are code examples available that you can download, however they are nowhere near the finished article that you should put into a production website. I would not recommend even attempting to integrate this without reading all the documentation thoroughly. On the other hand, if you would like to integrate a payment gateway where a user leaves your site, makes a payment (lets say, on Paypal's website) and then is returned to your website once a payment has been made, then this is not too difficult. Paypal have IPN (Instant payment notification). Basically you create a form that when submitted, sends a user to Paypal. The form contains hidden fields containing the amount, currency code, etc. You also create a page on your site that Paypal contacts (in the background) when a payment is made. This page is waiting for POST data containing certain things. If it sends a success message to the page then you can process the customers order via the same page. Most payment gateways work in the same way. If you still don't feel comfortable attempting an integration then there will be web companies that will do it for you. That being said, as you site is a custom script your code maybe up for scrutiny. Most companies offering payment gateway integrations do it for off-the-shelf scripts such as osCommerce, Joomla, Drupal, Zen Cart, etc I wouldn't bank on getting help from Paypal in terms of coding. Most of their code examples are written by third party developers. However, if you can understand the examples it is pretty straight forward to bastardize them to fit your script. You must read all documentation so you clearly understand how the payments process works and the data it expects to receive, and the responses it posts back to your website.
-
CURL seems to ignore "Connection: close"
JonnoTheDev replied to RuleBritannia's topic in PHP Coding Help
If you have scripts that take time to process why not simply fork them to the command line. If the script is on the same server why even use CURL? i.e exec("php /path/to/script.php --param=44 > /dev/null &"); The --param is the equiv of a URL param (GET) In your CLI script you can get the param value using this function function arguments($argv) { $_ARG = array(); foreach($argv as $arg) { if(preg_match('/--[a-zA-Z0-9]*=.*/', $arg)) { $str = preg_split('/=/',$arg); $arg = ''; $key = preg_replace('/--/','',$str[0]); for($i = 1; $i < count($str); $i++) { $arg .= $str[$i]; } $_ARG[$key] = $arg; } elseif(preg_match('/-[a-zA-Z0-9]/',$arg)) { $arg = preg_replace('/-/','',$arg); $_ARG[$arg] = 'true'; } } return $_ARG; } Usage $_ARGS = arguments($argv); // prints 44 echo $_ARGS['param']; -
First, run the query in your database admin so you can see what data is coming out (is it correct). If the query needs extending to add your other table in then do it and test the query again. Modify the $categories array to hold the extra data if you need to. Second, dump the array out so you can see that the data is all contained correctly. Don't expect code to just work first time. Always test to see what the data looks like. $categories = array(); $result = mysql_query("SELECT c.cat_id, c.cat_name, s.sub_cat_id, s.sub_cat_name FROM category c INNER JOIN sub_category s ON(c.cat_id=s.category_id) ORDER BY c.cat_name ASC, s.sub_cat_name ASC"); while($row = mysql_fetch_assoc($result)) { $categories[$row['cat_id']]['cat'] = array('name' => $row['cat_name']); $categories[$row['cat_id']]['subcats'][$row['sub_cat_id']] = array('name' => $row['sub_cat_name']); } print "<pre>"; print_r($categories); print "</pre>"; exit();
-
Is it possible to save a facebook session into a database?
JonnoTheDev replied to Mok's topic in Other Libraries
You can't log someone into Facebook from a third party website log on procedure. What you can do is the opposite. Allow a user to log on to your website using their Facebook username / password. You can read up on how to do this via the FB developers docs. This would log users into both systems.- 2 replies
-
- facebook sdk
-
(and 1 more)
Tagged with:
-
making non WordPress pages blend with WordPress theme
JonnoTheDev replied to rghollenbeck's topic in Applications
If your quiz section does not use any of the wordpress codebase then do not attempt to integrate it in. A 5 minute job is simply go to your website homepage (or a page that runs on wordpress) in Firefox (or whatever browser you use), right click on the page and select view source. Copy the source and paste it into your PHP editor. There is your base template. Add your quiz php code into the relevent parts of the template. Job done. Its quick and dirty but it will save you a headache. -
You need to organise the data into an array. If you are using mysql functions try the following: <?php $categories = array(); $result = mysql_query("SELECT c.cat_id, c.cat_name, s.sub_cat_id, s.sub_cat_name FROM category c INNER JOIN subcategory s ON(c.cat_id=s.category_id) ORDER BY c.cat_name ASC, s.sub_cat_name ASC"); while($row = mysql_fetch_assoc($result)) { $categories[$row['cat_id']]['cat'] = array('name' => $row['cat_name']); $categories[$row['cat_id']]['subcats'][$row['sub_cat_id']] = array('name' => $row[['sub_cat_name']); } foreach($categories as $cat_id => $row): ?> <h4><?php echo $row['name']; ?></h4> <ul> <?php foreach($row['subcats'] as $sub_cat_id => $sub_row): ?> <li><?php echo $sub_row['name']; ?></li> <?php endforeach; ?> </ul> <?php endforeach; ?>
-
Why doesn't this array update if no checkbox is selected?
JonnoTheDev replied to Exoon's topic in PHP Coding Help
When the form is submitted, firstly destroy the session variable and then reset it. Sessions will persist until you destroy them. It would be better to store the post data under a specific session key as opposed to a direct copy of the post array so you can easily clear it. i.e // form submitted if(isset($_POST) && count($_POST)) { // clear session data unset($_SESSION['form_data']); // store session data $_SESSION['form_data'] = $_POST; } // just to see whats in my session I will dump it if(isset($_SESSION)) { print_r($_SESSION); } -
GLOBAL VARIABLES ARE BEING USED! RULE 101 IN PHP: DO NOT USE GLOBAL VARIABLES. Have you written this script or copied & pasted it from somewhere? Here is a modified version: <?php //db connection mysql_connect($db_host,$db_username,$db_password) or die(mysql_error()); mysql_select_db($db_name) or die(mysql_error()); if(isset($_POST['submit'])) { //set emails as array $emails = array(); $x = 1; //quantity of emails sent before 3 sec delay to avoid timeout $hold = 99; //query to select the email address $sql = mysql_query("SELECT email_address FROM tblusers") or die(mysql_error()); //fetch them while($r = mysql_fetch_array($sql)) { $emails[] = $r['email']; } //count total emails $total = count($emails); //repeat for each email for ($i = 1; $i <= $total; $i++) { //stripslashes in message $msg = stripslashes($_POST['msg']); //send email to user (need to change name and email:) mail($emails[$i], $_POST['subject'], $msg, "From: Your Site<newsletter@yoursite.com>"); //if $x = 10 then wait 3 seconds to avoid timeout $x++; if($x == $hold) { sleep(3); $x = 0; } } //close database connection and echo success message mysql_close(); echo "<strong>Mail successfully sent to $total addresses!</strong><br><br>"; } ?> <html> <head> <title>Send Mail</title> <body> <form name="mail" action="" method="post"> Subject: <input type="text" name="subject" size="40"><br> <textarea name="msg" cols="40" rows="8"></textarea><br> <input type="submit" name="submit" value="Send Email"> </form> </body> </html> On a side note, you should not be using a web browser script to send mass email. This should be done through a command line script. You should use a SMTP server to send the mail. PHP's mail() function is not sufficient enough. Have a look at PEAR::Mail http://pear.php.net/package/Mail
-
Javascript can detect keyboard input. You can register an event handler i.e document.addEventListener('keydown', function(event) { if (event.keyCode == 69) { alert('you pressed the letter e'); } }, true); Here are the keycodes http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
-
As Kevin has stated you need to identify which affiliate the inbound link has come from. Give each affiliate a unique key, some md5 string will be fine. Every link that the affiliate uses must contain their key. You could have a page that the affiliates can login to to see what links they can use. So, for instance, if an affiliate wants to promote a book that you are selling on your website from their own website they may use http://www.x.com/book/php-for-dummies?aff_id=adre34rfdrehkj87654 When a user lands on your site you must always be looking for that parameter (aff_id). If it exists, verify it, store it in a session, and if that user registers or buys on your site you know that the customer has come from a link that the affiliate has published. Affiliates will want to know what their sales are so you will need to create an affiliated members area for your website. You need to decide on commission thresholds, etc. You will also need to create a mechanism so you know how much and when to pay an affiliated member. If a customer buys something and then is issued a refund, the commission total for the affiliate may need to change. You need to decide all this in your business model.
-
Far easier to do this yourself rather than using wordpress IMO. Wordpress works best for blogs. IMO it does not work when it is turned into something else. The codebase in wordpress is a mess.
-
Try this http://www.myezapp.com/apps/dev/regexp/show.ws Put the regex patter into this website and it will explain it to you. # replace any character that is not in the range 0 - 9 $managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); # replace any character that is not in the range A - Z or a - z or 0 - 9 $manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); The hash character (i.e. '#') at the beginning and end is the indicator for the beginning and end of the regex pattern.
-
Yeah, you want to be checking that the field is not empty. The isset() function does not do this. You should combine with another function like empty() or if you are using php < version 5.5 use the following <?php if(isset($_POST['submit'])) { if(!isset($_POST['name']) || trim($_POST['name']) == FALSE) { $nameerror = "<span class=\"feedback\">Please enter valid name</span>"; unset($_SESSION['name']); } else { $_SESSION['name'] = $_POST['name']; header('Location:page_2.php'); exit(); } } ?>
-
All this logic should come before any HTML output. I have cleaned up the code a bit. <?php session_start(); include 'mytool.php'; if(isset($_POST['myusername']) && isset($_POST['mypassword'])) { // username and password sent from form $myusername = $_POST['myusername']; $mypassword = $_POST['mypassword']; $host = 'localhost'; // Host name $username = 'root'; // Mysql username $password = ''; // Mysql password if(isset($_POST['tabs'])) { switch ($_POST['tabs']) { case 'students': $db_name = 'students'; // Database name $tbl_name = 'test'; // Table name $redirect = 'student/index.php'; break; case 'teachers': $db_name = 'managers'; // Database name $tbl_name = 'teachers'; // Table name $redirect = 'teachers/index.php'; break; case 'managers': $db_name = 'managers'; // Database name $tbl_name = 'employes'; // Table name $redirect = 'managers/index.php'; break; case'admin': $db_name = 'managers'; // Database name $tbl_name = 'moderator'; // Table name $redirect = 'admin/index.php'; break; } } else { die('Missing var: tabs'); } // Connect to server and select database. mysql_connect($host, $username, $password)or die("cannot connect"); $selected = mysql_select_db($db_name)or die("cannot select DB"); if(!$res = mysql_query("SET CHARACTER SET utf8;")) { die(mysql_error()); } if(!$res = mysql_query("SET SESSION collation_connection = 'utf8_persian_ci'")) { die(mysql_error()); } $sql = "SELECT * FROM " . $tbl_name . " WHERE username='" . $myusername . "' AND password='" . $mypassword . "'"; if(!$result = mysql_query($sql)) { die(mysql_error()); } if(mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); // not sure why you are not using the pk from the result set in your session var $_SESSION['mys'] = $myusername; header('Location:' . $redirect); exit(); } else { //back to login header('Location:index.php?cmd=error'); exit(); } } else { header('Location:index.php'); exit(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <link REL="SHORTCUT ICON" HREF="qeshmac.ico"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> </body> </html>
-
Is Responsive Design an inevitable component?
JonnoTheDev replied to mostafatalebi's topic in Miscellaneous
IMO, most browsers on mobile devices, tablets, etc can render most HTML pretty well regardless of it being responsive. I think it is down to the functionality that you require in the site. If you have a lot of navigation links or drop down lists, or hover elements then responsive design works well to remove some elements or move elsewhere when viewing on different devices. A lot of our clients who have older sites are asking for a responsive template as they have started using iPads, tablets, etc to view their website on and notice some things don't quite work too well. Our designer uses responsive templates from the get-go on new projects. A mobile site will not have all the functionality of a full blown website so sometimes it makes sense to have a mobile only version of the code-base. This can be done on a sub-domain as you have seen. You want to make a mobile version run as fast as possible as not all data networks are high speed. There will be other reasons for using sub-domains including traffic analysis, etc -
Did mention that there are better methods if php 5.3 is available