PHP - Retrieve File From .xml With Income Get Variable (video Thumbs)
Have page#1 with thumbs view_thumbs.php , when a thumb is clicked thumb link goes to page#2 which is the video_play.php page(which must play embed codes from xml sheet)
Using GET method to identify incoming link from page#1. QUESTION is how can i retrieve file(embed code) from xml to play on page#2 with incoming GET info from page#1? (embeds not you only from you tube, so no youtube solutions only, just retrieve file) I somehow have to fill play video div on page#2/video_play.php according to GET data from page#1/view_thumbs.php Similar TutorialsI have a variable $form in the code below what I cant figure out how do it is call it and get the information it has out so I can display the errors: Code: [Select] function login($subuser, $subpass, $subremember){ global $database, $form; //The database and form object /* Username error checking */ $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered"); } else{ /* Check if username is not alphanumeric */ if(!preg_match("^([0-9a-z])*$^i", $subuser)){ $form->setError($field, "* Username not alphanumeric"); } } if ($database->usernameBanned($subuser)) { $form->setError($field, "*Your Account has been banned"); } /* Password error checking */ $field = "pass"; //Use field name for password if(!$subpass){ $form->setError($field, "* Password not entered"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } /* Checks that username is in database and password is correct */ $subuser = stripslashes($subuser); $result = $database->confirmUserPass($subuser, md5($subpass)); /* Check error codes */ if($result == 1){ $field = "user"; $form->setError($field, "* Username not found"); } else if($result == 2){ $field = "pass"; $form->setError($field, "* Invalid password"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } Hi, I am not very good with php but this code was kindly given to me by mdjamato, except I added a variable $markGradeSum to add all the $markGrade. Problem is that I will get notice saying undefined variable $markGradeSum because the $markGradeSum is in the foreach loop which it needs to be in for the right calculation but where I want to output the variable is in the while loop in this line: Code: [Select] $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year'] $markGradeSum}</p>\n"; Below is whole code: Code: [Select] <?php if($num ==0){ echo "<p>Sorry, No Records were found from this Search</p>";} else{ function outputModule($moduleID, $moduleName, $sessionData) { if(!count($sessionData)) { return false; } $markTotal = 0; $markGrade = 0; $weightSession = 0; $markGradeSum = 0; $grade = ""; $sessionsHTML = ""; $courseHTML = ""; foreach($sessionData as $session) { $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} <strong>Session Mark:</strong> {$session['Mark']}</strong> <strong>Session Weight Contribution</strong> {$session['SessionWeight']}%</p>\n"; $markTotal += round($session['Mark'] / 100 * $session['SessionWeight']); $weightSession += ($session['SessionWeight']); $markGrade = round($markTotal / $weightSession * 100); $markGradeSum = round($markGrade); if ($markGrade >= 70){ $grade = "A";} else if ($markGrade >= 60 && $markGrade <= 69){ $grade = "B";} else if ($markGrade >= 50 && $markGrade <= 59){ $grade = "C";} else if ($markGrade >= 40 && $markGrade <= 49){ $grade = "D";} else if ($markGrade >= 30 && $markGrade <= 39){ $grade = "E";} else if ($markGrade >= 0 && $markGrade <= 29){ $grade = "F";} } $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} <strong>Module Mark:</strong> {$markTotal} <strong>Mark Percentage:</strong> {$markGrade} <strong>Grade:</strong> {$grade} </p>\n"; return $moduleHTML . $sessionsHTML; } $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year'] $markGradeSum}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; } } ?> How can I retrieve the variable so it doesn't come up with the notice but be able to display $markGradeSum to the places I want them in (one in foreach loop for calculation and other in while loop for output). Thank You I am presuming that I set a global variable so that I can retrieve it on a different page...My filename is userid; and I will need this in many different pages. I set it thusly: Code: [Select] mysql_select_db($db , $link) or die("Couldn't open $db: ".mysql_error()); $long=$_SERVER['PHP_SELF']; //get path $text = substr(strrchr($long, "/"), 1); //get file name+extension $UserID = trim($text, " .php"); //remove extension, leaving userid Globals["UserID"]; and in a different file try to retrieve it thusly: echo "user is ".$GLOBALS["UserID"]; but all I ever see is "user is"------any help appreciated. Hello, Please could someone tell me how to retrieve an incremental variable from MYSQL as soon as it is inserted? (i.e. before another variable can be inserted) Many thanks. Stu I am trying to create a code where the user enters the zip code and if found in the database, a location will be retrieved. I am getting two undefined variables as errors. I am still learning the POST and GET method and I fear that is where I am getting something mixed up. I have also attached an image of my DB. Thank you so much any input is greatly appreciated. Notice: Undefined variable: address in C:\xampp\htdocs\index.php on line 53 Notice: Undefined variable: zip in C:\xampp\htdocs\index.php on line 54
<?php include ('header.php'); include ('function.php'); ?> <div class="wrapper"> <div> <?php echo'<form method="POST" action"'.getLocations($conn).'"> <input type="text" name="zip" class="search" placeholder="Zip code"><br> <button type="submit" value="submit" id="submit">Submit</button> </form>'; getLocations($conn); ?> </div> </div> <div> <!--foreach($zip as $zip) : --> <?php echo $address['address']; echo $zip['zip']; ?> </div> function.php file code: <?php $dBServername = "localhost"; $dBUsername = "root"; $dBPassword = ""; $dBName = "addresses"; // Create connection $conn = mysqli_connect($dBServername, $dBUsername, $dBPassword, $dBName); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } function getLocations($conn) { if (isset($_POST['submit'])){ // Validate Zip code field if (!empty ($_POST['zip']) && is_numeric ($_POST['zip'])) { $zip = (int)$_POST['zip']; $query = "SELECT * FROM locations WHERE zip = '$zip'"; //get the results $result = mysqli_query($conn, $query); //fetch the data $zip = mysqli_fetch_all($result, MYSQLI_ASSOC); var_dump($zip); mysqli_free_result($result); //close connection mysqli_close($conn); } } }
Hi, I want to be able to let user type in xml text and it will be parsed and uploaded to db, but it doesn't work, it just keeps redirecting me back to this form below! here is html form: Code: [Select] <html> <body> <form method='post' method='form.php'> <p> <textarea name="pastedXML" rows="10" cols="30"> Please paste your xml file here. </textarea> </p> <p> <input type="submit" value="Convert to SQL" name="textXML" /> </p> </form> </body> </html> Here is script (form.php;I just want to retrieve the contents typed in text area to store to variable...how??) Code: [Select] <?php //get the text in textarea and shred it! if(isset($_POST['textXML'])) print $_POST['pastedXML']; ?> Any help much appreciated! What php method is good for getting file from a .xml sheet ? Hi, I want to be able to let user upload XML form, and then in the action page it needs to extract that so that I can add it to the database. Here is the upload form: Code: [Select] <html> <head></head> <body> <form method='post' action="uploadFileToDB.php" enctype="multipart/form-data"> <p> <label> Upload image<input type='file' name='imageFileType' id='imageFileType' /> </label> </p> <p> <input type='submit' value='Upload this image' name='upload' id='upload' /> </p> </form> </body> </html> Here is the uploadFileToDB.php: Code: [Select] <?php require("PHP_xml_parsing_via_DOM.php"); //NB: this script does the actual shreddering (XML to SQL) //IF User uploaded dir or XML file successful, then: if(isset($_POST['upload'])) { //SHRED NOW //NB: how to retrieve the uploaded xml file $_filePath=?? $node=basename($_filePath); $dom=new DOMDocument(); $dom->load($node); $labelPath=array(); mysql_connect("localhost","root"); mysql_select_db("dummydpev7"); $isXdocExist=mysql_query("SELECT file_Path,file_Name FROM xdocument WHERE file_Path='$_filePath' AND file_Name='$node'"); $docId=0; if(mysql_num_rows($isXdocExist)==1) { print "Entry already exists!"; $docId=mysql_next_id("xdocument")-1; } else { mysql_query("INSERT INTO xdocument (file_Path,file_Name) VALUES ('$_filePath','$node')"); $docId=mysql_next_id("xdocument")-1; } print "<br />".$docId; writeXMLtoDBViaDOM($dom->documentElement,$labelPath,$docId,$_filePath); } //ELSE else //Please upload Valid XML print "Problem with XML file being uploaded."; ?> The question in point is how do I extract the file I uploaded to set to $_filePath?? in the script so that I pass it to my function writeXMLtoDBviaDOM?? Please any help much appreciated! I am trying to retrieve an xml file from a webservice. I cant use the original server since it gags on non latin characters, unicode?, that is what the LOC says. The other server does work with non latin characters BUT it is too slow with file_get_contents, takes a minute to get anything, so slow you cant even use it in the program. YET, retrieves the xml fast in the browser window. So, what can I do that will work fast like it should? Code: [Select] //original database server, file_get_contents is faster, about 3 to 10 seconds //$request= 'http://z3950.loc.gov:7090/voyager?version=1.1&operation=searchRetrieve'.$query.$test2.'&startRecord='.$offset.'&maximumRecords=20'; //new one that can handle non latin characters //file_get_contents is SLOW, so slow to be unusable, about a minute or more $request='http://lx2.loc.gov:210/LCDB?version=1.1&operation=searchRetrieve'.$query.$test2.'&startRecord='.$offset.'&maximumRecords=20'; $raw_xml = file_get_contents($request); $filename = dirname(__FILE__)."/loc.xml"; $fp = fopen($filename, "w"); fwrite($fp, $raw_xml); fclose ($fp); Hello, I am new to the forum and somewhat new to php, nice to meet you all. This is the first time I have ever really scripted with PHP so I'm still learning about all the tools I have and what I have to call things in PHP. I have a list of urls and as I loop through each one, I'd like to be able to get information from the webpage. The <title> would be a good start. I also want to know the best way for me to compare data I have. I'll show the basic code below, but I successfully go through each url in this text file. I put it in a <ul><li> list just fine. So if $url == http://www.youtube.com/file how is the normal way to check and see if the word "youtube" is in $url? I found preg_match() but I think I'm approaching the whole thing wrong because I get no output. I am an intermediate to somewhat advanced scripter in other languages similar to php, I just need to learn how you do the normal things in PHP. So I'd like to compare a string "youtube" to a variable '$url'. And I would like to be able to grab the title or other info from the file $url. Here is what I have so far. (Recent research showed me how I should do this with an XML file so I will probably change the .txt to .xml) Can you please tell me what to look for as I have been searching and can't really find a comprehensive answer. I changed the whole page to an echo trying to fix something last night. Before it was written like.. Code: [Select] <?php if ($true) { $var = value ?> <html code>The value is <?php $var ?> .</html code> <?php } ?> Code: [Select] /index.php <?php include 'include/header.html'; echo "<div id='wrapper'> <div id='left'> <div class='article'> <br /> <p>"; echo "Today is " . date("l") . ", the " . date("jS") . " of " . date("F") . "."; $lines = file('data/news.txt'); if ($lines){ foreach ($lines as $line_num => $line) { $url = htmlspecialchars($line); //Now I have url. I want to check the url and get the <title> & misc. data. //if youtube is in $url {html code to embed youtube}; //my attempt was $x = file($url); but I got a lot of 404 and 403 errors. //now I fill html. echo "<ul id='menu1' class='auroramenu'> <li><a href='#'>Story ".$line_num."</a> <a style='display: none;' class='aurorashow' href='#'></a> <a style='display: inline;' class='aurorahide' href='#'></a> <ul> <br /> <p>".$url."</p><br /> <li style='text-align:right;'><a href='".$url."' target='_blank'>Read the story.</a> </li> </ul> </li> </ul>"; } } echo "</p><br /> </div> </div> <div id='right'>"; include 'include/sidebar.html'; echo "</div><br class='clr' /></div><br />"; include 'include/footer.html'; ?> Thank you for your help. Hi. I am trying to create a simple video file server. I finished the skeleton of it but when it came to creating the multitude of pages I realized that there could be an easier way to do it.
I started out basically getting the folder names in the server then printing them on the page.
<?php $dirs = glob("*", GLOB_ONLYDIR); echo '<ul>'; foreach($dirs as $dir) { $forbidden_folders = array("not4u", "ignore", Styles); $filename = str_replace($forbidden_folders, '', $dir); if (!empty($filename)) { echo '<li><a href="'.$dir.'">'.$dir.'</a></li>'; } } echo '</ul>' ?>Then I created in each of the folders with files a php file with this code: <?php function date_sort_desc($a, $b) { preg_match('/\w+ \d{4}/', $a, $matches_a); preg_match('/\w+ \d{4}/', $b, $matches_b); $timestamp_a = strtotime($matches_a[0]); $timestamp_b = strtotime($matches_b[0]); if ($timestamp_a == $timestamp_b) return 0; return $timestamp_a < $timestamp_b; } $files = array(); $dir = opendir('.'); while(false != ($file = readdir($dir))) { if(($file != ".") and ($file != "..") and ($file != "index.php")) { $files[] = $file; } } natsort($files); $i = 0; foreach($files as $file) { $i++; $string = str_replace("TV Show Name S1 E$i - ", '' , $file); echo '<div><a href="../Discriptions/'.$file.'.php">'.basename($string, '.m4v').'</a></div><br>'; } ?>This opens up a php file with the same file name as the file to be played containing the episode's thumbnail and description. That file then contains a link pointing back to the real file. The problem here is that I'd have to make a new php file for every file in my collection. I'm wondering if there's somehow a way to simplify all of this. Edited by chrisyroid, 11 August 2014 - 12:13 AM. This is a section of my code that goes and gets videos from any video site. What I’m having issues with is having it post a random title, that are all in a text file called titles.txt. What I’m wanting to accomplish is have my script go pull the video embed code, the duration, the tags, etc. Which all works fine until I get to the title part where it pulls locally from the server from the text file. I'm not an advance programmer so not sure if I am even approaching this correct way. Here is the code I have that is responsible for putting the title in. I appreciate your help. $video = array( ‘user_id’ => $this->user_id, ‘status’ => $this->status, ‘site’ => ‘my site’, ‘id’ => ‘’, ‘embeddable’ => true, ‘url’ => ‘’, ‘titles’ => ‘’, ‘title’ => ‘’, ‘description’ => ‘’, ‘tags’ => ‘’, ‘category’ => ‘’, ‘thumbs’ => array(), ‘duration’ => 0, ‘embed’ => ‘’ ); function random_title () { $titles = file (“titles.txt”, FILE_IGNORE_NEW_LINES); $num = rand (0, intval (count ($titles) / 3)) * 3; return ucwords($titles[$num]); } //Title if(preg_match(’/title="(.*?)"/’, $match, $matches_title)) { $video[‘title’] = random_title(). ’ - My site name’; } else { $this->errors[] = ‘Failed to get video title for ‘.$video[‘url’].’!’; if (!$this->debug) continue; else $debug_e[] = ‘TITLE’; }
Anyone know of a script that will allow you to upload a file and converts it to a specified file format? Folder layout: script/ script/videos/mp4/ } script/videos/ogg/ } folders for converted files from uploaded files script/videos/webm/ } script/videos/swf/ } Video player: Code: [Select] <video width="320" height="240" controls="controls"> <source src="script/videos/mp4/<? echo $movie; ?>.mp4" type="video/mp4" /> <source src="script/videos/ogg/ <? echo $movie; ?> .ogg" type="video/ogg" /> <source src="script/videos/webm/ <? echo $movie; ?> .webm" type="video/webm" /> <object data="script/videos/mp4/ <? echo $movie; ?> .mp4" width="320" height="240"> <embed src="script/videos/swf/ <? echo $movie; ?> .swf" width="320" height="240"> Your browser does not support video </embed> </object> </video> I have searched and searched the web for an answer and cannot find one pleas help? Hi I am trying display thumbs from a directory, BUT , I cannot figure out how to show more then just .jpg. For example, how could I make this code show the following file extensions, .jpg .png .gif ? Here is the code spinet and if you could advise that would be awesome Thanks so much for your time in advance Code: [Select] <?php $largeArray = glob("images/*.jpg"); $counter = 0; foreach (array_slice(glob("images/thumbs/*.jpg"),0,600) as $thumb) { echo ("<div class='thumbgall'><a href='$largeArray[$counter]' rel='lightbox'><img src='$thumb'/></a></div>"); $counter++; } ?> Hi guys, Im trying to resize and create thiumbnails while uploading an image but it doesnt work, as i am new to php and i have followed other tutorials, i might have made a mistake which i dont understand. i have a table called test (find attached image) and what i need is when i upload an image, it copies the location of both image and on fly created thumb into my database i appreciate your help & please excuse me for messed up code <?php session_start(); include ("../global.php"); //welcome messaage echo "Welcome, " .$_SESSION['username']."!<p>"; $username=$_SESSION['username']; //get user id & credit limit $query=mysql_query("SELECT id FROM users"); while($row = mysql_fetch_array($query)) { $id = $row['id']; echo $id; } $credit=mysql_query("SELECT credit FROM users"); while($row = mysql_fetch_array($credit)) { $creditcheck = $row['credit']; echo "your credit is: $creditcheck"; } $reference = rand(11111111,99999999); //image1 define ("MAX_SIZE","100"); define ("WIDTH","150"); define ("HEIGHT","100"); function make_thumb($img_nameone,$filenameone,$new_w,$new_h) { $ext=getExtension($img_nameone); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_imgone=imagecreatefromjpeg($img_nameone); if(!strcmp("png",$ext)) $src_imgone=imagecreatefrompng($img_nameone); $old_x=imageSX($src_imgone); $old_y=imageSY($src_imgone); $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; } $dst_imgone=ImageCreateTrueColor($thumb_w,$thumb_h); imagecopyresampled($dst_imgone,$src_imgone,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); if(!strcmp("png",$ext)) imagepng($dst_imgone,$filenameone); else imagejpeg($dst_imgone,$filenameone); imagedestroy($dst_imgone); imagedestroy($src_imgone); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if ($creditcheck<=0) Header("Location: buy-credit.php"); else if ($creditcheck>=0){ if(isset($_POST['register'])) $submit = mysql_query("INSERT INTO test (reference) VALUES ('$reference')"); { $image=$_FILES['myfileone']['nameone']; if ($image) { $filename = stripslashes($_FILES['myfileone']['nameone']); $extension = getExtension($filenameone); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { $size=getimagesize($_FILES['myfileone']['tmp_name']); $sizekb=filesize($_FILES['myfileone']['tmp_name']); if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } $image_nameone=time().'.'.$extension; $newname="rentimages/".$image_nameone; $copied = copy($_FILES['myfileone']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { $thumb_name='rentimages/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} if(isset($_POST['register']) && !$errors) { $locationone="rentimages/$nameone"; $image1 = mysql_query ("UPDATE test SET image1='$newname', thumb='$thumb_name' WHERE reference='$referenceran'"); } } } ?> <html> <body> <form action='imagetests.php' method='POST' enctype='multipart/form-data'> File: <input type='file' name='myfileone'><p /> <input type='submit' name='register' value='Update'> <p /> </body> </html> Hi folks... Trying to get a bit of gallery code to work the way I want it to and would appreciate some feedback from more experienced folks... What it's doing, or is supposed to be doing, is taking a thumb called 'thumb.jpg' from each folder within my gallery folder and displaying it in reverse order on a page. I only want a maximum number of images to display on the page at any one time, so that if I end up uploading loads of folders in the future, it will only display a set amount of thumbs on one page. I want the thumbs displayed in reverse order, so that the newest appears first. Here's the code... and as far as I can see, it should work... and I'm sure I have had it working in the past (I've just come back to working on it after a while) however now, it's putting the thumbs in a random order. My folders are all in the gallery folder, and are named 001, 002, 003, 004, 005, 006, etc. I want them to display with 006 at the top and to de-increment, but only for the most recent 16 folders. Code: [Select] <?php $images = "gallery/"; # Location of galleries $cols = 4; # Number of columns to display $max = 16; # Maximum number of galleries to show if ($handle = opendir($images)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $files[] = $file; } } closedir($handle); } $colCtr = 0; echo "<div id=\"updates\"><table><tr>"; $c = count($files) - 1; //$c = the number of files in the array, minus 1 = highest index in the array. for($i = $c; $i > ($c - $max); $i--) //$i = $c, $i is greater than the array count minus $max, $i de-increments on each loop. This will give us a countdown for the number of galleries required. { if($colCtr %$cols == 0) echo "</tr><tr>"; echo "<td><img src=\"" . $images . $files[$i] . "/thumb.jpg\" width=\"240px\" height=\"180px\" alt=\"" . $alt . "\" /></td>"; //echo'ing out the $file[$i] on the loop, will give us the last required number of files in the file array. $colCtr++; } echo "</table></div>" . "\r\n"; ?> I also want to work out how to set a start number for the galleries, so that I can paginate them... so, once I have 36 galleries (for example) I can have the latest 16 on the first page, and the next 16 on the 2nd page... and the 4 that run over would drift off into obscurity until I get round to deleting them... maybe with a variable named $min... How would I do that...? Like this, or differently? : Code: [Select] <?php $images = "gallery/"; # Location of galleries $cols = 4; # Number of columns to display $min = 16; # Minimum number of galleries to show $max = 32; # Maximum number of galleries to show if ($handle = opendir($images)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $files[] = $file; } } closedir($handle); } $colCtr = 0; echo "<div id=\"updates\"><table><tr>"; $c = count($files) - 1; //$c = the number of files in the array, minus 1 = highest index in the array. for($i = $c; ($i + $min) > ($c - $max); $i--) //$i = $c, $i plus $min is greater than the array count minus $max, $i de-increments on each loop. This will give us a countdown for the number of galleries required. { if($colCtr %$cols == 0) echo "</tr><tr>"; echo "<td><img src=\"" . $images . $files[$i] . "/thumb.jpg\" width=\"240px\" height=\"180px\" alt=\"" . $alt . "\" /></td>"; //echo'ing out the $file[$i] on the loop, will give us the last required number of files in the file array. $colCtr++; } echo "</table></div>" . "\r\n"; ?> Any help greatly appreciated! Hi the file file upload whenever i upload an image to main directory it saves one image into photos folder and copy another into thumbs folder but whenever i upload image to a different album (not main directory) it doesnt copy the other image to thumbs folder what i'm i doing wrong this is the line that i chose the folder... function make_locations ($locs) { $html = '<select name="locations" class="input"><option value="0">-- Main Directory --</option>'; foreach ($locs AS $key => $value) { $html .= '<option value="' .$value['album_id']. '">' .addslashes($value['album_name']). '</option>'; } $html .= '</select>'; return $html; } this is the whole code <?php /** * create a sub album directory for photos * to be stored in */ function create_album ($album_name, $sub_album = 0) { global $db; $sql = "INSERT INTO " .ALBUMS_TABLE. " ( album_name, sub_album ) VALUES ( '" .addslashes($album_name). "', " .intval($sub_album). " )"; if ($db->query($sql)) { return TRUE; } else { return FALSE; } } /** * get a list of sub albums */ function get_albums ($sub_album = 0) { global $db; $sql = "SELECT * FROM " .ALBUMS_TABLE. " WHERE sub_album = " .intval($sub_album); $db->query($sql); // initialise album storage $albums = array(); while ($row = $db->fetch()) { $albums[] = $row; } return $albums; } /** * get a list of photos within an album */ function get_photos ($album = 0) { global $db; $sql = "SELECT * FROM " .PHOTOS_TABLE. " WHERE album_id = " .intval($album). " ORDER BY photo_id ASC"; $db->query($sql); // initialise album storage $photos = array(); while ($row = $db->fetch()) { $photos[] = $row; } return $photos; } /** * get a large version of a particular photo */ function get_large ($photo, $album = 0, $next = '') { global $db, $template, $account_details; // shall we get the next / previous photo switch ($next) { case "next" : $next_sql = "AND photo_id > " .intval($photo). " ORDER BY photo_id ASC"; break; case "previous" : $next_sql = "AND photo_id < " .intval($photo). " ORDER BY photo_id DESC"; break; default : $next_sql = "AND photo_id = " .intval($photo); break; } $sql = "SELECT * FROM " .PHOTOS_TABLE. " WHERE album_id = " .intval($album). " " .$next_sql. " LIMIT 1"; $db->query($sql); if ($db->num_rows() == 0) { return ''; } else { $photo_info = $db->fetch(); // note the total directory $location = 'photos/' .$photo_info['photo_proper']; // now we need to resize list($width, $height) = getimagesize($location); if ($width < 300) { $new_width = $width; $new_height = $height; } elseif ($width > $height) { $new_width = 300; $new_height = $height * ($new_width / $width); } elseif ($width < $height) { $new_width = $width * ($new_height / $height); $new_height = 300; } // work out the next link $next = '<a href="portfolio.php?p=' .$photo_info['photo_id']. '&a=' .$photo_info['album_id']. '&next=next">Next</a>'; $previous = '<a href="portfolio.php?p=' .$photo_info['photo_id']. '&a=' .$photo_info['album_id']. '&next=previous">Previous</a>'; return '<div id="largephoto"><img src="' .$location. '" height="' .$new_height. '" width="' .$new_width. '" class="large"><br /><div id="prevnext">' .$previous. ' :: ' .$next. '</div></div>'; } } /** * get an array of locations */ function get_locations () { global $db; // initialise array $locations = array(); // select albums $sql = "SELECT album_id, album_name FROM " .ALBUMS_TABLE; $db->query($sql); while ($row = $db->fetch()) { $locations[] = $row; } return $locations; } /** * make the locations table */ function make_locations ($locs) { $html = '<select name="locations" class="input"><option value="0">-- Main Directory --</option>'; foreach ($locs AS $key => $value) { $html .= '<option value="' .$value['album_id']. '">' .addslashes($value['album_name']). '</option>'; } $html .= '</select>'; return $html; } /** * delete an album from the database * does not delete the photos in it */ function delete_albums ($album_ids) { global $db; if (sizeof($album_ids) > 0) { $sql = "DELETE FROM " .ALBUMS_TABLE. " WHERE album_id IN (" .implode(',', $album_ids). ")"; if ($db->query($sql)) { return TRUE; } } return FALSE; } /** * delete a set of photos */ function delete_photos ($photo_ids) { global $db; if (sizeof($photo_ids) > 0) { // select photo names for deletion $sql = "SELECT photo_proper FROM " .PHOTOS_TABLE. " WHERE photo_id IN (" .implode(',', $photo_ids). ")"; $db->query($sql); $unlink_ids = array(); while ($row = $db->fetch()) { $unlink_ids[] = $row['photo_proper']; } // now delete the photos if (sizeof($unlink_ids) > 0) { $sql = "DELETE FROM " .PHOTOS_TABLE. " WHERE photo_id IN (" .implode(',', $photo_ids). ")"; if ($db->query($sql)) { // remove photo from directory for ($i = 0; $i < sizeof($unlink_ids); $i++) { unlink("photos/" .$unlink_ids[$i]); unlink("photos/thumbs/" .$unlink_ids[$i]); } return TRUE; } } } return FALSE; } /** * upload a set of files */ function upload_files ($save_dir = '', $album = 0) { global $db; // check the save dir is writable if (!is_writable($save_dir)) { return FALSE; } // specify allowed file types $allowed_types = array ( 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif' ); // keep a list of uploaded files $uploaded = array(); // store bytes uploaded $total_bytes = 0; // go through the list of files while (list($key, $value) = each($_FILES['userfile']['name'])) { // check file has been passed if (!empty($value)) { // find extension $extension = substr($_FILES['userfile']['name'][$key], strpos($_FILES['userfile']['name'][$key],".") + 1); // time + $key for name $name = time(). "_" .$key. "." .$extension; // save url $add = $save_dir. "/" .$name; if (move_uploaded_file($_FILES['userfile']['tmp_name'][$key], $add)) { chmod($add, 0777); // add photo to database create_photo($_FILES['userfile']['name'][$key], $name, $album); } } } return TRUE; } /** * insert photo details into the database */ function create_photo ($photo_name, $key_name, $album = 0) { global $db; // get the filesize if (!$size = filesize("photos/" .$key_name)) { $size = 0; } // insert the photo in the database $sql = "INSERT INTO " .PHOTOS_TABLE. " ( photo_name, photo_date, photo_proper, photo_size, album_id ) VALUES ( '" .addslashes($photo_name). "', " .time(). ", '" .addslashes($key_name). "', " .intval($size). ", " .$album. " )"; if ($db->query($sql)) { return TRUE; } else { return FALSE; } } /** * get a complete raw copy of the directory */ function get_dir_contents ($dir) { // declare content array $contents = array(); // check gallery exists if (is_dir($dir)) { if ($handle = opendir($dir)) { while (FALSE !== ($file = readdir($handle))) { if ($file != '.' && $file != '..' && $file != 'thumbs') { if (file_exists($dir. '/thumbs/' .$file) || thumbnail($file, $dir. '/' .$file, $dir. '/thumbs')) { $contents[] = $dir. '/thumbs/' .$file; } else { $contents[] = 'no_image.gif'; } } } } } return $contents; } /** * create a thumbnail of a photo and store it * in the thumbs directory */ function thumbnail ($filename, $source_file, $destination, $new_h = 75, $new_w = 75) { if (!is_file($source_file)) { return FALSE; } // get the image details list($old_w, $old_h, $type) = getimagesize($source_file); // create source image switch($type) { case 1: $source = @imagecreatefromgif($source_file); break; case 2: $source = @imagecreatefromjpeg($source_file); break; case 3: $source = @imagecreatefrompng($source_file); break; default : return FALSE; } // work out dimensions if ($old_w < $old_h) { $thumb_w = $new_w; $thumb_h = $old_h * ($new_h / $old_w); } elseif ($old_w > $old_h) { $thumb_w = $old_w * ($new_w / $old_h); $thumb_h = $new_h; } elseif ($old_w == $old_h) { $thumb_w = $new_w; $thumb_h = $new_h; } $thumb = @imagecreatetruecolor($thumb_w, $thumb_h); // create image imagecopyresized($thumb, $source, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_w, $old_h); // check we have a proper destination if (!is_dir($destination)) { mkdir($destination, 0777); } // save image switch ($type) { case 1: case 2: imagejpeg($thumb, $destination. '/' .$filename); break; case 3: imagepng($thumb, $destination. '/' .$filename); break; } // memory saving imagedestroy($thumb); imagedestroy($source); // thumbnail created successfully return TRUE; } /** * make the table to show the directories and photos */ function make_table ($list, $type, $row = 3) { // initialize gallery html array $gallery_html = array(); // check if we have a list > 0 if ($size = sizeof($list)) { switch ($type) { case "GALLERIES" : $gallery_html[] = '<div id="galleries">'; break; case "PHOTOS" : case "RAW" : $gallery_html[] = '<div id="photos">'; break; } // loop through list for ($i = 0; $i < sizeof($list); $i++) { // shall we open a new list if ($i % $row == 0) { $gallery_html[] = '<ul>'; } // add to list switch ($type) { case "GALLERIES" : // create the delete link $delete_link = ''; if ($_SESSION['logged_in']) { $delete_link = '[ <a href="admin.php?mode=deletealbum&a=' .$list[$i]['album_id']. '">Delete</a> ]'; } $gallery_html[] = '<a href=portfolio.php?albums='.$list[$i]['album_id'].'><img src="folder.gif" class="directory"><br />' .addslashes($list[$i]['album_name']). '</a><br />' .$delete_link. '</li>'; break; case "PHOTOS" : // construct photo name $name = $list[$i]['photo_proper']; // construct location $location = "photos/"; // create thumbnail if (!file_exists($location. "/thumbs/" .$name)) { thumbnail($name, $location. "/" .$name, $location. "/thumbs/"); } // construct date $date = '<div class="date">' .date("d/m G:ia", $list[$i]['photo_date']). '</div>'; // create the delete link $delete_link = ''; if ($_SESSION['logged_in']) { $delete_link = '[ <a href="admin.php?mode=deletephoto&p=' .$list[$i]['photo_id']. '">Delete</a> ]'; } // image information list($width, $height) = getimagesize($location . $list[$i]['photo_proper']); // add to the html $gallery_html[] = '<li><a href="' .$location . $list[$i]['photo_proper']. '" rel="lightbox[racing]" title="Photos"><img src="' .$location. "/thumbs/" .$name. '" class="picture"><br />View</a><br />' .$delete_link. '</li>'; break; case "RAW" : $gallery_html[] = '<li><img src="' .$list[$i]. '" class="picture"></li>'; break; } // shall we close the list if ( ($i + 1) % $row === 0 || ($i + 1) == $size) { $gallery_html[] = '</ul>'; } } $gallery_html[] = '</div>'; } return implode('', $gallery_html); } ?> I'm new to php and i have a html form with 2 forms and 2 submit buttons, 1 of the forms is solely for uploading an image i downloaded the php script as i don't understand the code well enough to write it myself. The second form asks for your name and email then when you click submit it writes a new html file with the included information. I have managed to upload a file successfully and write the html document with the information successfully but i can't get the image to write into the html document. My file_upload.php script contains the variable for the image name, now how would i get the variable string from file_upload.php and use that name in compile.php. Here's my code. -------------- Form.html -------------- <!DOCTYPE html> <html lang="en"> <head> <title></title> </head> <body> <form action="compile.php" method="post"> <p>input name:<input type="text" name="name"/></p><br /> <p>email:<input type="text" name="email" /></p><br /> </form> <br /> <form enctype="multipart/form-data" method="post" action="file_upload.php"> Choose your file he <input name="file1" type="file" /><br /><br /> <input type="submit" value="Upload It" /> </form> </body> </html> ------------- compile.php ------------- <?php $name = $_POST['name']; $price = $_POST['price']; $desc = $_POST['desc']; $file = "new.html"; $handle = fopen($file,'w'); $data = "<!DOCTYPE html> <html> <head> <title></title> </head> <body> <table style='border-radius:8px;'> <tr> <td style='border-radius:8px;'> <h1>$name</h1> </td> </tr> </table> <table> <tr> <td> <ul> <lh>Product name: $name</lh> <br><br> <li>Price: $price</li><br> <li>Description: $desc</li><br> </ul> </td> <td> <img src='uploads/$fileName' width='' height='' alt='' title='' /> </td> </tr> </table> </body> </html>"; fwrite($handle, $data); print "data written"; fclose($handle); ?> ------------ file_upload.php ------------ <?php // Set local PHP vars from the POST vars sent from our form using the array // of data that the $_FILES global variable contains for this uploaded file $fileName = $_FILES["file1"]["name"]; // The file name $fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["file1"]["type"]; // The type of file it is $fileSize = $_FILES["file1"]["size"]; // File size in bytes $fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true // Specific Error Handling if you need to run error checking if (!$fileTmpLoc) { // if file not chosen echo "ERROR: Please browse for a file before clicking the upload button."; exit(); } else if($fileSize > 5000000000) { // if file is larger than we want to allow echo "ERROR: Your file was larger than 5mb in file size."; unlink($fileTmpLoc); exit(); } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) { // This condition is only if you wish to allow uploading of specific file types echo "ERROR: Your image was not .gif, .jpg, or .png."; unlink($fileTmpLoc); exit(); } // Place it into your "uploads" folder mow using the move_uploaded_file() function move_uploaded_file($fileTmpLoc, "uploads/$fileName"); // Check to make sure the uploaded file is in place where you want it if (!file_exists("uploads/$fileName")) { echo "ERROR: File not uploaded<br /><br />"; echo "Check folder permissions on the target uploads folder is 0755 or looser.<br /><br />"; echo "Check that your php.ini settings are set to allow over 2 MB files, they are 2MB by default."; exit(); } // Display things to the page so you can see what is happening for testing purposes echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; echo "It is a <strong>$fileType</strong> type of file.<br /><br />"; echo "The Error Message output for this upload is: <br />$fileErrorMsg"; ?> I am trying to use the variable $RATETHESE to include an array into file A. The array is in file B. PhP File A include_once(dirname(__FILE__) . '/PhpFileB.php'); global $RATETHESE; $VALID_RATING_IDS = $RATETHESE; Php File B $RATETHESE = "array("1", "2");" For some reason it is printing the array on the page, and the array is not being used to run the script. Did i do anything wrong? Hi Guys, I'm working on an image resizer, to create thumbnails for my page. The resizer works on principle of include a DIRECT link to the image. But what I want to do is put in the PHP Variable in the URL string, so that it points to that file and resizes it accordingly. My code is as follows : Code: [Select] <img src="thumbnail.php?image=<?php echo $row_select_property['image_url']; ?> Image Resize : Code: [Select] <?php // Resize Image To A Thumbnail // The file you are resizing $image = '$_GET[image_url]'; //This will set our output to 45% of the original size $size = 0.45; // This sets it to a .jpg, but you can change this to png or gif header('Content-type: image/jpeg'); // Setting the resize parameters list($width, $height) = getimagesize($image); $modwidth = $width * $size; $modheight = $height * $size; // Creating the Canvas $tn= imagecreatetruecolor($modwidth, $modheight); $source = imagecreatefromjpeg($image); // Resizing our image to fit the canvas imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); // Outputs a jpg image, you could change this to gif or png if needed imagejpeg($tn); ?> What I am trying to do is pass on the variable "image=<?php echo $row_select_property['image_url']; ?>" to the Thumbnail script. At the moment I am passing it through the URL string, but it doesnt seem to load the graphic. I'll try expand on this more, should you have questions as I am finding it a little difficult to explain. Thanks in advance. |