PHP - Code Review (directory Handling) Working, But Not Pretty
$username = $loggedInUser->username; // This is the logged in username
$time = time(); $makedir = $username.'_'.$time; $var = getcwd(); $var = str_replace('\users', '\imageuploads', $var); $dirlocation = $var."\\".test_directory($username, $mysqli); function test_directory ($username, $mysqli) { $stmt = $mysqli->prepare("SELECT Temp_Directory FROM uc_users WHERE user_name LIKE ?"); $stmt->bind_param("s", $username); $stmt->execute(); $stmt->bind_result($Tempdir); while ($stmt->fetch()){ return $Tempdir; } } if((!empty(test_directory($username, $mysqli))) && is_dir($dirlocation)){ //echo "this is it"; $thedirectory = $dirlocation; } if(empty(test_directory($username, $mysqli))){ //echo "it's not a directory"; $newdir = $var."\\".$makedir; $query = mysqli_query($mysqli, "UPDATE uc_users SET Temp_Directory='$makedir' WHERE user_name='$username'"); if(!$query){ //echo mysqli_error($mysqli); } mkdir($newdir); //security chmod($newdir, 0644); $thedirectory = $newdir; } if(!is_dir($dirlocation) && (!empty(test_directory($username, $mysqli)))){ //echo "third one"; mkdir($dirlocation); chmod($dirlocation, 0644); $thedirectory = $dirlocation; } Ok, so what I'm doing here is testing to see whether a a record exists of the user having a folder in the MySQL database. Then, if it does, make sure that a folder exists at that location. If there is no folder, we create one for the user. If there is already a folder, we leave it alone. This is for image uploads, and $thedirectory, is where we upload images later on in the script. Hope that makes sense. The code seems to work. But how can I improve it and make it more robust? Or should I just leave it alone? Should I return FALSE from the function for better reliability over empty()? Similar TutorialsThis topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=354376.0 In a project that I'm working on I can specify routing rules, which is somewhat similar to mod_rewrite but in PHP. It's currently set up to use full regular expressions, but it's kind of overkill. I'm trying to convert it to use routing rules similar to some of the php frameworks I've seen. The code I've written up below is working, and while it's unlikely that I would need anything more complex, I'm wondering if anyone would like to comment, offer suggestions, or offer criticisms. This little piece of code is just a part of a bigger routing class, but this is the code that I'm concerned with. Thanks.
<?php $cfg['routes'] = [ 'cars/(:any)/(:any)/(:num).php' => 'cars/$3/$1/$2', 'default_route' => 'cars/index', 'trucks/parts?year=(:num)' => 'parts/trucks/$1', 'vans/articles(:any)' => 'articles$1' ]; $uris = [ 'cars/toyota/tercel/2014.php', # /cars/2014/toyota/tercel 'default_route', # /cars/index 'trucks/parts?year=2014', # /parts/trucks/2014 'vans/articles?p=42342' # /articles?p=42342 ]; $i = 0; foreach( $cfg['routes'] as $k => $v ) { $k = '|^' . preg_quote( $k ) . '$|uiD'; $k = str_replace( [ '\(\:any\)', '\(\:alnum\)', '\(\:num\)', '\(\:alpha\)', '\(\:segment\)' ], [ '(.+)', '([[:alnum:]]+)', '([[:digit:]]+)', '([[:alpha:]]+)', '([^/]*)' ], $k ); echo '<br />' . $uris[$i] . '<br />' . $k . '<br />'; if( @preg_match( $k, $uris[$i] ) ) { echo preg_replace( $k, $v, $uris[$i] ) . '<br /><br />'; } $i++; } i want the code for review approval platform (costumer reviews for a product )and in backend editing the code and updating it if(get_images_for_delete($username, $newid, $mysqli) !== FALSE){ // WE are dealing with images $images = get_images_for_delete($username, $newid, $mysqli); $sourceBucket = "***********"; $targetBucket = "***********"; foreach($images as $image){ // copy our object $aws = new s3; $aws = $aws->copyObject($targetBucket, $image, $sourceBucket, $image); // delete our object $aws_delete = new s3; $aws_delete = $aws_delete->deleteObject($image); // copy our (thumbnail) object $aws2 = new s3; $aws2 = $aws2->copyObject($targetBucket, "thumb_".$image, $sourceBucket, "thumb_".$image); // delete our (thumbnail) object $aws_delete2 = new s3; $aws_delete2 = $aws_delete2->deleteObject("thumb_".$image); }Is my code. Do I need to declare so many new s3 classes? All the methods are within the same class. Not sure if this is the correct way to go about it. I have a problem with the below code: Code: [Select] <?php $sql_ranks = ("SELECT vtp_members.id, vtp_members.name, vtp_members.teamleader, teams.team_name, count(vtp_tracking.id) surfs FROM vtp_members, vtp_tracking, teams WHERE vtp_members.team_id=".$_GET['t']." AND vtp_tracking.credit_members_id=vtp_members.id AND vtp_tracking.action_date > '$last_sunday' AND vtp_tracking.action_date < '$next_sunday' GROUP BY teams.team_name ORDER BY surfs DESC"); $rsranks = mysql_query($sql_ranks); echo "<br><table align='center' valign='top' border='0' width='300px'> <tr><td colspan='2' align='center'><font size='2px'><b>Team Rankings (Current Week)</b></font></td></tr> <tr><td><font size='2px'><b>Team</font></td><td align='right'><font size='2px'>Total Surfs</font></td></tr>"; while ($row = mysql_fetch_array($rsranks)) { echo "<tr><td><font size='2px'><b>".$row[team_name]."</font></td><td align='right'><font size='2px'>".$row[surfs]."</font></td></tr>";} echo "</table>"; ?> Problem is that the last output (".$row[surfs].") is the same for all teams. It seems it is not making a total of all id's and not per team_name. anyone can see what I am doing wrong. I need to sort by team_name and the surfs should display the total of the members with team_id is ".$_GET['t']." I have a weird kind of problem. I uploaded all upload-directories through FTP which have 777 permissions and owner name 'abc' This means I can access all of them through the codes. But while creating files inside those full permitted directories, the compiler complains for access denied. Meanwhile, a different directory is created with same name whose owner is 'apache' itself and the previous directory is lost. Then I cannot change the permissions of that directory through FTP. I don't if it is apache server's problem itself or not. Or is it a way to define user while creating/editing/deleting files and directories through php code itself? Hi guys, I wrote this speck of code to prevent directory transversal. However, I'm not that great with security issues, so I would like some of the gurus to offer pointers/tips/hints as to whether my code is safe or not and how to improve it. $pageID = $_GET["pageid"]; $pageNewIDLower = strtolower($pageID); $pageNewID = ereg_replace("[^A-Za-z0-9]","",$pageNewIDLower); if (strstr($pageNewID,"../") || strstr($pageNewID,"%") != true) { // do stuff } else { include("pages/home.htm"); } If this looks wrong, let me know. I didn't take it directly from my php code as I'm on a cell phone at the moment. I am getting Use of undefined constant id - assumed 'id' with this: $query = "SELECT * FROM products WHERE id = ".mysql_real_escape_string($_POST[id]).""; That seems pretty bull shit to me. Is this a bug in PHP? Hi guys, I've been working on a script for a while now, and I'm sure it doesn't look great and all, and it's probably really messed up.. But right now I've finally got it working! There's only 1 thing I'd really like to add.. Searching through & listing of remote directories! The directories I'm trying to list have directory listings enabled, and I think it *should* be possible. I just have no clue how. Here's my current code in a beautiful mix of HTML and PHP: <? $border_size = "0"; function returner($what) { $what=explode("/",$what); $tps=count($what); $what=$what[$tps-1]; return $what; } $page_url= ""; $home_url=returner(__FILE__); if(isset($_GET['q'])) { $qtext=$_GET['q']; } else { $qtext=""; } function getdirsize($directory, $format=FALSE) { $size = 0; if(substr($directory,-1) == '/') { $directory = substr($directory,0,-1); } if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return -1; } if($handle = opendir($directory)) { while(($file = readdir($handle)) !== false) { $path = $directory.'/'.$file; if($file != '.' && $file != '..') { if(is_file($path)) { $size += filesize($path); } elseif(is_dir($path)) { $handlesize = getdirsize($path); if($handlesize >= 0) { $size += $handlesize; } else { return -1; } } } } closedir($handle); } if($format == TRUE) { if($size / 1048576 > 1) { return round($size / 1048576, 1).' MB'; } elseif($size / 1024 > 1) { return round($size / 1024, 1).' KB'; } else { return round($size, 1).' bytes'; } } else { return $size; } } if(isset($_GET['type'])){ $type=$_GET['type']; } else { $type="new"; } $textures=0; $models=0; $avatars=0; $seqs=0; $sounds=0; foreach (glob("textures/*.jpg") as $texture){ $textures++; } foreach (glob("models/*.zip") as $model){ $models++; } foreach (glob("avatars/*.zip") as $avatar){ $avatars++; } foreach (glob("seqs/*.zip") as $seq){ $seqs++; } foreach (glob("sounds/*.zip") as $sound){ $sounds++; } ?> <!DOCTYPE html> <html> <head> <title>ObjectPath Search</title> <style type="text/css"> #wrapper { width: 850px; margin: 30px auto 30px auto; padding: 10px; } body { color:#C6C6C6; background:#1E1E1E; /* margin:0; padding:0; */ overflow-x:hidden; } #tabs { font: 85% "Trebuchet MS", sans-serif; } .left { float: left; } .right { float: right; } a:link, a:visited, a:active { color: #3DB015; text-decoration: none; } a:hover { color: #00E0FF; } h2 { color: #3DB015; padding-bottom: 0.2em; font-size: 110%; } ul#icon {margin: 0; padding: 0;} ul#icon li {margin: 1px; position: relative; padding: 1px 0; cursor: pointer; float: left; list-style: none;} ul#icon span.ui-icon {float: left; margin: 0 1px;} </style> <link type="text/css" href="http://objects.jk-hosting.com/search/css/black-tie/jquery-ui-1.8.2.custom.css" rel="stylesheet" /> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://objects.jk-hosting.com/search/js/jquery-ui-1.8.2.custom.min.js"></script> <script type="text/javascript"> function formHandler(form){ var URL = document.form.site.options[document.form.site.selectedIndex].value; window.location.href = URL; }; $(function(){ // Tabs $('#tabs').tabs(); }); </script> </head> <body> <div id="wrapper"> <div id="tabs"> <!-- Tabs start --> <ul> <li><a href="#tab-search">Search</a></li> <li><a href="#tab-list">List Objects</a></li> <li><a href="#tab-info">OP info</a></li> </ul> <div id="tab-search"><!-- Searchtab start --> Please enter a string to search for, and choose a folder to search in. <br /><br /> <form name="Search"> <input type='hidden' value='search' name='type'> <input value='<? print $qtext; ?>' type='text' name='q'> <select name='map'> <option selected='selected' value='models'>Models</option> <option value='avatars'>Avatars</option> <option value='textures'>Textures</option> <option value='seqs'>Seqs</option> <option value='sounds'>Sounds</option></select> <input type='submit' value='Search'> </form> </div> <!-- Searchtab end --> <div id="tab-list"><!-- Listtab start --> Please pick a folder to browse. <br /><br /> <form name="form"> <select name="site" onChange="javascript:formHandler()"> <option value="#">Look in folder...</option> <option value="<? print $page_url; ?>?type=list&map=models">Models</option> <option value="<? print $page_url; ?>?type=list&map=avatars">Avatars</option> <option value="<? print $page_url; ?>?type=list&map=textures">Textures</option> <option value="<? print $page_url; ?>?type=list&map=seqs">Seqs</option> <option value="<? print $page_url; ?>?type=list&map=sounds">Sounds</option> </select> </form> </div> <!-- Listtab end --> <div id="tab-info"><!-- Info tab start --> The OP currently contains: <br /><br /> <table> <tr><td><b><? echo $models; ?></b></td> <td>Models</td></tr> <tr><td><b><? echo $avatars; ?></b></td> <td>Avatars</td></tr> <tr><td><b><? echo $textures; ?></b></td> <td>Textures</td></tr> <tr><td><b><? echo $seqs; ?></b></td> <td>Seqs</td></tr> <tr><td><b><? echo $sounds; ?></b></td> <td>Sounds</td></tr> </table> </div> <!-- Info tab end --> </div> <!-- Tabs end --> </div> <!-- Start PHP generated content --> <? if($type=="search" || $type=="list") { $M=$_GET['map']; if($type=="search") { $Q=$_GET['q']; $empty="Nothing found with <b>\"" . $Q . "\"</b> in it's name.<br />\nPlease make a more general search query, or try a different folder.\n\n"; } else { $Q=""; $empty='This folder is empty'; } if($M=="textures") { $ext="jpg"; } else { $ext="zip"; } $i=0; print "<hr>\n"; $endfile=array(); $endsize=array(); $endsize2=array(); foreach (glob($M."/*".$Q."*.".$ext) as $filename) { $filename = explode(".", $filename); $filename=$filename[0]; $filename = explode("/", $filename); $filename=$filename[1]; $i++; $endfile[$i]=$filename; if($ext=="jpg") { $endfile[$i]="<a name='".$endfile[$i]."' href='".$pageurl."?type=view&name=".$endfile[$i]."&folder=".$M."&from=".$type."&addon=".$Q."'>".$endfile[$i]."</a>"; } $endsize[$i]=$size; $endsize2[$i]=$size2; } if($i != 1) { print "<b>".$i."</b> items were found.\n<hr>\n"; } else { print "<b>".$i."</b> item was found.\n<hr>\n"; } echo("<table width='100%' border='" . $border_size . "' cellspacing='0' cellpadding='0' >\n"); if($i!=0) { for ($t = 1; $t < $i; $t++) { $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } if($t=="1") { echo("<tr><td width='10%'>Number</td><td width='3%'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></td><td width='60%'>Name</td></tr>\n"); } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); flush(); } $thumbfile = $M."/".$endfile[$t].'.jpg'; if(file_exists($thumbfile)) { $thumbnail = "<a name='".$endfile[$t]."' href='".$page_url."?type=view&name=".$endfile[$t]."&folder=".$M."&from=".$type."&addon=".$Q."'><ul id='icon'><li class='ui-state-default ui-corner-all' title='".$endfile[$t]."'><span class='ui-icon ui-icon-image'></span></li></ul></a>"; } else { $thumbnail = ""; } echo("<tr><td>" . $t . "</td><td>".$thumbnail."</td><td>" . $endfile[$t] . "</td></tr>\n"); } print "</table>\n"; if($i=="0") { print $empty; } } elseif($type=="view") { $filename=$_GET['name']; $folder=$_GET['folder']; if($_GET['from']=="list"){ $addon="?type=list&map=".$folder."#".$filename; } if($_GET['from']=="search"){ $addon="?type=search&q=".$filename."&map=".$folder."#".$filename; } print"<center><a href='".$home_url."'>Home</a></center>"; print "<hr>\n<center><img src='".$folder."/".$filename.".jpg'></img></center>\n<hr>\n<br />\n<a href='".$page_url."".$addon."'>Previous Page</a>\n"; } $htmlshow=""; if($_GET['type']=="returnOPfile") { if(isset($_GET['split'])) { $splitter=$_GET['split']; } else { $splitter=" | "; } if(isset($_GET['html'])) { $htmlshow="<br />"; } foreach (glob("textures/*.jpg") as $texture){ if(isset($_GET['size'])) { $size=$splitter.filesize($texture); } $texture = explode("/", $texture); $texture=$texture[1]; print "textures".$splitter.$texture.$size."\n".$htmlshow; } foreach (glob("models/*.zip") as $model){ if(isset($_GET['size'])) { $size=$splitter.filesize($model); } $model = explode("/", $model); $model=$model[1]; print "models".$splitter.$model.$size."\n".$htmlshow; } foreach (glob("avatars/*.zip") as $avatar){ if(isset($_GET['size'])) { $size=$splitter.filesize($avatar); } $avatar = explode("/", $avatar); $avatar=$avatar[1]; print "avatars".$splitter.$avatar.$size."\n".$htmlshow; } foreach (glob("seqs/*.zip") as $seq){ if(isset($_GET['size'])) { $size=$splitter.filesize($seq); } $seq = explode("/", $seq); $seq=$seq[1]; print "seqs".$splitter.$seq.$size."\n".$htmlshow; } foreach (glob("sounds/*.zip") as $sound){ if(isset($_GET['size'])) { $size=$splitter.filesize($sound); } $sound = explode("/", $sound); $sound=$sound[1]; print "sounds".$splitter.$sound.$size."\n".$htmlshow; } } ?> <!-- End PHP generated content --> </body> </html> So right now my question to you PHP freaks is, can you please help me edit my script so I can search through a remote directory? *This* is one of the directories I wish to be able to search through & list.. Thanks in advance. Edit; It might help if you know what the site currently looks like. *Click* I'm in the process of building a network for investors and entrepreneurs. When a user logs in, they are directed to profile.php where they can have access to their profile information. If you go into the address bar and type in network.jasonbiondo.com/jasonbiondo you will not be able to view my profile, but if you type in http://network.jasonbiondo.com/profile. ... asonbiondo , you will be able to see my profile. I want to make it cleaner so that you can access profiles by going directly to network.jasonbiondo.com/jasonbiondo . I think my .htaccess file is causing the problem. I have listed my code below. .htaccess Code: [Select] Options +FollowSymLinks RewriteEngine On RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME} !-f RewriteRule ^(.*)$ ./profile.php?u=$1 [NC] I would like to take the following xml file, and convert it to a nice array. Is there any functions to do this or any suggestions how to do this? xml file: Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <users> <instructions> <phpfile>users.php</phpfile> </instructions> <users action="multiple"> <user> <name>root</name> <password>5f4dcc3b5aa765d61d8327deb882cf99</password> <permissions> <access>CREATE_USR</access> </permissions> </user> <users> </users> Desired array: Code: [Select] Array ( [instructions] => Array ( [phpfile] => users.php ) [users] => Array ( [0] => Array ( [name] => root [password] => 5f4dcc3b5aa765d61d8327deb882cf99 [permissions] => Array( [access] => CREATE_USR ) ) ) ) you can see it at the link below on my site. The generated thumbnails look terrible but I don't know why. Any help greatly appreciated. thank you . (code below of upload script and viewgallery script) http://ealike.com/gallery/viewgallery.php?cid=1 upload script Code: [Select] <?php include("config.inc.php"); // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by preupload.php $photos_uploaded = $_FILES['photo_filename']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) { $thumbnail_width = 100; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(100 * $size[0] / $size[1]); $thumbnail_height = 100; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } // Print Result echo <<<__HTML_END <html> <head> <title>Photos uploaded</title> </head> <body> $result_final </body> </html> __HTML_END; ?> DISPLAY THUMBNAILS AND IMAGES SCRIPT Code: [Select] <?php include("config.inc.php"); // initialization $result_array = array(); $counter = 0; $cid = (int)($_GET['cid']); $pid = (int)($_GET['pid']); // Category Listing if( empty($cid) && empty($pid) ) { $number_of_categories_in_row = 4; $result = mysql_query( "SELECT c.category_id,c.category_name,COUNT(photo_id) FROM gallery_category as c LEFT JOIN gallery_photos as p ON p.photo_category = c.category_id GROUP BY c.category_id" ); while( $row = mysql_fetch_array( $result ) ) { $result_array[] = "<a href='viewgallery.php?cid=".$row[0]."'>".$row[1]."</a> "."(".$row[2].")"; } mysql_free_result( $result ); $result_final = "<tr>\n"; foreach($result_array as $category_link) { if($counter == $number_of_categories_in_row) { $counter = 1; $result_final .= "\n</tr>\n<tr>\n"; } else $counter++; $result_final .= "\t<td>".$category_link."</td>\n"; } if($counter) { if($number_of_categories_in_row-$counter) $result_final .= "\t<td colspan='".($number_of_categories_in_row-$counter)."'> </td>\n"; $result_final .= "</tr>"; } } // Thumbnail Listing else if( $cid && empty( $pid ) ) { $number_of_thumbs_in_row = 5; $result = mysql_query( "SELECT photo_id,photo_caption,photo_filename FROM gallery_photos WHERE photo_category='".addslashes($cid)."'" ); $nr = mysql_num_rows( $result ); if( empty( $nr ) ) { $result_final = "\t<tr><td>No Category found</td></tr>\n"; } else { while( $row = mysql_fetch_array( $result ) ) { $result_array[] = "<a href='viewgallery.php?cid=$cid&pid=".$row[0]."'><img src='".$images_dir."/tb_".$row[2]."' border='0' alt='".$row[1]."' /></a>"; } mysql_free_result( $result ); $result_final = "<tr>\n"; foreach($result_array as $thumbnail_link) { if($counter == $number_of_thumbs_in_row) { $counter = 1; $result_final .= "\n</tr>\n<tr>\n"; } else $counter++; $result_final .= "\t<td>".$thumbnail_link."</td>\n"; } if($counter) { if($number_of_photos_in_row-$counter) $result_final .= "\t<td colspan='".($number_of_photos_in_row-$counter)."'> </td>\n"; $result_final .= "</tr>"; } } } // Full Size View of Photo else if( $pid ) { $result = mysql_query( "SELECT photo_caption,photo_filename FROM gallery_photos WHERE photo_id='".addslashes($pid)."'" ); list($photo_caption, $photo_filename) = mysql_fetch_array( $result ); $nr = mysql_num_rows( $result ); mysql_free_result( $result ); if( empty( $nr ) ) { $result_final = "\t<tr><td>No Photo found</td></tr>\n"; } else { $result = mysql_query( "SELECT category_name FROM gallery_category WHERE category_id='".addslashes($cid)."'" ); list($category_name) = mysql_fetch_array( $result ); mysql_free_result( $result ); $result_final .= "<tr>\n\t<td> <a href='viewgallery.php'>Categories</a> > <a href='viewgallery.php?cid=$cid'>$category_name</a></td>\n</tr>\n"; $result_final .= "<tr>\n\t<td align='center'> <br /> <img src='".$images_dir."/".$photo_filename."' border='0' alt='".$photo_caption."' /> <br /> $photo_caption </td> </tr>"; } } // Final Output echo <<<__HTML_END <html> <head> <title>Gallery View</title> </head> <body> <table width='100%' border='0' align='center' style='width: 100%;'> $result_final </table> </body> </html> __HTML_END; ?> i dont understand what is wrong plz help me.
here is code
$name = "img/".rand(1,9999999).".png"; $myFile = $name; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = $html; fwrite($fh, $stringData); fclose($fh); $file=$name; $fst=file_get_contents($file); $im=imagecreatefromstring($fst); imagefilter($im, IMG_FILTER_GRAYSCALE); imagefilter($im, IMG_FILTER_NEGATE); //Convert to Grey Scale for($i=0;$i<123;$i++){ for($j=0;$j<50;$j++){ $px=imagecolorat($im,$i,$j); if($px<0x303030){ imagesetpixel($im,$i,$j,0); }else{ imagesetpixel($im,$i,$j,0xffffff); } } } $database = unserialize(@file_get_contents("db.txt")); if($database === false) $database = array(); // modify the database if needed if($_SERVER['REQUEST_METHOD'] == 'POST'){ if($_POST['submit'] == 'Add') $database[$_POST['ident']] = substr($_POST['letter'], 0, 1); if($_POST['submit'] == 'Del') unset($database[$_POST['ident']]); if($fh = @fopen('db111.txt', 'w+')){ fwrite($fh, serialize($database)); fclose($fh); } }else{ $newimage = true; } $width = 130; $height = 40; $captcha_gridstart =1; $captcha_gridspace =2; $letters = findletters($im, $width, $height, $captcha_gridstart, $captcha_gridspace); $count = count($letters); $cellw = ($count > 0) ? intval(100 / $count) : 0; //dispeckle the image and GET co-ordinates of the characters of captcha image and return them. function findletters($image, $width, $height, $gridstart, $gridspace){ $offsets = array(); $o = 0; $atstartx = true; for($x = 0; $x < $width; $x++){ $blankx = true; for($y = 0; $y < $height; $y++){ if(imagecolorat($image, $x, $y) == 0){ $blankx = false; break; } } if(!$blankx && $atstartx){ $offsets[$o]['startx'] = $x; $atstartx = !$atstartx; }else if($blankx && !$atstartx){ $offsets[$o]['endx'] = $x; $atstartx = !$atstartx; $o++; } } $count = $o; for($o = 0; $o < $count; $o++){ for($y = 0; $y < $height; $y++){ $blanky = true; for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){ if(imagecolorat($image, $x, $y) == 0){ $blanky = false; break; } } if(!$blanky){ $offsets[$o]['starty'] = $y; break; } } for($y = $height-1; $y > $offsets[$o]['starty']; $y--){ $blanky = true; for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){ if(imagecolorat($image, $x, $y) == 0){ $blanky = false; break; } } if(!$blanky){ $offsets[$o]['endy'] = $y; break; } } } for($o = 0; $o < $count; $o++){ $offsets[$o]['ident'] = ""; for($x = $offsets[$o]['startx'] + $gridstart; $x < $offsets[$o]['endx']; $x += $gridspace){ for($y = $offsets[$o]['starty'] + $gridstart; $y < $offsets[$o]['endy']; $y += $gridspace){ $offsets[$o]['ident'] .= ((imagecolorat($image, $x, $y) == 0) ? "0" : "1"); #echo $offsets[$o]['ident'].'<br>'; } } } return $offsets; } $a=""; foreach($letters as $letter){ $asciiletter = $database[$letter['ident']]; if(!empty($asciiletter)) { $a.=$asciiletter; } } http://paste.ee/p/OhiWv
The above is a link to a readable version of my code. The XMLHTTPREQUEST worked, and the array was pulled down. Was able to print out the undecoded/unparsed array. However, immediately afterwards, all code stops working.
<script> var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 8 and older xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("POST", "PHPLibrary/selectMemberResults.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(); xhr.onreadystatechange = display_data; var $phparray function display_data() { if (xhr.readyState == 4) { if (xhr.status == 200) { //alert(xhr.responseText); $phparray = xhr.responseText; document.getElementById("suggestion").innerHTML = $phparray; // // //......................................................? // The above line of code is the last thing to print or // to do anything that returns to the browser.... //.......................................................? // All lines below do nothing............................? // } else { //alert('There was a problem with the request.'); } } } document.write("Length of phparray Array :" + $phparray.length + "<"); var output = JSON.parse($phparray, function (key,val) { if ( typeof val === 'string' ) { // regular expression to remove extra white space if ( val.indexOf('\n') !== -1 ) { var re = /\s\s+/g; return val.replace(re, ' '); } else { return val; } } return val; } ); document.write("Length of Array :" + $output.length + "<"); for (var i=0; i < $output.length; i++) { document.getElementById("suggestion").innerHTML = $output[i].MEMBER_NAME; } </script> http://i.imgur.com/6olCy.png The picture (in the imgur link) pretty much describes what I'm trying to do. As it stands, it would take too long to simply do everything manually with html and css (both of which I'm pretty good at I think), moving all img src and dates from one div tag to another whenever I wanna add something. So yeah, what's the most efficient way to simply submit a picture, and all my other pictures will move? I know some of you guys will say to just learn php, but quite frankly, I don't have the time... and all the php books are ~1000pgs long which seems really daunting. I know, my problem's pretty basic and it'll probably be covered in the first 100pages or so, but still, like I said I don't have that much time for the moment. When I do, however, can you guys recommend me the quickest guide/video series/book to learn practical php? Not the most comprehensive, as the stuff I'm going to be doing's not that complex. One last thing, I've been hearing about CakePHP; what is it? I read that it's an "open source web application framework", but I still have little clue. I'm currently using dreamweaver for all my web stuff (no I do not use the WYSIWYG feature, I just grown accustom to using it). Should I "learn cakephp"? Please answer any one of those questions (particularly the first one). Many thanks and I'll be sure to reply! <?php if (!isset($_GET['register'])) { echo "register stuff here"; } elseif (!isset($_GET['login'])) { echo "login stuff here"; } elseif (!isset($_GET['forgotpassword'])) { echo "password recovery stuff here"; } else { echo "default page stuff here"; } ?> you get what i'm going for, but it kinda messes up this way with different contents on different places? help As a freelancer working alone, I've got to wear all the hats, doing all the front end and back end design and development. So perhaps I'm never really specializing in any one thing, and I tend to miss some good stuff, like MySQL GROUP BY. Doing counts of things using GROUP BY is very handy. I saw somebody doing that in a thread, and adapted it to two things that I was working on in the last week. Sweet!
What other fun MySQL stuff am I missing out on?
I found this online at http://php.net/manual/en/function.time.php: <?php function rel_time($from, $to = null) { $to = (($to === null) ? (time()) : ($to)); $to = ((is_int($to)) ? ($to) : (strtotime($to))); $from = ((is_int($from)) ? ($from) : (strtotime($from))); $units = array ( "year" => 31536000, // seconds in a year (12 months) "month" => 2628000, // seconds in a month (4 weeks) "week" => 604800, // seconds in a week (7 days) "day" => 86400, // seconds in a day (24 hours) "hour" => 3600, // seconds in an hour (60 minutes) "minute" => 60, // seconds in a minute (60 seconds) "second" => 1 // 1 second ); $diff = abs($from - $to); $suffix = (($from > $to) ? ("from now") : ("ago")); foreach($units as $unit => $mult) if($diff >= $mult) { $and = (($mult != 1) ? ("") : ("and ")); $output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s")); $diff -= intval($diff / $mult) * $mult; } $output .= " ".$suffix; $output = substr($output, strlen(", ")); return $output; } ?> ======================= Basically, if you type <?php echo rel_time("March 12, 2011 7:00 PM"); ?>, it will show you the time ago relative to the current time. But there's two problems. 1) The time it sends out is about 5hrs early (the actual time is 7:00pm, I set the rel time to 7:00pm, but the time it displays reads '5 hours ago, 1 minute, and 3 seconds ago'. I'm not much of a coder, but judging by the looks of it, it would appear correct... but apparently not. 2) My second gripe is that the code shows too many increments of date. What I mean is, if if I set the date to over a year ago, it would display the years,months,weeks,days,minutes,seconds. That is way too much increments. I just want it to display seconds, if I submitted it seconds ago, just display minutes if it was displayed minutes ago, and display days if it was submitted days ago. You get the idea. Friends, family, fellow coders, and bored people- can you help a nooblet? Thanks! Heya folks, I came here in hope someone could shed some light on the situation I'm in, it's probably looking me straight in the face and I cant see it.. So basically, I've got my page sorted, I'll theme it for my website later, but it echo's out entry's from a SQL database (images to be reviewed) then it has the name, id and accept and reject buttons. Currently I have the page echoing perfectly, the reject button removes from SQL but does not delete the actual image (that's where I need help) The accept button currently has no function as I've tried INSERT INTO but I cant get it working, so here's some code I hope someone knows what's missing Page that echo's from SQL; Code: [Select] <?php $dbHost = "xxxxxxx"; $dbUser = "xxxxxxx"; $dbPass = "xxxxxxx"; $dbName = "xxxxxxxx"; $db = mysql_connect($dbHost,$dbUser,$dbPass); mysql_select_db($dbName,$db); $image_name='fullsize' ?> <?php $result = mysql_query("SELECT id, fullsize FROM tblimages"); $filename['fullsize'] ?> <html> <table> <tr> <td>Image Uploads</td> </tr> <?php while($row = mysql_fetch_array($result)) : $image = $row['fullsize'] ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['fullsize']; ?></td> <td><?php echo '<img src= "uploads/'.$row['fullsize'].'" width="180" height="180"/> '; ?> </td> <!-- and so on --> <td> <form action="delete.php" method="post"> <input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>" /> <input type="submit" value="Reject" /> </form> <form action="insert.php" method="post"> <input type="hidden" name="insert_id" value="<?php echo $row['filename']; ?>" /> <input type="submit" value="Accept" /> </form> </td> </tr> <?php endwhile; ?> </table> </html> The delete.php's code is; Code: [Select] <?php if(isset($_POST['delete_id']) && !empty ($_POST['delete_id'])) { $delete_id = mysql_real_escape_string($_POST['delete_id']); mysql_query("DELETE FROM tblimages WHERE `id`=".$delete_id); header('Location: test.php'); } ?> And my insert.php is currently faulty code, so but I used virtually the same as the delete.php but where 'delete_id' is I replaced with 'insert_id' My database is laid out like this, tblimages (this is where images that need to be reviewed are stored) [id, fullsize] <- columns stored inside images (this is where images that have been accepted should be moved to) [filename] <-where images should be inserted to. Hope someone can understand and help with this, if so, thank you very much ^_^ I've develped this small script to display user reviews stored in a my databases review table. The problem with the script though is that it seems to be looping ad nauseum. The wierd thing though, is that I've used a very similair script to display another list of items on this site, and it worked correctly without any issue. Could someone take a look at this for me and diagnose the error with the script. The SQL table: Code: [Select] CREATE TABLE IF NOT EXISTS `rev` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rev_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `usr_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `text` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; The PHP script: Code: [Select] User reviews for <? echo $member;?> <br> <table border="0"> <?php for($count = 1; $count <= $revrows; $count++) { $sqlrev = "SELECT * FROM rev WHERE rev_name = '$member' ORDER BY id DESC"; $revresult = mysql_query($sqlrev) or die(mysql_error()); $revrows = mysql_fetch_row($revresult); $revname = mysql_fetch_array($revresult); ?> <tr> <?php print "Review by: " . $revname['usr_name'] . "<br>". $revname['text']; ?> </tr> <?php } ?> </table> |