PHP - Optimizing Minor Php Script.
Hi
I have a small script, on a single file that needs to be optimized.
file is about 300 lines (16Kb), and basiccaly looks like the "PHP-monster" threw up on it.
Script is working ok, but surely could be much better.
PM if interested and I can send you a copy of file. If possible leave price/hourly rate.
Similar TutorialsHi I am trying to learn to clean coding and learning to clean old coding for any vulnerabilities. Can anyone help me with this code and see what I missed. I know theres a lot can anyone help so I can someday be able to do this myself easily please. Thanks for any and all help... Code: [Select] <? include("connect.php"); include("mail.php"); include("config.php"); function SendCounterMail($butlerstat1, $updatestat1) { $content1 = ''; $content1 .= "<font style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "</font><br>"."<br>". "<p align='center' style='font-size: 14px;font-family: Arial, Helvetica, sans-serif;font-weight:bold;'>Counter Information</p>". "<br>"."<table border='0' cellpadding='3' cellspacing='0' width='100%' align='center' class='style13'>"; if ( $butlerstat1 ) $content1 .= "<tr style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "<td>Butler file is not running so it is now running by this process.</td></tr>"; if ( $updatestat1 ) $content1 .= "<tr style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "<td>Records file is not running so it is now running by this process.</td></tr>"; $content1 .= "<tr style='font-size: 10px;font-family: Arial, Helvetica, sans-serif;color: #333333;'>". "<td>This mail is testing for check file running in.</td></tr></table>"; $subject = "Counter Information"; $from=$adminemailadd;//= "newuser@thissite.com"; $email = $adminemailadd; //SendHTMLMail($email, $subject, $content1, $from); } $butlerstat = FALSE; $updatestat = FALSE; $ressel = mysql_query("select referral_bids from auction_pause_management where id=3"); if ( mysql_num_rows($ressel) == 0 ) { mysql_free_result($ressel); mysql_query("Insert into auction_pause_management (referral_bids) values (1)"); $ressel = mysql_query("select referral_bids from auction_pause_management where id=3"); } $oldvalue1 = mysql_result($ressel, 0); mysql_free_result($ressel); $ressel = mysql_query("select referral_bids from auction_pause_management where id=4"); if ( mysql_num_rows($ressel) == 0 ) { mysql_free_result($ressel); mysql_query("Insert into auction_pause_management (referral_bids) values (1)"); $ressel = mysql_query("select referral_bids from auction_pause_management where id=4"); } $oldvalue = mysql_result($ressel, 0); mysql_free_result($ressel); sleep(2); $ressel = mysql_query("select referral_bids from auction_pause_management where id=3"); $newvalue1 = mysql_result($ressel, 0); mysql_free_result($ressel); $ressel = mysql_query("select referral_bids from auction_pause_management where id=4"); $newvalue = mysql_result($ressel, 0); mysql_free_result($ressel); //if ( $oldvalue1 == $newvalue1 ) { $output1 = exec("php ".getcwd()."/update_butler.php >/dev/null &"); $butlerstat = TRUE; //} //if ( $oldvalue == $newvalue ) { $output = exec("php ".getcwd()."/update_records.php >/dev/null &"); $updatestat = TRUE; //} //SendCounterMail($butlerstat, $updatestat); //mysql_close($db); ?> Code: [Select] <?php $query = 'SELECT COUNT(*) FROM `fonts`'; $result = mysql_query($query) or die('Sorry, we could not count the number of results: ' . mysql_error()); $numberofresults = mysql_result($result, 0); $numberofresults = $numberofresults + 1; /*** query the database ***/ $i=1; /*** loop over the results ***/ while($i<$numberofresults) { $querySelect1 = "SELECT * FROM fonts WHERE id='$i'"; $resultSelect1 = mysql_query($querySelect1); $row2 = mysql_fetch_array($resultSelect1); /*** create the options ***/ echo '<option value="'.$row2['id'].'"'; if ($row2['id']==$font){ echo "selected='selected'"; } echo '>'.$row2['font']. '</option>'."\n"; $i++; } ?> Currently my site is still underdevelopment and I was having trouble creating a dynamically driven drop down to select which font the user wanted out of the selection that are available. I managed to get this to work just for proof of concept so I could move onto other things. Any help on how to get this to work in a more efficient manner would be greatly appreciated. I have approximately 50k-100k files in a directory. I'm running a script to check if any of the files are being used by the DB, if not then delete them. The problem is that I have made a quick test on a directory of just 1k files and it dies. Is there a way to optimize it? I know the script works, it's just that it takes too long to run. Even with just 1k files. And I'm pretty sure is the is_dir that's taking its sweet time. Any ideas? <?php require_once 'db_connect.php'; $default_dir = "storage/2011/"; if(!($dp = opendir($default_dir))) die("Cannot open $default_dir."); while($file = readdir($dp)) { if(is_dir($file)) { continue; } else if($file != '.' && $file != '..') { $query = "SELECT * FROM images Where filename = '".$file."' OR thumbname = '".$file."'"; $dbResult = mysql_query($query); $num_rows = mysql_num_rows($dbResult); if ($num_rows == 0){ unlink($default_dir.$file); echo $file."<br />"; } } } closedir($dp); ?> I have created a form, that contains multiple text fields. When the user clicks on the Submit button, the form data should be populated in MySQL, I have programmed it in a way, that it works well, but the problem is, Since it contains so many text fields that collects the Manufacturer, Brand and so on repeatedly, I have created multiple queries to populate the DB. Here is the code, Code: [Select] <?php include("connect.php"); if (isset($_POST['confirm_order'])) { $o_manufacturer = trim(@$_POST['o_manufacturer']); $o_brand = trim(@$_POST['o_brand']); $o_type = trim(@$_POST['o_type']); $o_exp_date = trim(@$_POST['o_exp_date']); $o_qty = trim(@$_POST['o_qty']); $o_unit = trim(@$_POST['o_unit']); $o_unit_price = trim(@$_POST['o_unit_price']); $o_package = trim(@$_POST['o_package']); $o_package_price = trim(@$_POST['o_package_price']); $o_selling_price_perUnit = trim(@$_POST['o_selling_price_perUnit']); $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '$o_manufacturer', '$o_brand', '$o_type', '$o_exp_date', '$o_qty', '$o_unit', '$o_unit_price', '$o_package', '$o_package_price', '$o_selling_price_perUnit')"; $results = mysql_query($query); if ($results) { echo '<center><p class=small>Order updation successful, Click on LIST ORDERS button below to view the order entry.</p><br></center>'; echo '<center><a href="List_Orders.php" class="myButton">List Orders</a></center>'; } // Second Row Insertion if(!empty($_POST['o_manufacturer1'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer1']."' , '".$_POST['o_brand1']."' , '".$_POST['o_type1']."' , '".$_POST['o_exp_date1']."' , '".$_POST['o_qty1']."' , '".$_POST['o_unit1']."' , '".$_POST['o_unit_price1']."' , '".$_POST['o_package1']."' , '".$_POST['o_package_price1']."', '".$_POST['o_selling_price_perUnit1']."' )"; $results = mysql_query($query); } // Third Row Insertion if(!empty($_POST['o_manufacturer2'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer2']."' , '".$_POST['o_brand2']."' , '".$_POST['o_type2']."' , '".$_POST['o_exp_date2']."' , '".$_POST['o_qty2']."' , '".$_POST['o_unit2']."' , '".$_POST['o_unit_price2']."' , '".$_POST['o_package2']."' , '".$_POST['o_package_price2']."', '".$_POST['o_selling_price_perUnit2']."' )"; $results = mysql_query($query); } // Fourth Row Insertion if(!empty($_POST['o_manufacturer3'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer3']."' , '".$_POST['o_brand3']."' , '".$_POST['o_type3']."' , '".$_POST['o_exp_date3']."' , '".$_POST['o_qty3']."' , '".$_POST['o_unit3']."' , '".$_POST['o_unit_price3']."' , '".$_POST['o_package3']."' , '".$_POST['o_package_price3']."', '".$_POST['o_selling_price_perUnit3']."' )"; $results = mysql_query($query); } // Fifth Row Insertion if(!empty($_POST['o_manufacturer4'])) { $query = "INSERT INTO order_entry (o_sno, o_manufacturer, o_brand, o_type, o_exp_date, o_qty, o_unit, o_unit_price, o_package, o_package_price, o_selling_price_perUnit) VALUES ('', '".$_POST['o_manufacturer4']."' , '".$_POST['o_brand4']."' , '".$_POST['o_type4']."' , '".$_POST['o_exp_date4']."' , '".$_POST['o_qty4']."' , '".$_POST['o_unit4']."' , '".$_POST['o_unit_price4']."' , '".$_POST['o_package4']."' , '".$_POST['o_package_price4']."', '".$_POST['o_selling_price_perUnit4']."' )"; $results = mysql_query($query); } mysql_close(); } ?> Instead of posting the 'o_manufacturer ' value multiple times 'o_manufacturer1', 'o_manufacturer2', 'o_manufacturer3' and 'o_manufacturer4' I m looking for a code, that uses for loop or any other alternative ways that optimizes the code and works the proper way... NOTE : The file that i have attached is working 100% perfect, but I am looking for code optimization. Looking for help from experts.. Thanks a lot in advance... I've been searching for a science that will solve this analysis problem. Since I don't know what I'm looking for, I cannot properly express the task to accomplish.
I have an eCommerce store selling a product that has (let's keep it simple) three properties and each property can hold any one of three possible relevant values (or null).
Combinations: 3^3=27
A typical combination would be round/solid/blue, or cubic/squishy/white.
The task is to efficiently eliminate that part of the array if any particular {set of values} is null. That is, if I currently have no pink items, the relevant sections of the array would get eliminated.
Product variations with low n-values is easy to manually handle. But with five and above, that's the math(?) theory I am trying to know the name of.
(I wonder if any Matlab manuals would give a clue.)
I am trying this elimination of sections of an established array instead of rebuilding the array every time a value is locked in.
On the other hand, maybe I'm trying to be too smart about this and should just let the server do the grunt work over and over.
ok , this is to request someone to be your friend and i keep getting an error saying "mysql_error() expects parameter 1 to be resource" i dont know what is wrong , it worked before ... please help. Code: [Select] <?php if ($_POST["request"] == "requestFriendship") { $mem1 = preg_replace('#[^0-9]#i', '', $_POST['mem1']); $mem2 = preg_replace('#[^0-9]#i', '', $_POST['mem2']); // if (!$mem1 || !$mem2 || !$thisWipit) { echo 'Error: Missing data'; exit(); } // if ($mem1 == $mem2) { echo 'Error: You cannot add yourself as a friend'; exit(); } //See if already friends $sql1 = "SELECT id FROM friends WHERE mem2='$mem1' AND mem1='$mem2' LIMIT 1"; $result1 = mysql_query($sql1) or die (mysql_error("sql1 failed")); $data1 = mysql_fetch_row($result1); if ($data1[0]) { echo 'This member is already your Friend'; exit(); } //Check if user already requested to be friends $sql2 = "SELECT id FROM friends_requests WHERE mem1='$mem1' AND mem2='$mem2' Limit 1"; $result2 = mysql_query($sql2) or die (mysql_error("sql2 failed")); $data2 = mysql_fetch_row($result2); if ($data2[0]) { echo '<img src="images/round_error.png" width="20" height="20" alt="Error" /> You have a Friend request pending for this member. Please be patient.'; exit(); } //Check if friend already requested to be friends $sql3 = "SELECT id FROM friends_requests WHERE mem1='$mem2' AND mem2='$mem1' Limit 1"; $result3 = mysql_query($sql3) or die (mysql_error("sql3 failed")); $data3 = mysql_fetch_row($result3); if ($data3[0]) { echo '<img src="images/round_error.png" width="20" height="20" alt="Error" /> This user has requested you as a Friend already! Check your Requests on your profile.'; exit(); } //If still here make insert $mem1=mysql_real_escape_string($mem1); $mem2=mysql_real_escape_string($mem2); $sql = mysql_query("INSERT INTO friends (mem1, mem2, timedate) VALUES('$mem1','$mem2',now())") or die (mysql_error("Friend Request Insertion Error")); echo '<img src="images/round_success.png" width="20" height="20" alt="Success" /> Friend request sent successfully. This member must approve the request.'; exit(); } ?> Hi All, I have been handed a site from a friend of mine to fix as there were a few errors on it. I have only had very little experience with php coding and believe im doing well so far as i only have one more error to rectify on this particular site. Is any one familiar with the following error codes and how to resolve them? Warning: include(list_.inc.php) [function.include]: failed to open stream: No such file or directory in /home/user/public_html/list.php on line 13 Warning: include(list_.inc.php) [function.include]: failed to open stream: No such file or directory in /home/user/public_html/list.php on line 13 Warning: include() [function.include]: Failed opening 'list_.inc.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/user/public_html/list.php on line 13 Iv done a bit of research and to me it doesn't seem like a huge fix and i think its something i am capable of doing myself i just need a bit of guidance. Any help greatly appreciated. Michael I have a form with a table that contains ONLY dropdown menus for users to select quantities from 25 dinner items. It contains some Javascript, but nothing fancy. In an effort to establish my database and TEST to see how some PHP functions might respond so I could improve my form, I created a mini version of the db in MySQL. But when I click the submit button, the page blinks, the address bar fills with field names, but there is no connect. No error messages. No data transfer. NO NOTHING! I searched the web and copied a form and plugged it in (an html form, a php insert file, and a MySQL database) and it worked fine. I peared down my page to mirror it, and still, no success. What little detail am I missing?? If I have 25 fields but create a db for the first 6, should it function? If I reduce it and try to re-use the same db, am I persuing a problem? I've tried error trapping and changing the form inputs, but it just still doesn't connect. Please help! Hey guys im having 2 minor problems with my script if someone can give me some advise please?
(all 2 problems are commented on the script itself)
1. highlighting string characters when typed.
2. also im trying to add "Hide Suggestions" at the bottom of my menu so people can turn on/off autocomplete
$(document).ready(function() { function search_autocomplete(selector, tags, default_value) { $('#' + selector).focus(function() { if($('#' + selector).val() == default_value) { $('#' + selector).val(''); } }); $('#' + selector).blur(function() { if($('#' + selector).val() == '') { $('#' + selector).val(default_value); } }); $('#' + selector).autocomplete( { source: tags, timeout: 0, select: function (a, b) { $(this).val(b.item.value); //submit }, create: function () { $(this).data('ui-autocomplete')._renderItem = function (ul, item) { // not highlighting when string characters match var re = new RegExp('^' + this.term); var t = item.label.replace(re, "<span id='dropdown-item-highlight'>" + "$&" + "</span>"); return $('<li></li>') .append('<a>' + t + ' in ' + item.type + '</a>') .addClass( 'dropdown-item' ) .appendTo(ul); }; } }); $(this).data('ui-autocomplete')._renderMenu = function (ul, item) { // unable to show "Hide Suggestions at the bottom of the autocomplete menu return $('<ul></ul>') .append('<a>Hide Suggestions</a>') .addClass( 'dropdown-menu' ); }; } var availableTags = [{"label" : "XBOX 360", "type":"Electronics"}, {"label":"XBOX One", "type":"Electronics"}, {"label":"Nike", "type":"Clothing & Footwear"}]; search_autocomplete('query', availableTags, 'Search...'); });thanks Good day dear community. I need to build a function which parses the domain from a url. I have used various ways to parse html sources. But this one is is a bit tricky! See the target i want to parse - it has some invaild Markup: http://www.schulministerium.nrw.de/BP/SchuleSuchen?action=644.0013008534253&SchulAdresseMapDO=194190 well what do you think - can i apply this code here <?php require_once('config.php'); // call config.php for db connection $filename = "url.txt"; // Include the txt file which have urls $each_line = file($filename); foreach($each_line as $line_num => $line) { $line = trim($line); $content = file_get_contents($line); //echo ($content)."<br>"; $pattern = '/<td>(.*?)<\/td>/si'; preg_match_all($pattern,$content,$matches); foreach ($matches[1] as $match) { $match = strip_tags($match); $match = trim($match); //var_dump($match); $sql = mysqli_query("insert into tablename(contents) values ('$match')"); //echo $match; } } ?> well i have to rework the parser-part of this script. I need to parse somway different - since i have other site here. Can anybody help me here to get a better regex - or a better way to parse this site ... Any and all help will be greatly apprecaited. regards db1 I just installed this new script here http://webhost.pro/domain-check.php it's a basic domain availability tool. I am trying to make a form that can be used on any page forward to this page with the content. The page loads with this in the url webhost.pro/domain-check.php?domain=dwhs.net and will run the page. So I can make a form that just submits to that page and sends the details. I made this page for testing http://webhost.pro/test.html But no go, here is the code: <form id="search" action="/domain-check.php" method="GET"> <input type="text" name="s"> <a onClick="document.getElementById('search').submit()" class="button1">Search</a> <div class="clear"></div> </form> Thanks! Hi everyone! I've been working on a php script to replace links that contain a query with direct links to the files they would redirect to. Hi i have this upload script which works fine it uploads image to a specified folder and sends the the details to the database. but now i am trying to instead make a modify script which is Update set so i tried to change insert to update but didnt work can someone help me out please this my insert image script which works fine but want to change to modify instead Code: [Select] <?php mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("upload") or die(mysql_error()) ; // my file the name of the input area on the form type is the extension of the file //echo $_FILES["myfile"]["type"]; //myfile is the name of the input area on the form $name = $_FILES["image"] ["name"]; // name of the file $type = $_FILES["image"]["type"]; //type of the file $size = $_FILES["image"]["size"]; //the size of the file $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name $error =array(); // this an empty array where you can then call on all of the error messages $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values $location = 'images/'; //location of the file or directory where the file will be stored $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg //echo $extension = substr($name, 3); //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg // another way of doing is with explode // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode $myfile = $_POST["myfile"]; if (isset($image)) // if you choose a file name do the if bellow { // if extension is not equal to any of the variables in the array $allowed_exts error appears if(in_array($extension, $allowed_exts) === false ) { $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line } // if file type is not equal to any of the variables in array $image_type error appears if(in_array($type, $image_type) === false) { $error[] = 'Type of file not allowed! only images allowed<br />'; } // if file bigger than the number bellow error message if($size > 2097152) { $error[] = 'File size must be under 2MB!'; } // check if folder exist in the server if(!file_exists ($location)) { $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location; } } // if no error found do the move upload function if (empty($error)){ if (move_uploaded_file($temp, $location .$appendic_name)) { // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image mysql_query("INSERT INTO image (myfile ,image) VALUES ('$myfile', '$appendic_name')") ; exit(); } } else { foreach ($error as $error) { echo $error; } } //echo $type; ?> I'm having trouble echoing $year in my script. Listed below is the script, just below ,$result = mysql_query("SELECT * FROM $dbname WHERE class LIKE '%$search%'") or die(mysql_error());, in the script I try to echo $year. It doesn't show up in the table on the webpage. Everything else works fine. Any help wold be appreciated greatly. Thanks in advance. <?php include 'config2.php'; $search=$_GET["search"]; // Connect to server and select database. mysql_connect($dbhost, $dbuser, $dbpass)or die("cannot connect"); mysql_select_db("vetman")or die("cannot select DB"); $result = mysql_query("SELECT * FROM $dbname WHERE class LIKE '%$search%'") or die(mysql_error()); // store the record of the "" table into $row //$current = ''; echo "<table align=center border=1>"; echo "<br>"; echo "<tr>"; echo "<td align=center>"; ?> <div style="float: center;"><a><h1><?php echo $year; ?></h1></a></div> <?php echo "</td>"; echo "</tr>"; echo "</table>"; // keeps getting the next row until there are no more to get if($result && mysql_num_rows($result) > 0) { $i = 0; $max_columns = 2; echo "<table align=center>"; echo "<br>"; while($row = mysql_fetch_array($result)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; echo "<td align=center>"; ?> <div style="float: left;"> <div><img src="<?php echo $image1; ?>"></div> </div> <?php echo "</td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i > 0) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; echo '</tr>'; } mysql_close(); ?> </table> Hello, I stored a fsockopen function in a separate "called.php" file, in order to run it as another thread when it needs. The called script should return results to the "master.php" script. I'm able to run the script to get the socket working, and I'm able to get results from the called script. I tried for hours but I can't do the twice both My master.php script (with socket working): Code: [Select] <?php $command = "(/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR] &) > /dev/null"; $result = exec($command); echo ("result = $result\r\n"); ?> and my called.php script Code: [Select] #!/mnt/opt/usr/bin/php-cli -q <?php $device = $_SERVER['argv'][1]; $port = "8080"; $fp = fsockopen($device, $port, $errno, $errstr, 5); fwrite($fp, "test"); fclose($fp); echo ("normal end of the called.php script"); ?> In the master script, if I use Code: [Select] $command = "(/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR] &) > /dev/null"; the socket works, but I have nothing in $result (note also that I don't anderstand why the ( ... &) are needed!?) and if I use Code: [Select] $command = "/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR]"; I have the correct text "normal end of the called.php script" in $result but the socket connection is not performed (no errors in php logs) Could you help me to find a way to let's work the two features correctly together? Thank you. I'm trying to use this script known as SimpleImage.php that can be found here <a href="http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php">link</a> I'm trying to include what is on the bottom of the page to my existing script can anyone help me I've tried several ways but its not working. Code: [Select] <?php session_start(); error_reporting(E_ALL); ini_set('display_errors','On'); //error_reporting(E_ALL); // image upload folder $image_folder = 'images/classified/'; // fieldnames in form $all_file_fields = array('image1', 'image2' ,'image3', 'image4'); // allowed filetypes $file_types = array('jpg','gif','png'); // max filesize 5mb $max_size = 5000000; //echo'<pre>';print_r($_FILES);exit; $time = time(); $count = 1; foreach($all_file_fields as $fieldname){ if($_FILES[$fieldname]['name'] != ''){ $type = substr($_FILES[$fieldname]['name'], -3, 3); // check filetype if(in_array(strtolower($type), $file_types)){ //check filesize if($_FILES[$fieldname]['size']>$max_size){ $error = "File too big. Max filesize is ".$max_size." MB"; }else{ // new filename $filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type; // move/upload file $target_path = $image_folder.basename($filename); move_uploaded_file($_FILES[$fieldname]['tmp_name'], $target_path); //save array with filenames $images[$count] = $image_folder.$filename; $count = $count+1; }//end if }else{ $error = "Please use jpg, gif, png files"; }//end if }//end if }//end foreach if($error != ''){ echo $error; }else{ /* -------------------------------------------------------------------------------------------------- SAVE TO DATABASE ------------------------------------------------------------------------------------ -------------------------------------------------------------------------------------------------- */ ?> hey guys im really just after a bit of help/information on 2 things (hope its in the right forum).
1. basically I'm wanting to make payments from one account to another online...like paypal does...im wondering what I would need to do to be able to do this if anyone can shine some light please?
2.as seen on google you type in a query in the search bar and it generates sentences/keywords from a database
example:
so if product "chair" was in the database
whilst typing "ch" it would show "chair" for a possible match
I know it would in tale sql & json but im after a good tutorial/script of some sort.
if anyone can help with some information/sites it would be much appreciated.
Thank you
Well the subject line is pretty explicit. I found this script that uploads a picture onto a folder on the server called images, then inserts the the path of the image on the images folder onto a VACHAR field in a database table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> The script seems to work fine because I managed to upload a picture which was successfully inserted into my images folder and into the database. Now the problem is, I can't figure out exactly how to write the script that displays the image on an html page. I used the following script which didn't work. Code: [Select] //authenticate user //Start session session_start(); //Connect to database require ('config.php'); $sql = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($sql); $imagebytes = $row['image']; header("Content-type: image/jpeg"); print $imagebytes; Seems to me like I need to alter some variables to match the variables used in the insert script, just can't figure out which. Can anyone help?? How would I go about making it to where,, I can tell the script to use a certain extension of php in the script like curl.. ? Thanks |