43 Ways to Optimize your PHP Code. Build PDF files dynamically with PHP. Sometimes you need control over exactly how pages are rendered for printing. At times like those, HTML is not the best choice. PDF files give you complete control over how pages are rendered and how text, graphics and images are rendered on the page. Sadly, APIs for building PDF files are not standard parts of the PHP toolkit.
Now is the time to bring in a little help. Another choice is the Free PDF library (FPDF), which is native PHP. Listing 1. The root element for the XML is an events tag. Listing 2. getresults.php This script implements a getResults function that reads the XML file into a DOMDocument. To test that this script works, you will build an HTML export page that uses the getResults function to read the file, then outputs the data as a series of HTML tables.
Listing 3. Building the PDF With the data in hand, it's time to focus on building PDF files. Listing 4. This script is literally a "Hello World" but as a PDF instead of HTML. Listing 5. Building a results table. PHP & MySQL – Preventing MySQL Injection. Posted at Good PHP Tutorials by Ross Tanner In this tutorial I am going to explain what MySQL injection is and how important it is to prevent this attack on your database(s). It is vital that all security measures are in place before you make your website live because the effects can be devastating especially if you store sensitive data. Lets start with the basics and learn what MySQL injection is. What is MySQL injection? “MySQL injection is an attack technique used to exploit applications that construct SQL statements from user-supplied input.” This statement for me sums it up perfectly. How often does this attack occur?
It is diffult to estimate just how many websites are suffering from these attacks but it is really dependant on the level of coding. Can you show me an example of MySQL injection? MySQL injection is really very easy and anyone can do it. As you can see the database is queried for a record matching the username AND the password.
How do I prevent MySQL injection? How to Process Credit Cards with PayPal Payments Pro Using PHP | B-Creative. Namespaces With PHP. PHP namespaces was introduced in version 5.3. Namespaces is a way of group classes together into virtual directories, the main reason we would want to do this is to help avoid collision of class names in your application. In PHP you can not define two classes with the same name, if you do this PHP will display a fatal error in your application. Using namespaces means that you can define two classes with the same name as long as they are in different namespaces.
For example if you had two classes both named Table and both classes perform different tasks, one will be used to read a database table and the other will be used to display a HTML table. If these are not in namespaces then PHP will throw a class is already defined error, the old way of fixing this problem would be to prefix the class name with something unique. The database table class would now be called Database_Class and the HTML class will now be called Html_Class. Defining Namespaces Defining Sub Namespaces Using Namespaces. Formatted Strings With PHP. When you are using PHP to output a string on the page most of the time you will use the syntax echo, which will take the following string and display that string in HTML.
You can even concaternate multiple strings or variables together to be outputted by the echo syntax. Here is an example of using echo to output multiple options in a select box. As you can see from the echo syntax that you can create a HTML element by using PHP. This code uses a concatenated string to insert the variables into the value attribute and a title inside the option tag. This is quite easy to read and is fine to use in normal development but what if you were using this method to display a more complicated element with more attributes such as an image tag. This will create 5 image tags which will populate the a number of different attributes. The solution is to PHP built in functions sprintf() and printf() to create a formatted string to output in the HTML. This is how it will be used to display the image tag. Test Driven Development With PHP. 21 Really Useful & Handy PHP Code Snippets. Posted at WebDeveloper+ Contents Human Readable Random String This code will create a human readable string that will look more close to dictionary words, useful for captchas.
Generate a Random String If you don’t need human readable string, then use this function instead, which will create a random string you can use for user id’s etc. Encode Email Address With this snippet, you can encode any email address into HTML entities so that spam bots do not find it. Validate email Address E-mail validation is perhaps the most used validation in web forms, this code will validate email address and also optionally check the MX records of the domain provided in email address to make email validation more robust. List Directory Contents Destroy Directory Delete a directory including its contents. Parse JSON Data With most of the popular web services like Twitter providing their data through APIs, it is always helpful to know how to parse API data which is sent in various formats including JSON, XML etc. Creating web services using PHP. Posted at Web Developing using Open Source Technologies by Mohammed Diab What is web service?
First of all I want to explain or define what is web service. You can think of web services as DLL files over the web. You write the code, then compile it and every one can use it whatever language they are using. But in the web you don’t compile anything. Actually when I started using webservices, I was writing c# code so .NET was doing every thing for me. I couldn’t understand what is happening behind the scene. First you have to define what you are serving. You can consider SOAP as a waiter in a restaurant. What do you need? PHP and SOAP. Creating your first web service We are going to create a web service for a library, where users can search for authors, books, browse each author’s books etc.
Creating the WSDL file I’m going now to create the WSDL file “menu”. The BookData class: The AuthorData class: Now I am going to create wrapper classes. Book class: Author Class: library.php index.php. Create a Photo Admin Site Using PHP and jQuery. Posted at Nettuts+ by Jeffrey Way I’m pleased to present you with part one of a two part series on creating a photo site using PHP, jQuery and AJAX. Originally, I intended to fit the entire tutorial into one screencast, but that quickly became a pipe dream as I realized that there was simply too much to cover. Nevertheless, even if you only watch this first video, you should learn a great deal. We’ll be retrieving images from a database, creating a simple login form with authentication and will then allow for our database to be asynchronously updated. Sounds good? If so, let’s get into it.
Our goal For this lesson, our goal is to create a photo admin section where an administrator can retrieve photos from a database and update the title of his photos simply by clicking on the appropriate text. Creating our tables with MySQL Open PHPMyAdmin and create a database called "db". Photos Rather than hard-coding our images into our document, we’ll store them in a database. Users Querying the database. PHP: The Right Way. Php Scripts :: Hot php Scripts. List of Videos for PHP.
How to Create a PHP/MySQL Powered Forum from Scratch. In this tutorial, we're going to build a PHP/MySQL powered forum from scratch. This tutorial is perfect for getting used to basic PHP and database usage. Let's dive right in! It's always a good idea to start with creating a good data model when building an application. Let's describe our application in one sentence: We are going to make a forum which has users who create topics in various categories. Other users can post replies. CategoriesTopicsPosts These three objects are related to each other, so we'll process that in our table design. Looks pretty neat, huh? I'll discuss each table by explaining the SQL, which I created using the scheme above. The CREATE TABLE statement is used to indicate we want to create a new table, of course. "A primary key is used to uniquely identify each row in a table. " The type of this field is INT, which means this field holds an integer.
There is a user called John Doe. All the other tables have got primary keys too and they work the same way. Replace: Making a site admin page in PHP. PHP & MySQL For Dummies Cheat Sheet. Cheat Sheet When writing PHP programs to create your Web database application and communicate with a MySQL database, you have many things to remember. You must spell code correctly and use perfect syntax. This Cheat Sheet provides a reference for quickly looking up the correct syntax for the code you use most frequently. Use PHP Statements to Create Programs PHP programs are a series of PHP statements, executed one at a time. Here’s a list of the PHP statements (with syntax) that you use when writing PHP programs: Communicate with a Database through PHP MySQL Functions PHP communicates with MySQL databases by using a set of functions developed specifically for this purpose.
Mysqli_connect("host","accnt","passwd")mysqli_select_db($cxn, "dbname",)mysqli_query($cxn,"query")mysqli_fetch_assoc($result)mysqli_num_rows($result)mysqli_insert_id($cxn) Make MySQL Database Changes with the ALTER Query The ALTER query is used to change the structure of a MySQL database. WHERE exp AND|OR exp AND|OR exp… PHP MySQL Web Development Security Tips. We are closing down our forums, it’s time to move on, but we are keeping some important threads, here is one… I read about many of these points in books and tutorials but I was rather lazy to think about many of them initially learned some of these lessons the hard way. Fortunately I didn’t lose any major data over security issues with PHP MySQL, but my suggestion to everyone who is new to PHP is to read these tips and apply them *before* you end up with a big mess.
If you are expecting an integer call intval() (or use cast) or if you don’t expect a username to have a dash (-) in it, check it with strstr() and prompt the user that this username is not valid. Here is an example: $post_id = intval ( $_GET [ 'post_id' ] ) ; mysql_query ( "SELECT * FROM post WHERE id = $post_id " ) ; Now $post_id will be an integer for sure JavaScript validation is only good to reduce the server load. Use mysql_real_escape_string() to escape the user input. Then you can use it like this: deny from all Thanks! Next and Previous Posts With Thumbnails. Media rich content is engaging content, right? And giving readers an opportunity to browse through posts linearly is one good way to keep them at your site reading longer, right?
So why just give them a title? This quick tip will give you the programming you need to include the post thumbnail and the date of the next and previous posts. Styling is left up to you. Check for the Previous and Next Posts These two variables will get the previous and next posts if they exist. Output the Thumbnails and Other Stuff This code will go into your single.php template. A generically labeled "Previous/Next" linkThe post thumbnail wrapped in a link to the postThe title in an h2 and wrapped in a link to the postand the date Conclusion Once you have this set up with the styling that you prefer you can do any number of things with the post information.
Building Your First Simple CMS. The Magic of PHP + MySQL It’s safe to say that nearly every website that’s up-to-date these days is using some form of content management system (CMS). While there are a ton of great free options that provide us with a CMS to power a website (WordPress, Drupal, etc.), it doesn’t hurt to peek under the hood and get a feel for how these systems work. To get our feet wet as back-end developers, we’ll be creating a simple PHP class that will: Create a databaseConnect to a databaseDisplay a form with two fieldsSave the form data in the databaseDisplay the saved data from the database Download Files This class is intended to give you a feel for how PHP and MySQL interact together, and to show the basics of a CMS.
I’ll be skipping explanations of some of the very basic programming stuff, so if at any point you feel lost, checkout the course Diving into PHP and give yourself a crash-course in PHP. Building the Class As you can see, we’re creating one class with four variables and five methods. <! <? Backup Your MySQL Database Using PHP. One of the most important tasks any developer needs to do often is back up their MySQL database. In many cases, the database is what drives most of the site. While most web hosts do a daily backup of a customer's database, relying on them to make backups and provide them at no cost is risky to say the least.
That's why I've created a database backup function that I can call whenever I want -- including nightly CRONs. The PHP & MySQL Code Of course, you'll need to provide database credentials to the function, as well as an array of tables you'd like to backup. If you provide a "*" or no tables, a complete database backup will run. The script does the rest! Never take chances when your website is on the line. Be Heard Tip: Wrap your code in <pre> tags or link to a GitHub Gist! Older Same Site, New Theme Newer PHP / MooTools 1.2 Accordion Helper. FPDF Library. How to Connect to a Database with PDO. We've covered PHP's PDO API a couple of times here on Nettuts+, but, generally, those articles focused more on the theory, and less on the application. This article will fix that! To put it plainly, if you're still using PHP's old mysql API to connect to your databases, read on!
What? It's possible that, at this point, the only thought in your mind is, "What the heck is PDO? " mysqlmysqli - MySQL Improvedpdo - PHP Data Objects The traditional mysql API certainly gets the job done, and has become so popular largely due to the fact that it makes the process of retrieving some records from a database as easy as possible. Yes, the code above is fairly simple, but it does come with its significant share of downsides. PDO, or PHP Data Objects, provides a more powerful API that doesn't care about the driver you use; it's database agnostic.
How? When I was first learning about the PDO API, I must admit that it was slightly intimidating. Connect Errors That's better! Fetch Query Prepared Statements Update. Creating a Flat-File Blog Engine Using Slim. In this article, we will learn how to create a flat file blog engine in PHP using the Slim framework. If you don't understand the jargon, don't worry. We're simply going to create a spartan blogging application, which utilizes text files instead of a database to store data.
If you're a beginner, fret not! We will start with the basics of using Slim. Let's get started after the jump! Introduction Slim is a light weight RESTful PHP framework for creating simple websites. Step 1: Getting Started To get started, let's set up a hello world application. Slim/ - Slim frameworkIndex.php - The index file .htaccess - For URL rewriting Now open up index.php, where you will see a bunch of HTML inside the following section. I've created a Virtualhost in my machine which is the URL shown in the screenshot. Navigate to the URL and you'll see a home page with the text "Hello world" in it.
Step 2: Render a PHP Page The next step is to render a PHP file. Let's create an about page for our blog. Excellent! Automatic Face Detection in Photos with PHP. Practical PHP Programming.