PHP - Adding Text To Image Script
So its a virtual pet script I'm making.
This script changes the image of the pet with time. It also puts the user's name,in text on the image. For some reason It doesnt turn out too well= http://amiteka.comli.com/viewpet_forum.php?id=1 Can someone tell me what is wrong with the script or how I can make it show something like; Error on line # <?php require_once('./inc/config.php'); function greaterDate($dformat, $beginDate, $endDate) { $subtract = $endDate - $beginDate; if($subtract > 0) { return 1; } else { return 0; } } function check(){ $pid = mysql_real_escape_string($_GET['id']); $result = mysql_query("SELECT * FROM `pets_adopted` WHERE `id` = '{$pid}'"); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $results = mysql_query("SELECT * FROM `pets_list` WHERE `id` = '{$row [petid]}'"); $pet = mysql_fetch_array($results); $results2 = mysql_query("SELECT * FROM `users` WHERE `id` = '{$row [adopter]}'"); $usercc = mysql_fetch_array($results2); if(greaterDate(".", $row[fulldate], date('Ymd')) > 0) { $im = showpet_forum($pet[adulturl]); $image = imagecreatefrompng($im); return imagepng($image); header('Content-type: image/png'); } elseif(greaterDate(".", $row[halfdate], date('Ymd')) > 0 && greaterDate (".", $row[fulldate], date('Ymd')) <= 0){ $im = showpet_forum($pet[teenurl]); $image = imagecreatefrompng($im); return imagepng($image); header('Content-type: image/png'); } elseif(greaterDate(".", $row[halfdate], date('Ymd')) <= 0){ $im = showpet_forum($pet[babyurl]); $image = imagecreatefrompng($im); return imagepng($image); } } } echo check(); ?> Thank you for any help. Similar TutorialsI am looking for a dynamic image script that handles word wrapping and possible font resizing. Basically, I have a dimensions, a font and a company name. So, lets say I am trying to make a 300x300 image for Bob's Boats in verdana. I want a script that not only creates the image, but tries to use up the available space (putting each word on a line, using a large font, horizontally and vertically aligning everything) Worst case I'll write my own, but the algorithm seems pretty complex. For example, lets say the companies name was: Chocolates in a Basket, it could be: Chocolates in a Basket Or: Chocolates in a Basket But never: Chocolates in a Basket Worst case, I might make it so that it supports 3 lines, but only ever puts the company name on 2 by default, and if the user wants to manually change it, they can. Even that isn't perfect though, because if the dimensions are something like 300x35, you wouldn't want a second line, let alone a 3rd. 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?? Hi, I've read a lot of places that it's not recommended to store binary files in my db. So instead I'm supposed to upload the image to a directory, and store the link to that directory in database. First, how would I make a form that uploads the picture to the directory (And what kinda directories are we talking?). Secondly, how would I retrieve that link? And I guess I should rename the picture.. I'd appreciate any help, or a good tutorial (Haven't found any myself). I have been getting a lot of bots spamming this script, and need to add captcha to it. I am new to php and was wondering if someone would help me with this issue. Below is the script, and I really would appreciate the help. Code: [Select] <?php include "admin/conf.php"; $setting1="SELECT * FROM ".$prefix."settings"; $setting2=mysql_query($setting1) or die("Sorry, Could not select sites table"); $setting=mysql_fetch_array($setting2); include "lang/$setting[lang]/main.php"; print "<title>$lang_reg1</title>"; print "<link rel='stylesheet' href='skin/$setting[style]/style.css' type='text/css'>"; print "<body bgcolor='#FFFFFF'>"; print "<table cellpadding='0' cellspacing='0' align='center' class='outtable'><tr><td>"; /*----------------- Bread ------------------*/ print "<br /><table><tr><td width='100%'><a href='index.php'>$setting[title]</a> > $lang_reg4</td></tr></table><br />"; /*----------------- Bread End ------------------*/ print "<table cellpadding='0' cellspacing='0' align='center' width='100%'><tr><td valign='middle'><img src='skin/$setting[style]/images/pen.gif' style='vertical-align: middle;'></td> <td valign='middle'>$lang_reg1</td></tr></table>"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/cat_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_left.gif' style='vertical-align: middle;'></td> <td class='tilecat' width='100%'><img src='skin/$setting[style]/images/tile_back.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/cat_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td class='shadowL'><img src='skin/$setting[style]/images/left_shadow.gif' style='vertical-align: middle;'></td> <td width='100%'>"; print "<form name='topsite' action='source/reguser.php' method='post' onSubmit='return check_it();'>"; print "<table cellspacing='0' cellpadding='2' align='center' class='maintable'>"; print "<tr><td colspan='2' class='titlemedium' style='padding: 3px;' align='center'>$lang_reg4</td></tr>"; print "<tr><td class='tileshadow' colspan='2' align='center'><img src='skin/$setting[style]/images/spacer.gif' width='1' height='3' alt='' /></td></tr>"; print "<tr class='row5'><td nowrap valign='top'>$lang_reg5</td>"; print "<td><input type='text' name='topsiteuser' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg6</td>"; print "<td><input type='password' name='password' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg7</td>"; print "<td><input type='text' name='email' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg8</td>"; print "<td><input type='text' name='title' size='60'></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg9</td>"; print "<td><input type='text' name='url' size='60' value=''></td></tr>"; print "<tr class='row5'><td valign='top'>$lang_reg10</td>"; print "<td><input type='text' name='button' size='60' value=''> <a href=\"javascript:void(window.open('http://www.imageshack.us/iframe.php?txtcolor=111111&type=blank&size=30','','height=100,width=275,left=0,top=0,toolbar=0,scrollbars=0'))\" target=\"_self\"><font face=\"Arial\" size=\"1\">UPLOAD HERE</font></a></td></tr>"; $selects="SELECT * FROM ".$prefix."categories where 1"; $selects2=mysql_query($selects) or die("Sorry, Could not select"); $selects3=mysql_fetch_array($selects2); if($selects3[ID]<1) {print"";}else { print "<tr class='row5'><td valign='top'>$lang_reg11</td>"; $selectcategory="SELECT * FROM ".$prefix."categories"; $selectcategory2=mysql_query($selectcategory) or die("Sorry, Could not select category"); print "<td><select name='catname'>"; $selectcategory="SELECT * FROM ".$prefix."categories"; $selectcategory2=mysql_query($selectcategory) or die("Sorry, Could not select category"); while($selectcategory3=mysql_fetch_array($selectcategory2)) {print "<option>$selectcategory3[catname]</option>";} print "</select></td></tr>";} print "<tr class='row5'><td width='40%' valign='top'>$lang_reg13<br>$lang_reg12</td>"; print "<td width='60%' ><textarea name='description' rows='5' cols='50'></textarea></td></tr>"; print "</table><br /><br />"; print "</td> <td class='shadowR'><img src='skin/$setting[style]/images/right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print"<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/mainfoot_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_left.gif' style='vertical-align: middle;'></td> <td class='footer' width='100%'><img src='skin/$setting[style]/images/mainfoot.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/mainfoot_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table><br />"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/cat_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_left.gif' style='vertical-align: middle;'></td> <td class='tilecat' width='100%'><img src='skin/$setting[style]/images/tile_back.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/cat_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/cat_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print "<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td class='shadowL'><img src='skin/$setting[style]/images/left_shadow.gif' style='vertical-align: middle;'></td> <td width='100%'>"; print "<table cellspacing='0' cellpadding='2' align='center' class='maintable'>"; print "<tr><td class='titlemedium' style='padding: 3px;' align='center'>$lang_rul</td></tr>"; print "<tr><td class='tileshadow' align='center'><img src='skin/$setting[style]/images/spacer.gif' width='1' height='3' alt='' /></td></tr>"; print "<tr class='row5'><td nowrap valign='top' align='center'><textarea cols='60' rows='10'>$setting[rules]</textarea></td></tr>"; Print"<tr><td class='subs' colspan='2' align='center'><input type='submit' name='submit' value='$lang_agree'></td></tr></table></form>"; print "</td> <td class='shadowR'><img src='skin/$setting[style]/images/right_shadow.gif' style='vertical-align: middle;'></td> </tr></table>"; print"<table cellspacing='0' cellpadding='0' width='100%' align='center'><tr> <td><img src='skin/$setting[style]/images/mainfoot_left_shadow.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_left.gif' style='vertical-align: middle;'></td> <td class='footer' width='100%'><img src='skin/$setting[style]/images/mainfoot.gif' style='vertical-align: middle;'></td> <td><img src='skin/$setting[style]/images/mainfoot_right.gif' style='vertical-align: middle;'></td><td><img src='skin/$setting[style]/images/mainfoot_right_shadow.gif' style='vertical-align: middle;'></td> </tr></table><br />"; print "<table width='100%' border='0' cellspacing='0' cellpadding='0'> <tr><td colspan='$cols' nowrap style='padding: 3px;' id='runtime' ><div><span><center>$setting[magic]</center></span></div></td></tr></table>"; print "</td></tr></table>"; ?> I need help adding a feature to the following php script that goes through folders and reads from txt files. Right now it is just grabbing the sub folder name, title and body and exporting it to a csv in columns A B and C respectively. What I need it to do is grab a summary from each txt file as well and added to the 4th column in the csv. I think the best way to do this would be to grab from the beginning of the body, to pre-defined closing }. So If I set it at 25 it will end the summary on the 25th } found in the txt file from the beginning of the body. All the txt is in spintax format like "The {Fox|Bird|Cat} {Stole|Took} The {Food|Water}" Code: [Select] <?php set_time_limit(0); // set unlimited execution time $base_folder = $_POST['base_folder']; $article_to_capture = (int)$_POST['article_to_capture']; $words = explode(',', $_POST['words']); // print_r($words); die(''); if(!is_dir($base_folder)) die('Invalid base folder. Please go <a href="step1.php"><strong>back</strong></a> and enter correct folder.'); ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Artcle Scraper Step 2</title> <style type="text/css"> <!-- body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; } --> </style> </head> <body> <h2>Step 2 : Processing the content of the folder. </h2> <table width="100%" border="0" cellpadding="2" cellspacing="1" bgcolor="#CCCCCC"> <tr bgcolor="#FFFFFF"> <th width="10%"> </td> <th width="30%">BASE FOLDER NAME</td> <th width="50%"> <?php echo $base_folder;?></td> <th width="10%"> </td> </tr> <?php $subfolder_arr = scandir($base_folder); //print_r($arr1); $total_subfolders = sizeof($subfolder_arr); $subfolder_count = 0; $file_count = 0; $report = ""; $fp = fopen('articles.csv', 'w+'); for($i=0; $i< $total_subfolders; $i++){ $file_name = $subfolder_arr[$i]; if($file_name=='.'||$file_name=='..') continue; $sub_folder_name = $base_folder ."\\". $file_name; $file_type = is_dir($sub_folder_name) ? 'dir' : 'file'; if($file_type=='dir'){ $sub_folder_count++; $rpeort .= "Processing folder $sub_folder_count $sub_folder_name \r\n"; $msg = "Processing folder $sub_folder_count $sub_folder_name \r\n"; ?> <tr bgcolor="#FFFFFF"><td> </td><td colspan="2"> <?php echo $msg;?> </td><td> </td></tr> <tr bgcolor="#FFFFFF"><td> </td><td colspan="2"> <table width="90%" cellpadding="0" cellspacing="0" border="1" bordercolorlight="#0000FF"> <?php // process sub folder $column1 = $file_name; $column2 = '{'; $column3 = '{'; $first = true; $files_arr = scandir($sub_folder_name); $article_processed =0; // article_processed in current sub folder foreach($files_arr as $key=>$val){ if(is_file($sub_folder_name.'\\'.$val) ) { if( substr($val,-4)=='.txt' && (filesize($sub_folder_name.'\\'.$val) <= 35000) && (filesize($sub_folder_name.'\\'.$val) >= 4000)) //file is > 1kb { $size = filesize($sub_folder_name.'\\'.$val); $article_processed++; if($article_to_capture==0 || $article_processed <= $article_to_capture ){ if($first==true) $first=false; else { $column2 .= '|'; $column3 .= '|'; } // read file get title and body $file_content = file($sub_folder_name.'\\'.$val); $file_title = rtrim($file_content[0]); $file_content[0] = ''; $file_arr_size = sizeof($file_content); $words_arr_size = sizeof($words); $t=1; while($t < $file_arr_size){ $file_content[$t] = rtrim($file_content[$t]); //echo $file_content[$t]; //die('inside'); if( $words_arr_size>0 ){ //die('inside'); $temp = str_replace($words, "", $file_content[$t]); $file_content[$t] = $temp; } $t++; //if($t>=3) die('aa'); } $file_body = implode('',$file_content); $column2 .= $file_title; $column3 .= $file_body; ?> <tr><td> <?php //print_r($files_arr); echo $val ."\r\n"; echo round(($size / 1024), 2).' KB'; ?> </td></tr> <?php } //end if .txt } // article processed } // end if is_file } // end foreach ?> </table> </td><td> </td></tr> <?php $column2 .= '}'; $column3 .= '}'; // write to csv / excel file $erro = fputcsv ($fp, array($column1,$column2,$column3) ); } //end if filetype else{ } } // end for fclose($fp); ?> <tr bgcolor="#FFFFFF"> <td> </td> <td colspan=""> File Generated. Download it <a href="articles.csv" target="_blank">HERE</a></td> <td> </td> </tr> </table> </body> </html>
Hello! I found this code from github. https://github.com/gburtini/Learning-Library-for-PHP and I want to know if its possible to add variables to it and what changes needed to be done to the whole script. $xs and $ys I want replace them and add two more. The whole code is he <?php require_once 'function.php'; function ll_nn_predict($xs, $ys, $row, $k) { $distances = ll_nearestNeighbors($xs, $row); $distances = array_slice($distances, 0, $k); $predictions = array(); foreach($distances as $neighbor=>$distance) { $predictions[$ys[$neighbor]]++; } asort($predictions); return $predictions; } function ll_nearestNeighbors($xs, $row) { $testPoint = $xs[$row]; $distances = _ll_distances_to_point($xs, $testPoint); return $distances; } function _ll_distances_to_point($xs, $x) { $distances = array(); foreach($xs as $index=>$xi) { $distances[$index] = ll_euclidean_distance($xi, $x); } asort($distances); array_shift($distances); return $distances; } and the function.php that is required is this: <?php function ll_transpose($rows) { $columns = array(); for($i=0;$i<count($rows);$i++) { for($k = 0; $k<count($rows[$i]); $k++) { $columns[$k][$i] = $rows[$i][$k]; } } return $columns; } function ll_mean($array) { return array_sum($array)/($array); } function ll_variance($array) { $mean = ll_mean($array); $sum_difference = 0; $n = count($array); for($i=0; $i<$n; $i++) { $sum_difference += pow(($array[$i] - $mean),2); } $variance = $sum_difference / $n; return $variance; } function ll_euclidean_distance($a, $b) { if(count($a) != count($b)) return false; $distance = 0; for($i=0;$i<count($a);$i++) { $distance += pow($a[$i] - $b[$i], 2); } return sqrt($distance); } I just want to know where is the variables in those 2 scripts and add more as I'm not well versed in using PHP. Thank you! I found a newsletter script called 'easy newsletter' which allows me to set up a page for users to sign up to a news letter emailing list. There is then another page that a admin can log into and create a simple text email to send out to everyone that has signed up. My problems is i require the email to include a attachment and have no clue how i can add this to the script to get it working. Can anyone help me? The script that sends out the email is included below if this helps: <?php //load configuration require("config.php"); //connect to database @mysql_connect($db_server,$db_user,$db_password) or die("Database server connection failed. Check variables \$db_server, \$db_user and \$db_password in config.php"); @mysql_select_db($db_name) or die("Selecting database failed. Check variable \$db_name in config.php"); //print header echo $header; ?> <h1><?php echo $title; ?> - Administration</h1> <hr> <?php $pwd = $_GET["pwd"]; //simple login if(isset($pwd) && ($pwd == $password)){ $submit = $_POST["submit"]; $submit_newsletter = $_POST["submit_newsletter"]; $del = $_GET["del"]; //insert new address if(isset($submit)){ $name = $_POST["name"]; $email = $_POST["email"]; @mysql_query("INSERT INTO $db_table (email,name) VALUES ('$email','$name');"); //error occurred if(@mysql_error()){ ?><p>Inserting entry failed: <?php echo @mysql_error(); ?></p> <p><a href="javascript&#058;history.back();">Click here to go back.</a></p><?php //successful }else{ ?><p>Entry has been inserted successfully. <a href="admin.php?pwd=<?php echo $pwd; ?>">Click here to continue.</a></p><?php } //delete an entry }else if(isset($del)){ @mysql_query("DELETE FROM $db_table WHERE id=$del;"); //error occurred if(@mysql_error()){ ?><p>Deleting entry failed: <?php echo @mysql_error(); ?></p> <p><a href="javascript&#058;history.back();">Click here to go back.</a></p><?php //successful }else{ ?><p>Entry has been deleted successfully. <a href="admin.php?pwd=<?php echo $pwd; ?>">Click here to continue.</a></p><?php } //send newsletter }else if(isset($submit_newsletter)){ $sent = 0; $result = @mysql_query("SELECT name,email FROM $db_table ORDER BY email ASC;"); $subject = $_POST["subject"]; $message = $_POST["message"]; ?><p>Sending emails to ...</p> <ul><?php //send emails one by one while($row=@mysql_fetch_array($result)){ $name = $row["name"]; $email = $row["email"]; ?><li><?php echo $name; ?> (<?php echo $email; ?>) ... <?php if(@mail($email,$subject,$message,"From: $admin <$admin>\n")){ ?>sent<?php $sent++; }else{ ?>failed<?php } ?></li><?php } ?></ul> <p><strong><?php echo $sent; ?> emails sent.</strong> <a href="admin.php?pwd=<?php echo $pwd; ?>">Click here to continue.</a></p><?php //print forms }else{ ?><h2>Send newsletter</h2> <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>?pwd=<?php echo $pwd; ?>"> <table> <tr> <td>Subject:</td> <td><input type="text" name="subject" class="fixedwidth"></td> </tr> <tr> <td valign="top">Message:</td> <td><textarea name="message" cols="60" rows="20" class="fixedwidth"><?php echo $signature; ?></textarea></td> </tr> <tr> <td> </td> <td><input type="submit" name="submit_newsletter" value="Send"></td> </tr> </table> </form> <h2>Add an email address</h2> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>?pwd=<?php echo $pwd; ?>" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" name="name" value="" maxlength="255"></td> </tr> <tr> <td>Email address:</td> <td><input type="text" name="email" value="" maxlength="255"></td> </tr> <tr> <td> </td> <td><input type="submit" name="submit" value="Submit"></td> </tr> </table> </form> <h2>Email addresses</h2> <table cellpadding="5" cellspacing="2"> <tr class="header"> <td><strong>Name</strong></td> <td><strong>Email address</strong></td> <td> </td> </tr> <?php $result = @mysql_query("SELECT * FROM $db_table ORDER BY email ASC;"); $colored = false; while($row=@mysql_fetch_array($result)){ $colored = !$colored; ?><tr<?php if($colored){ ?> class="colored"<?php } ?>> <td width="200"><?php echo $row["name"]; ?></td> <td width="200"><?php echo $row["email"]; ?></td> <td><a href="<?php echo $_SERVER["PHP_SELF"]; ?>?pwd=<?php echo $pwd; ?>&del=<?php echo $row["id"]; ?>">remove</a></td> </tr><?php } ?> </table> <?php } }else{ //print login form echo $login; } //print link to news ?><p align="right"><a href="index.php">Newsletter</a></p><?php //print footer echo $footer; //close database connection @mysql_close(); ?> Hi,
I am developing a web application which will be comprised of three columns: (1) Search form, (2) Image gallery, (3) Image details. The site is going to be more like html framesets, but research reveals that framesets are not favourable due to many reasons. I however found an alternative that I want to use instead of html framesets http://www.ironspide...smartframes.htm
I thought it would be easy for me to add rows which should serve as a page header, but I was wrong. I tried adding
document.write('<frameset rows="17%,*" frameborder="no">');
to this part of the code, but row apeared in a wrong place at the bottom:
// Writes frameset document.write('<frameset rows="17%,*" frameborder="no">'); document.write('<frameset cols="25%,75%" frameborder="no">'); document.write('<frame src="' + menuURL + '" name="menu">'); document.write('<frame src="' + contentURL + '" name="content" marginheight="15" marginwidth="50" scrolling="yes">'); // -->The original script for the index.html page is as follows: <!-- /* SmartFrames - Author: Robert Darrell - http://www.ironspider.ca/ */ // Defines variables // REPLACE menu.htm WITH YOUR MENU PAGE // REPLACE page1.htm WITH YOUR INITIAL CONTENT PAGE menuURL = "menu.htm"; contentURL = "page1.htm"; reloadURL = parent.document.URL; orphanURL = reloadURL.substring(reloadURL.indexOf('?')+1, reloadURL.indexOf('&')); frameName = reloadURL.substring(reloadURL.indexOf('&')+1, reloadURL.length); // Reassigns variable according to frame name passed by orphan if (frameName == "menu") { menuURL = orphanURL; } else if (frameName == "content") { contentURL = orphanURL; } // Writes frameset document.write('<frameset cols="25%,75%" frameborder="no">'); document.write('<frame src="' + menuURL + '" name="menu">'); document.write('<frame src="' + contentURL + '" name="content" marginheight="15" marginwidth="50" scrolling="yes">'); // --> </script> <!-- Use the noframes section to help search engines index your site --> <noframes>THIS WEBSITE IS ABOUT...<br><br> <a href="menu.htm">Site Menu</a> </noframes> </frameset>I hope someone will help. Regards. joseph Can someone help me add a filter to my script that reads txt files from subfolders, I want it to only read txt files that are <= a certain KB size Code: [Select] 1.<?php 2.set_time_limit(0); // set unlimited execution time 3. 4. 5.$base_folder = $_POST['base_folder']; 6.$article_to_capture = (int)$_POST['article_to_capture']; 7. 8.$words = explode(',', $_POST['words']); 9. 10. 11.// print_r($words); die(''); 12. 13. 14.if(!is_dir($base_folder)) 15. die('Invalid base folder. Please go <a href="step1.php"><strong>back</strong></a> and enter correct folder.'); 16. 17.?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 18.<html> 19.<head> 20.<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 21.<title>Artcle Scraper Step 2</title> 22.<style type="text/css"> 23.<!-- 24.body { 25. font-family: Verdana, Arial, Helvetica, sans-serif; 26. font-size: 12px; 27. color: #333333; 28.} 29.--> 30.</style> 31.</head> 32. 33.<body> 34.<h2>Step 2 : Processing the content of the folder. </h2> 35.<table width="100%" border="0" cellpadding="2" cellspacing="1" bgcolor="#CCCCCC"> 36. <tr bgcolor="#FFFFFF"> 37. <th width="10%"> </td> 38. <th width="30%">BASE FOLDER NAME</td> 39. <th width="50%"> <?php echo $base_folder;?></td> 40. <th width="10%"> </td> 41. </tr> 42.<?php 43. 44.$subfolder_arr = scandir($base_folder); 45. 46.//print_r($arr1); 47. 48.$total_subfolders = sizeof($subfolder_arr); 49.$subfolder_count = 0; 50.$file_count = 0; 51.$report = ""; 52. 53.$fp = fopen('articles.csv', 'w+'); 54. 55.for($i=0; $i< $total_subfolders; $i++){ 56. $file_name = $subfolder_arr[$i]; 57. 58. if($file_name=='.'||$file_name=='..') 59. continue; 60. 61. $sub_folder_name = $base_folder ."\\". $file_name; 62. $file_type = is_dir($sub_folder_name) ? 'dir' : 'file'; 63. if($file_type=='dir'){ 64. $sub_folder_count++; 65. $rpeort .= "Processing folder $sub_folder_count $sub_folder_name \r\n"; 66. $msg = "Processing folder $sub_folder_count $sub_folder_name \r\n"; 67.?> 68. <tr bgcolor="#FFFFFF"><td> </td><td colspan="2"> 69. <?php echo $msg;?> 70. </td><td> </td></tr> 71. <tr bgcolor="#FFFFFF"><td> </td><td colspan="2"> 72. <table width="90%" cellpadding="0" cellspacing="0" border="1" bordercolorlight="#0000FF"> 73.<?php 74. // process sub folder 75. $column1 = $file_name; 76. $column2 = '{'; 77. $column3 = '{'; 78. $first = true; 79. $files_arr = scandir($sub_folder_name); 80. $article_processed =0; // article_processed in current sub folder 81. foreach($files_arr as $key=>$val){ 82. 83. if(is_file($sub_folder_name.'\\'.$val) ) 84. { if( substr($val,-4)=='.txt' ) 85. { 86. $article_processed++; 87. 88. if($article_to_capture==0 || $article_processed <= $article_to_capture ){ 89. 90. if($first==true) $first=false; 91. else 92. { $column2 .= '|'; $column3 .= '|'; } 93. 94. // read file get title and body 95. $file_content = file($sub_folder_name.'\\'.$val); 96. $file_title = rtrim($file_content[0]); 97. 98. $file_content[0] = ''; 99. 100. $file_arr_size = sizeof($file_content); 101. $words_arr_size = sizeof($words); 102. $t=1; 103. while($t < $file_arr_size){ 104. $file_content[$t] = rtrim($file_content[$t]); 105. //echo $file_content[$t]; 106. //die('inside'); 107. if( $words_arr_size>0 ){ 108. //die('inside'); 109. $temp = str_replace($words, "", $file_content[$t]); 110. $file_content[$t] = $temp; 111. } 112. $t++; 113. //if($t>=3) die('aa'); 114. } 115. $file_body = implode('',$file_content); 116. 117. $column2 .= $file_title; 118. $column3 .= $file_body; 119. 120. ?> 121. <tr><td> 122. <?php //print_r($files_arr); 123. echo $val ."\r\n"; 124. ?> 125. </td></tr> 126. <?php 127. } //end if .txt 128. } // article processed 129. } // end if is_file 130. } // end foreach 131.?> 132.</table> 133.</td><td> </td></tr> 134.<?php $column2 .= '}'; 135. $column3 .= '}'; 136. 137. // write to csv / excel file 138. $erro = fputcsv ($fp, array($column1,$column2,$column3) ); 139. 140. } //end if filetype 141. else{ 142. 143. } 144.} // end for 145. 146.fclose($fp); 147. 148.?> <tr bgcolor="#FFFFFF"> 149. <td> </td> 150. <td colspan=""> File Generated. 151. Download it <a href="articles.csv" target="_blank">HERE</a></td> 152. <td> </td> 153. </tr> 154.</table> 155.</body> 156.</html> Ok Here is my Problem the following works great except it does not add the $user var to the account_details. As well as outputs md5 wrong it outputs something but its different than the password should be. Heres my PHP code: Code: [Select] <?php session_start(); /** * @author Brian T. Flores * @copyright 2010 - 2014 */ error_reporting(E_ALL); $conn = mysql_connect($db_host, $db_user, $db_pass) or die ('Error connecting to mysql'); mysql_select_db($db_name); if($_GET['goahead']==1){ // If GoAhead Is set if(isset($_GET['user'])){ // If isset GoAhead $user = mysql_real_escape_string($_GET['user']); // Clean User for Transfer. $user_check = mysql_query("SELECT * FROM `account_details` WHERE `username01` = '$user'"); // Check to see if username is taken. $ucount = mysql_num_rows($user_check); // Get Username Check Count if($ucount!=""){ // If Username is Taken. die(3); // Die Error Number 3 } // End If Username is Taken. if(isset($_GET['pass'])){ // If password is set. $pass = mysql_real_escape_string($_GET['pass']); // Clean Password for Transfer. $encPass = md5($pass); // Encrypt Password if(isset($_GET['race'])){// If Race is Set. $race = mysql_real_escape_string($_GET['race']); // Clean Race for Transfer. if(isset($_GET['email'])){ // If Email is set. $email = mysql_real_escape_string($_GET['email']); // Clean Email for Transfer. $email_check = mysql_query("SELECT * FROM `account_details` WHERE `email` = '$email'");// Check to see if Email is Taken. $ecount = mysql_num_rows($email_check); // Get Email Check Count. if($ecount!=""){ // If Email is Taken. die(2); // Die Error Number 2 } // End If Email is Taken. if(isset($_GET['email2'])){ // If email confirmation is set. $email2 = mysql_escape_string($_GET['email2']); // Clean Email Confirmation for Transfer. if($email == $email2){ // If emails match. if(isset($_GET['planet'])){ // If Planet Name is Set. $pname = mysql_real_escape_string($_GET['planet']); // Clean Planet Name for Transfer. if(isset($_GET['security_code'])){ // If Security Code Input is set. $security_code = mysql_real_escape_string($_GET['security_code']); // Clean Security Code. $security_enc = md5($security_code); // Encrypt Security Code. $security_code2 = $_SESSION['image_random_value']; // Get Security Code Session if($security_enc == $security_code2){ // If Codes Match. $randActive = rand(11111111111111111111,99999999999999999999); // Get Activation Link pre-encrypt. $activation_link = md5($randActive); // Get Encrypted Activation Link. $q = "INSERT INTO `account_details` (`username01`, `password01`, `loggedIn`, `currentlyLogged`, `active`, `activelink`, `race`, `email`) VALUES ('$user', '$encPass', 0, 0, 0, '$activation_link', '$race', '$email');"; // ^ Add Account Query. $res = mysql_query($q) or die("Error Detected! <br />".mysql_error()); // ^ Add Account to SQL. $q = mysql_query("SELECT * FROM `account_details` WHERE `username01` = '$user'")or die(mysql_error()); // ^ Get Information from New Account. $newuserinfo = mysql_fetch_array($q);// Get New User Information $id = $newuserinfo['id']; // Set New Account Id. $q="INSERT INTO `planets` (`owner`, `name`, `recource1`, `recource2`, `recource3`, `recource4`, `recource5`, `turns_01`, `untrained_units_01`, `attackers_01`, `defenders_01`, `miners_01`, `covert_01`, `anticovert_01`, `ship_01`, `ship_02`, `ship_03`, `ship_04`, `ship_05`, `ship_06`, `ship_07`, `building01`, `building02`, `building03`, `building04`, `building05`, `building06`, `building07`, `building08`, `building09`) VALUES ('$id', '$pname', 35000, 15000, 12000, 135000, 125000, 220, 150, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0);"; // ^ Add Planet Query. $res2 = mysql_query($q) or die("Error Detected! <br />".mysql_error()); // Add Planet to SQL. $body = " Hello ".$user.", Congradulations! Your account on Ultimate Conquest has been Registed Today! Click the following Link to Activate Account: http://testing.ultimateconquest.net/activate.php?code=".$activation_link." If you have not registered an account and have found this message in error please click the following link to report this error: http://testing.ultimateconquest.net/errorreg.php?account=".$user." Thank you for registering for Ultimate Conquest - ULC, Head Admin Brian Flores AKA Photonic.... "; // Activation Email Information. if (mail($email, "Activate your ULC Ultimate Conquest Account! No-Reply!", $body)) { // If Email Is Sent. die("1"); // Die Error Number 1 } // End Send Email }else{ // If Security Codes do Not Match. die("12"); // Die Error Number 12 } }else{ // If Security Code is Not Set die("11"); // Die Error Number 13 } }else{ // If Planet Name is Not Set. die("10"); // Die Error Number 10. } }else{ // If Emails do not match. die("9"); // Die Error Number 9. } }else{ // If email confirmation is not set. die("8"); // Die Error Number 8. } }else{ // If email is not set. die("7"); // Die Error Number 7. } }else{ // If race is not set. die("6"); // Die Error Number 6. } }else{ // If Password is not set. die("5"); // Die Error Number 5. } }else{ // If Username is not set. die("4"); // Die Error Number 4. } }else{ // If GoAhead is Not Set. die("Go Ahead Not Established By Game System!"); } ?> Here is the Register Function in Javascript: Code: [Select] function regMast(){ var user = document.getElementById('username_client').value; var pass = document.getElementById('password_client').value; var race1 = document.getElementById('races1').value; if(race1 !=""){var race = document.getElementById('races1').value;} var race2 = document.getElementById('races2').value; if(race2 !=""){var race = document.getElementById('races2').value;} var race3 = document.getElementById('races3').value; if(race3 !=""){var race = document.getElementById('races3').value;} var race4 = document.getElementById('races4').value; if(race4 !=""){var race = document.getElementById('races4').value;} var planet_name = document.getElementById('pname').value; var email = document.getElementById('email').value; var email2 = document.getElementById('email2').value; var security_code = document.getElementById('security_code').value; var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var returni = ajaxRequest.responseText; if(returni == "1"){ document.getElementById('reg_error').innerHTML = 'Registration Completed! Check Activation Email for more information.'; } if(returni == "2"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Email Address Already Taken!'; } if(returni == "3"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Username Already Taken!'; } if(returni == "4"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Username Field Empty!'; } if(returni == "5"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Password Field Empty!'; } if(returni == "6"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! You must select a race!'; } if(returni == "7"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Email Field Empty!'; } if(returni == "8"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Email Confirmation Field Empty!'; } if(returni == "9"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Emails did not Match!'; } if(returni == "10"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! Planet Name Field Empty!'; } if(returni == "11"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! You did not Input the Security Code!'; } if(returni == "12"){ document.getElementById('reg_error').innerHTML = 'Registration Incomplete! The Security Code you Inputed did not Match the Image!'; }else{ document.getElementById('reg_error').innerHTML = returni; } } } var queryString = "?goahead=1&user=" + user + "&pass=" + pass + "&race=" + race + "&email=" + email + "&email2=" + email2 + "&security_code=" + security_code + "&planet=" + planet_name; ajaxRequest.open("GET", "register.php" + queryString, true); ajaxRequest.send(null); } Hi there, This doesn't seem to echo as attempted, is their a way of doing this? $body2 = "Hello $name, \n <strong>I want to make this paragraph bold!</strong>\n"; Displays as: Code: [Select] Hello John Smith, <strong>I want to make this paragraph bold!</strong> I want to format the text making it bold, but it displays the <strong> tags. Thanks This topic has teleported to Third Party PHP Scripts. Beam me up, Scotty. http://www.phpfreaks.com/forums/index.php?topic=343682.0 Hi, I am pretty much a new newbie when it comes to PHP, and have a problem that I need to solve, for a website that has to go live tomorrow. Basically I have been using a javascript upload script called 'uploadify' which had an option for the upload folder which was added to the script in the form: Code: [Select] 'folder' : '/songs/<?php echo $_SESSION["name"];?>', I added the php echo to return the username from a PHP login, so it gets added to the path to the upload folder (each user has their own subfolder for uploading to). With the new version of the uploadify script, the folder option has been moved to a separate PHP file where it is now in the form: Code: [Select] $targetFolder = '/songs/'; I need to find a way of adding the username variable to this line. I have tried using echo in various ways, and googled about, but it has stumped me, simple as it may be. If anyone could let me know how I construct this line I'd be very grateful. Time is of the essence, as they say... Thanks, Nick I am building an Event Registration system, and am thinking that it should put the Attendee's name on the Ticket (and in the database) as a backup. Is there a way to easily (and dynamically) display the same number of Text-Boxes as the # of Attendees entered? For example, let's say the Customer (payor) wants to buy Tickets for herself and 5 friends to a Banjo Festival. Right now, I just have a drop-down box to capture the head-count, but it would be nice to have 5 Text-Boxes (or something appear) so that the Customer can easily type in the Names of the 5 Attendees *without* having to suffer numerous other clicks and/or screens. Follow me? Is there a way to do that? Thanks, Debbie Not sure if that title encapsulates what I am trying to say, but basically I have the script that can work if the page is on the root of the domain with htaccess, but not in a subfolder. I just want an easy way to have it so if I type in a domain name such as: www.mysite.com/subfolder/hi that it will put "hi" in the page where I want. The code I had was something like: $item = $_GET['item']; if (!$item) $item = "test"; $item2 = str_replace("-", " ", $item); then in the page it would have <?=$item2;?> but I cant get it to work. help please! Hello, I'm just learning PHP and I'm trying to have a different image display for each Item in a shop.. My only guess to how this would be possible is to name the IMG after the ID of the Item, like Item #10 has a name of 10.jpg. My question is, how would I go about doing this? or is there a better way of doing this.. Here is the Code I currently have. Thanks for help. Code: [Select] <?php session_start(); $page = 'index.php'; mysql_connect ('localhost','root','') or die(mysql_error()); mysql_select_db ('buggs') or die (mysql_error()); function products() { $get = mysql_query('SELECT id, name, description, price FROM products WHERE quantity > 0 ORDER BY id DESC LIMIT 10'); if (mysql_num_rows($get)==0) { echo "There are no products to display!"; } else { while ($get_row = mysql_fetch_assoc($get)) { echo '<p>'.$get_row['id'].'<br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />'.number_format($get_row['price'], 2).' <a href="cart.php?add='.$get_row['id'].'">Add</a></p>'; } } } ?> and the code to where it displays.. Code: [Select] <?php require 'cart.php'; ?> <html> <head> </head> <body> <?php products();?> </body> </html> Hiya all, Firstly thanks for the previous help with the arrays and that... you guys (or girls) ROCK ! But now I am stuck... lol. I am creating a simple motor dealer script for a friend with a garage and a few cars. The idea is... they fill in the form... upload the image(s) and then it adds it in to the database and displays the info on the page with other cars. So far I have got it to array all the info in the database how I want (thanks to you lot !). Now I need to add another box on the add vehicle page to upload photos and then on the show vehicles page I need it to show the uploaded photos next to the vehicles info. This is what I have so far: showvehicles.php: <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Current Showroom</B></CENTER> <BR> <!-- VIEWING BIT --> <?php include('dbconnect.php') ?> <?php // Make a MySQL Connection $query = "SELECT * FROM cars"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo "<TABLE CELLPADDING=0 CELLSPACING=0 WIDTH=100% BORDER=0>"; echo "<TR />"; echo "<TD WIDTH=30% VALIGN=TOP />"; echo " <IMG SRC=immg.gif /> "; echo "<br />"; echo "</TD>"; echo "<TD WIDTH=10 VALIGN=TOP />"; echo " "; echo "</TD>"; echo "<TD />"; echo "<font size=3 face=arial /><B >"; echo $row['CarPrice']; echo "</B><font size=2 face=arial />"; echo "<br />"; echo $row['CarTitle']; echo "<br />"; echo "Vehicle Type: "; echo $row['CarName']; echo "<br />"; echo "Vehicle Mileage: "; echo $row['CarMiles']; echo "<br />"; echo "Description: "; echo "<br />"; echo "<br />"; echo $row['CarDescription']; echo "<br />"; echo "</TD>"; echo "</TR>"; echo "</TABLE>"; echo "<hr WIDTH=100% COLOR=BLACK />"; } ?> <!-- END OF VIEWING BIT --> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> AddVehicle.php <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Add a Vehicle</B></CENTER> <BR> <form action="inserts.php" method="post"> <CENTER>Vehicle Name:</CENTER> <CENTER><input type="text" name="CarName"></CENTER> <br> <CENTER>Vehicle Type:</CENTER> <CENTER><input type="text" name="CarTitle"></CENTER> <br> <CENTER>Vehicle Price:</CENTER> <CENTER><input type="text" name="CarPrice"></CENTER> <br> <CENTER>Vehicle Mileage:</CENTER> <CENTER><input type="text" name="CarMiles"></CENTER> <br> <CENTER>Vehicle Description:</CENTER> <CENTER><textarea name="CarDescription" rows="10" cols="30"></textarea></CENTER> <br> <CENTER><input type="Submit"></CENTER> </form> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> inserts.php (Actually handles adding info to the database thats been typed in form) <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Vehicle Added</B></CENTER> <BR> <?php mysql_connect("localhost", "wormste1_barry", "barry") or die(mysql_error()); mysql_select_db("wormste1_barry") or die(mysql_error()); $CarName = mysql_real_escape_string(trim($_POST['CarName'])); $CarTitle = mysql_real_escape_string(trim($_POST['CarTitle'])); $CarPrice = mysql_real_escape_string(trim($_POST['CarPrice'])); $CarMiles = mysql_real_escape_string(trim($_POST['CarMiles'])); $CarDescription = mysql_real_escape_string(trim($_POST['CarDescription'])); mysql_query("INSERT INTO cars (CarName, CarTitle, CarPrice, CarMiles, CarDescription) VALUES('$CarName', '$CarTitle', '$CarPrice', '$CarMiles', '$CarDescription' ) ") or die(mysql_error()); echo "The vehicle data has been added!"; ?> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> If anyone can help me... much appreciated. I googled it and it started quoting BLOBS and stuff... i was confused Hi There, I want to add a picture to an existing user. The sql looks like: CREATE TABLE `klanten` ( `id` int(4) unsigned NOT NULL auto_increment, `username` varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `level` int(4) default '1', `filename` varchar(255) not null, `mime_type` varchar(255) not null, `file_size` int not null, `file_data` mediumblob not null, primary key (id), index (filename) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; id, username, password and level are allready filled in. Now i need some code to go with <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> process.php: <?php require_once 'database.php'; function assertValidUpload($code) { if ($code == UPLOAD_ERR_OK) { return; } switch ($code) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $msg = 'Image is too large'; break; case UPLOAD_ERR_PARTIAL: $msg = 'Image was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $msg = 'No image was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $msg = 'Upload folder not found'; break; case UPLOAD_ERR_CANT_WRITE: $msg = 'Unable to write uploaded file'; break; case UPLOAD_ERR_EXTENSION: $msg = 'Upload failed due to extension'; break; default: $msg = 'Unknown error'; } throw new Exception($msg); } $errors = array(); try { if (!array_key_exists('image', $_FILES)) { throw new Exception('Image not found in uploaded data'); } $image = $_FILES['image']; // ensure the file was successfully uploaded assertValidUpload($image['error']); if (!is_uploaded_file($image['tmp_name'])) { throw new Exception('File is not an uploaded file'); } $info = getImageSize($image['tmp_name']); if (!$info) { throw new Exception('File is not an image'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } if (count($errors) == 0) { // no errors, so insert the image $query = sprintf( "insert into klanten (filename, mime_type, file_size, file_data) values ('%s', '%s', %d, '%s')", mysql_real_escape_string($image['name']), mysql_real_escape_string($info['mime']), $image['size'], mysql_real_escape_string( file_get_contents($image['tmp_name']) ) ); mysql_query($query, $con); $id = (int) mysql_insert_id($con); // finally, redirect the user to view the new image header('Location: view.php?id=' . $id); exit; } ?> <html> <head> <title>Error</title> </head> <body> <div> <p> The following errors occurred: </p> <ul> <?php foreach ($errors as $error) { ?> <li> <?php echo htmlSpecialChars($error) ?> </li> <?php } ?> </ul> <p> <a href="upload.php">Try again</a> </p> </div> </body> </html> to add to an existing user. Can somebody help me here? Best regards, Martijn Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks |