PHP - A Very Small Problem With Uploading Image In My Script
I have this code and its working awsomely fine if i provide a direct link of an uploaded image.
Just and just only one problem i am not able to pass my uploaded image to facebook->api (whether its valid or not) and the following always echo echo 'Only jpg, png and gif image types are supported!'; i even remove the check on image type and try to get the image from $img = realpath($_FILES["pic"]["tmp_name"]); but $img gets nothing in it and uploads a by default empty image on facebook as my page Kindly check my following code and let me know what is wrong with my code and what should i do instead to upload images Online link of the following CODE: http://radiations3.com/facebook/1.php Code: [Select] <? require 'src/facebook.php'; $app_id = "364900470214655"; $app_secret = "xxxxxxxx"; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'cookie' => true, 'fileUpload' => true, )); $user = $facebook->getUser(); //echo $user; if(($facebook->getUser())==0) { header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos,offline_access,manage_pages'))}"); exit; } else { $accounts_list = $facebook->api('/me/accounts'); echo "i am connected"; } $valid_files = array('image/jpeg', 'image/png', 'image/gif'); //to get the page access token to post as a page foreach($accounts_list['data'] as $account){ if($account['id'] == 194458563914948){ // my page id =123456789 $access_token = $account['access_token']; echo "<p>Page Access Token: $access_token</p>"; } } //posting to the page wall if (isset($_FILES) && !empty($_FILES)) { if( !in_array($_FILES['pic']['type'], $valid_files ) ) { echo 'Only jpg, png and gif image types are supported!'; } else{ #Upload photo here $img = realpath($_FILES["pic"]["tmp_name"]); $attachment = array('message' => 'this is my message', 'access_token' => $access_token, 'name' => 'This is my demo Facebook application!', 'caption' => "Caption of the Post", 'link' => 'example.org', 'description' => 'this is a description', 'picture' => '@' . $img, 'actions' => array(array('name' => 'Get Search', 'link' => 'http://www.google.com')) ); $status = $facebook->api('/194458563914948/feed', 'POST', $attachment); // my page id =123456789 var_dump($status); } } ?> <body> <!-- Form for uploading the photo --> <div class="main"> <p>Select a photo to upload on Facebook Fan Page</p> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data"> <p>Select the image: <input type="file" name="pic" /></p> <p><input class="post_but" type="submit" value="Upload to my album" /></p> </form> </div> </body> Similar TutorialsMe and a friend are working on a nice secure Image Upload Script. The Upload Class <?php class imageUploader { public $image; // [name], [type], [tmp_name], [error], [size] public $maxFileSize; public $imageExtension; public function __construct($image, $max_file_size) { $this->image = $image; $this->maxFileSize = $max_file_size; } public function isValidImage() { $validExts = array("gif" => "image/gif", "jpeg" => "image/jpeg", "png" => "image/png"); if(in_array(strtolower($this->image["type"]), $validExts) == true) { foreach($validExts as $name => $value) { if(strtolower($this->image["type"]) == $value) { $this->imageExtension = $name; break; } } return true; } else { return false; } } public function isValidSize() { if($this->image["size"] > $this->maxFileSize) { return false; } else { return true; } } public function uploadImage() { if($this->image["error"] > 0) { $errors[] = "An error has occurred"; } elseif($this->isValidImage() == false) { $errors[] = "Invalid file type. Only use JPG, GIF or PNG"; } elseif($this->isValidSize() == false) { $errors[] = "Max file size exceeded."; } if(count((array) $errors) == 0) { move_uploaded_file($this->image["tmp_name"], "Images/" . $this->generateName(rand(10, 15)) . time() . "." . $this->imageExtension); } else { echo implode("<br />", $errors); } } public function createThumbnails() { } public function resizeImage($size_y, $size_x) { } public function generateName($length) { $randstr = ""; for ($i = 0; $i < $length; $i++) { $randnum = mt_rand(0, 61); if ($randnum < 10) { $randstr .= chr($randnum + 48); } elseif ($randnum < 36) { $randstr .= chr($randnum + 55); } else { $randstr .= chr($randnum + 61); } } return $randstr; } } ?> The Everyday HTML Code: [Select] <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>Image</td> <td><input type="file" name="file" id="file" /></td> <td><input type="submit" name="submit" value="Submit" /></td> </tr> </table> </form> My friend did most of the work, but had to go to sleep. My problem is I have a deadline to finish this in under 3 hours for use on my website. What I need it to do is create thumbnails in a /Thumbnail/ sub-folder, with thumbnails being cropped to 100px x 100px. If the full image is larger than 600px x 600px they would have to be resized down to nothing more than 600px for the longest side. I wouldn't mind if they were 300px x 600px, just nothing larger than 600px. I'm willing to pay for this to be completed, I only have roughly $50 though. I know this isn't a freelance area, but it kind of suits this area too with a freelance option. After the upload script is done, I have to work on a php system to get the images and display them, so that I'm not directly linking images. So anyone got some spare time to help out? ok i have a image uploading script here, it works fine but theres one thing im unhappy with when i first downloaded it it had 1 working one, and the rest examples which you basically have to put together yourself with the sample code (doesen't work without adding missing coding), i have done all that then i took the time to add a random string prefix, im new at php so it took me awhile to work out which strings would work in the right area. now this is what i need help with, when it uploads it has two options, download and remove, these both work fine, but on the file uploader that does work it has "file uploaded to "http://site.com/image.png" the example of course did not work (had loading bar working, and etc but didn't upload or have the feature i just mentioned) and the coder of the script used javascript and inner html for the file uploaded.... etc, because it uploads without refreshing, only thing is i cant seem to get it to work with the new random string i put in, i tried to recreate one with the same type of thing they used for the filename but it didn't work well here is the code, hope you can help. image upload handler Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php $uploader=new PhpUploader(); if(@$_GET["download"]) { $fileguid=$_GET["download"]; $mvcfile=$uploader->GetUploadedFile($fileguid); header("Content-Type: application/oct-stream"); header("Content-Disposition: attachment; filename=\"" . $mvcfile->FileName . "\""); readfile($mvcfile->FilePath); } if(@$_POST["delete"]) { $fileguid=$_POST["delete"]; $mvcfile=$uploader->GetUploadedFile($fileguid); unlink($mvcfile->FilePath); echo("OK"); } if(@$_POST["guidlist"]) { $guidarray=explode("/",$_POST["guidlist"]); //OUTPUT JSON echo("["); $count=0; foreach($guidarray as $fileguid) { $mvcfile=$uploader->GetUploadedFile($fileguid); if(!$mvcfile) continue; //process the file here , move to some where //rename(...) if($count>0) echo(","); echo("{"); echo("FileGuid:'");echo($mvcfile->FileGuid);echo("'"); echo(","); echo("FileSize:'");echo($mvcfile->FileSize);echo("'"); echo(","); echo("FileName:'");echo($mvcfile->FileName);echo("'"); echo("}"); $count++; } echo("]"); } //USER CODE: $rand = substr(md5(microtime()),rand(0,26),10); $targetfilepath= 'savefiles/' . $rand->rand . $mvcfile->FileName; if( is_file ($targetfilepath) ) unlink($targetfilepath); $mvcfile->MoveTo( $targetfilepath ); exit(200); ?> image upload(with form to choose file) Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Ajax - Build attachments table </title> <link href="demo.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var handlerurl='ajax-attachments-handler.php' function CreateAjaxRequest() { var xh; if (window.XMLHttpRequest) xh = new window.XMLHttpRequest(); else xh = new ActiveXObject("Microsoft.XMLHTTP"); xh.open("POST", handlerurl, false, null, null); xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); return xh; } </script> <script type="text/javascript"> var fileArray=[]; function ShowAttachmentsTable() { var table = document.getElementById("filelist"); while(table.firstChild)table.removeChild(table.firstChild); AppendToFileList(fileArray); } function AppendToFileList(list) { var table = document.getElementById("filelist"); for (var i = 0; i < list.length; i++) { var item = list[i]; var row=table.insertRow(-1); row.setAttribute("fileguid",item.FileGuid); row.setAttribute("filename",item.FileName); var td1=row.insertCell(-1); td1.innerHTML="<img src='phpuploader/resources/circle.png' border='0'/>"; var td2=row.insertCell(-1); td2.innerHTML=item.FileName; var td4=row.insertCell(-1); td4.innerHTML="[<a href='"+handlerurl+"?download="+item.FileGuid+"'>download</a>]"; var td4=row.insertCell(-1); td4.innerHTML="[<a href='javascript:void(0)' onclick='Attachment_Remove(this)'>remove</a>]"; } } function Attachment_FindRow(element) { while(true) { if(element.nodeName=="TR") return element; element=element.parentNode; } } function Attachment_Remove(link) { var row=Attachment_FindRow(link); if(!confirm("Are you sure you want to delete '"+row.getAttribute("filename")+"'?")) return; var guid=row.getAttribute("fileguid"); var xh=CreateAjaxRequest(); xh.send("delete=" + guid); var table = document.getElementById("filelist"); table.deleteRow(row.rowIndex); for(var i=0;i<fileArray.length;i++) { if(fileArray[i].FileGuid==guid) { fileArray.splice(i,1); break; } } } function CuteWebUI_AjaxUploader_OnPostback() { var uploader = document.getElementById("myuploader"); var guidlist = uploader.value; var xh=CreateAjaxRequest(); xh.send("guidlist=" + guidlist); //call uploader to clear the client state uploader.reset(); if (xh.status != 200) { alert("http error " + xh.status); setTimeout(function() { document.write(xh.responseText); }, 10); return; } var list = eval(xh.responseText); //get JSON objects fileArray=fileArray.concat(list); AppendToFileList(list); } function ShowFiles() { var msgs=[]; for(var i=0;i<fileArray.length;i++) { msgs.push(fileArray[i].FileName); } alert(msgs.join("\r\n")); } </script> </head> <body> <div class="demo"> <h2>Building attachment table (AJAX)</h2> <p>This sample demonstrates how to build your own attachment table.</p> <?php $uploader=new PhpUploader(); $uploader->MaxSizeKB=10240; $uploader->Name="myuploader"; $uploader->MultipleFilesUpload=true; $uploader->InsertText="Select multiple files (Max 10M)"; $uploader->AllowedFileExtensions="*.jpg,*.png,*.gif,*.bmp,*.txt,*.zip,*.rar"; $uploader->Render(); ?> <br/><br/> <table id="filelist" style='border-collapse: collapse' class='Grid' border='0' cellspacing='0' cellpadding='2'> </table> <br/><br/> <button onclick="ShowFiles()">Show files</button> </div> <script type='text/javascript'> //this is to show the header.. ShowAttachmentsTable(); </script> <script type='text/javascript'> function CuteWebUI_AjaxUploader_OnTaskComplete(task) { var div=document.createElement("DIV"); var link=document.createElement("A"); link.setAttribute("href","savefiles/"+task.rand); link.innerHTML="You have uploaded file : savefiles/"+task.rand; link.target="_blank"; div.appendChild(link); document.body.appendChild(div); } </script> </body> </html> and here is the phpuploader.php file just in case Hey, I have found a script off the net which uploads an image to a directory but even though it says the image was uploaded successfully - it didn't actually upload it. The folder permission is 775 (im assuming that is correct). The script i found is he http://www.reconn.us/content/view/30/51/ Code: [Select] <?php //define a maxim size for the uploaded images in Kb define ("MAX_SIZE","100"); //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 errro occures. //If the error occures 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['image']['name']; //if it is not empty if ($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['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 and will not upload the file, //otherwise we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message 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=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { 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=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } ?> <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" --> <form name="newad" method="post" enctype="multipart/form-data" action=""> <table> <tr><td><input type="file" name="image"></td></tr> <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr> </table> </form> I was also wondering how do upload images to separate folders related to a UserID ? So i have this page that pretty much displays all the members in the database, and its split into pages using a pagination php script. The problem is that i want the ID number displayed next to it, however the database record id jumps since some records have been deleted. So while there were a total of 1000 records 10 have been removed so instead of showing the accurate ID number of 995 on the last record it displays the number 1000 .... I've tried just assigning a number to each record using the following code... $get_members = "SELECT * FROM members ORDER BY ID ASC LIMIT $rowsperpage OFFSET $offset"; $run_mem_query = mysql_query($get_members) or die(mysql_error()); $club_id = 1; while($member = mysql_fetch_assoc($run_mem_query)){ ?> <li><strong><?php echo $club_id++ ;?>.</strong><?php echo $member['username'] ;?> - <span><?php echo $member['state'] ;?></span></li> <?php } The problem with that is that every time i click to go to the next page the number sequence refreshed back to 1 and starts over.... i've been trying to find a way around his, but can't....does anyone have any solutions to this??? Here's the script that controls the pagination <?php if ($totalpages > 1){ /*********** Start the pagination links ********/ echo "<p>"; // range of num links to show $range = 6; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'>First</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> "; } // end if if($result > 0){ // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " <b>$x</b> "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for }else{ echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>1</a>"; } // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'> Next </a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'> Last </a> "; } // end if echo "</p>\n"; /****** end build pagination links ******/ } ?> I have created a page for users to upload files, but for some reason end users can't access the files. we are getting an access denied page and every time files get uploaded i have to ftp to the site and change the permissions. is there something i am missing? Thank you in advance. Hello all, I'm designing an upload file section for a home medical company. So far it has been going great, I am uploading files and they're being successfully inserted into my MYSQL Table. However, my issue is when I download the files they claim to be corrupted and unusable. If I save the PDF files to my desktop they won't open at all, they claim to be corrupted. If I download a JPG and then open it in photshop it warns me the file may be corrupted, knowing it is not I clicked "yes". The jpg actually opens and looks like the image, however about 50 pixels on the bottom get cut off and look like a messy TV screen, if that makes sense. Wondering if anyone has had this similar issue, the uploading part is not the issue - just downloading the files. My Upload Form Code: Code: [Select] <p><a href="upload.php">Upload a File</a> <a href="../admin/admin.php">Back to Control Panel</a></p> <form action="add_file.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> My Add File Code (This is working fine but may cause issues with downloading?) Code: [Select] <?php // Check if a file has been uploaded if(isset($_FILES['uploaded_file'])) { // Make sure the file was sent without errors if($_FILES['uploaded_file']['error'] == 0) { // Connect to the database $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Gather all required data $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']); $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']); $data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name'])); $size = intval($_FILES['uploaded_file']['size']); // Create the SQL query $query = " INSERT INTO `file` ( `name`, `mime`, `size`, `data`, `created` ) VALUES ( '{$name}', '{$mime}', {$size}, '{$data}', NOW() )"; // Execute the query $result = $dbLink->query($query); // Check if it was successfull if($result) { echo 'Success! Your file was successfully added!'; } else { echo 'Error! Failed to insert the file' . "<pre>{$dbLink->error}</pre>"; } } else { echo 'An error accured while the file was being uploaded. ' . 'Error code: '. intval($_FILES['uploaded_file']['error']); } // Close the mysql connection $dbLink->close(); } else { echo 'Error! A file was not sent!'; } // Echo a link back to the main page echo '<p>Click <a href="upload.php">here</a> to go back</p>'; ?> My List File Code (This is working fine also, but does contain the link that I click when I want to download a file) Code: [Select] <?php $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Query for a list of all existing files $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file`'; $result = $dbLink->query($sql); // Check if it was successfull if($result) { // Make sure there are some files in there if($result->num_rows == 0) { echo '<p>There are no files in the database</p>'; } else { // Print the top of a table echo '<table width="100%"> <tr> <td><b>Name</b></td> <td><b>Mime</b></td> <td><b>Size (bytes)</b></td> <td><b>Created</b></td> <td><b> </b></td> </tr>'; // Print each file while($row = $result->fetch_assoc()) { echo " <tr> <td>{$row['name']}</td> <td>{$row['mime']}</td> <td>{$row['size']}</td> <td>{$row['created']}</td> [u][b]<td><a href='get_file.php?id={$row['id']}'>Download</a></td>[/b][/u] </tr>"; } // Close table echo '</table>'; } // Free the result $result->free(); } else { echo 'Error! SQL query failed:'; echo "<pre>{$dbLink->error}</pre>"; } // Close the mysql connection $dbLink->close(); ?> And here is my Get File page. This is where my problem lies. (I think) Code: [Select] <?php // Make sure an ID was passed if(isset($_GET['id'])) { // Get the ID $id = intval($_GET['id']); // Make sure the ID is in fact a valid ID if($id <= 0) { die('The ID is invalid!'); } else { // Connect to the database $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Fetch the file information $query = " SELECT `mime`, `name`, `size`, `data` FROM `file` WHERE `id` = {$id}"; $result = $dbLink->query($query); if($result) { // Make sure the result is valid if($result->num_rows == 1) { // Get the row $row = mysqli_fetch_assoc($result); // Print headers header("Content-Type: ". $row['mime']); header("Content-Length: ". $row['size']); header("Content-Disposition: attachment; filename=". $row['name']); // Print data echo $row['data']; } else { echo 'Error! No image exists with that ID.'; } // Free the mysqli resources @mysqli_free_result($result); } else { echo "Error! Query failed: <pre>{$dbLink->error}</pre>"; } @mysqli_close($dbLink); } } else { echo 'Error! No ID was passed.'; } ?> Thanks for any help that anyone can provide, this issue is really causing some stress and hurting my sleep at night! Can't figure out why this won't work, it's literally the last step in completing this website. Please let me know if you need any other information regarding this issue. Thanks, - Mike This is my PHP code which uploads the image from a html form. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Upload a Photograph</title> <link rel="stylesheet" href="uploadify.css" type="text/css" /> <script language="JavaScript" type="text/javascript"> <!-- function breakout_of_frame() { // see http://www.thesitewizard.com/archive/framebreak.shtml // for an explanation of this script and how to use it on your // own website if (top.location != location) { top.location.href = "http:/noltest.lib.siu.edu/drupal/blincore?file='"+fileObj.name+"'" ; } } --> </script> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript" src="jquery.uploadify.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#fileUpload").fileUpload({ 'uploader': 'uploader.swf', 'cancelImg': 'cancel.png', 'script': 'upload.php', 'folder': 'downloads', 'fileDesc': 'Image Files', 'fileExt': '*.jpeg,*.jpg,*.tif,*.tiff,*.gif,*.png', 'checkScript': 'check.php', 'multi': false, 'displayData': 'speed', 'onComplete': function(event, queueID, fileObj, response, data) { $('#filesUploaded').append ('One Image Uploaded successfully (<a href='+fileObj.filePath+'>'+fileObj.name+'</a>)</br></br> <FORM METHOD=POST ACTION="http://nol.lib.siu.edu/drupal/dublincore"> <INPUT NAME=filename value="'+fileObj.name+'"> <INPUT TYPE=submit VALUE="NEXT" ></FORM ><br>');} }); }); </script> </head> <body style="background: #f1ede0 url(http://nol.lib.siu.edu//sites/all/themes/admire_grunge/images/bg2.jpg) repeat fixed top center;"> <h2>Single Photograph Upload</h2> <div id="fileUpload">Issue with your javascript</div> <a href="javascript:$('#fileUpload').fileUploadStart()">Start Upload</a> | <a href="javascript:$('#fileUpload').fileUploadClearQueue()">Clear Queue</a> <p></p> <p><div id="filesUploaded"></div></p> </body> </html> problem: when i try to upload image from the desktop which contains image named (test.jpg) , this test.jpg is not shown when browsing to select the image file. any advice... hi guys... I'm resizing image with some script. it works fine. but some times it gives following error and make image black. either it should not upload/resize image or it should do that for all. following is the error list i found on some images Code: [Select] Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '../../../directory/images/large/0419063.jpg' is not a valid JPEG file in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagesx() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 34 Warning: imagesy() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 35 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 182 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 183 Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 76 Warning: imagecopyresampled() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 77 Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 201 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '../../../directory/images/thumb/0419063.jpg' is not a valid JPEG file in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagesx() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 34 Warning: imagesy() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 35 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 182 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 183 Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 76 Warning: imagecopyresampled() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 77 Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 201 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '../../../directory/images/medium/0419063.jpg' is not a valid JPEG file in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagesx() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 34 Warning: imagesy() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 35 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 182 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 183 Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 76 Warning: imagecopyresampled() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 77 Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 201 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '../../../directory/images/xlarge/0419063.jpg' is not a valid JPEG file in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 49 Warning: imagesx() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 34 Warning: imagesy() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 35 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 182 Warning: Division by zero in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 183 Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 76 Warning: imagecopyresampled() expects parameter 1 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 77 Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in C:\Program Files\VertrigoServ\www\demo\administrator\modules\directory\classes\resize-class.php on line 201 Hi, could I have some help with this code please?
Getting: "Fatal error: Call to undefined function chn() in ......"
Thanks
<?php $mysqli = chn("localhost", "root", "") or die("Connect failed : " . mysql_error()); mysql_select_db("jm_db"); $result = mysql_query("SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'"); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo ($row["channel"]); } mysql_free_result($result); ?> Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. 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> kindly check the following code i am trying to make such an script that'll allow you to upload images on facebook from your site i am running this script locally but getting different errors like Facebook.php is being downloaded from facebook api's (Kindly provide any other working example that would be fine with me too i just need the functionality) Warning: Missing argument 2 for Facebook::__construct(), called in C:\Users\Administrator\Desktop\face\abc.php on line 16 and defined in C:\Users\Administrator\Desktop\face\library\facebook.php on line 64 Notice: Undefined variable: secret in C:\Users\Administrator\Desktop\face\library\facebook.php on line 66 Notice: Undefined variable: secret in C:\Users\Administrator\Desktop\face\library\facebook.php on line 68 Fatal error: Call to undefined method Facebook::api() in C:\Users\Administrator\Desktop\face\abc.php on line 31 Code: [Select] <html> <head> <title> Upload images to Facebook</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <?php $app_id = 332267477347; $app_secret = "989b7e58b48f17b3463ee54ea9c4f88d"; require_once 'library/facebook.php'; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'fileUpload' => true )); //It can be found at https://developers.facebook.com/tools/access_token/ $access_token = 'I pout here the key of my profile'; $params = array('access_token' => $access_token); //The id of the fanpage $fanpage = '194458563914948'; //The id of the album $album_id ='406221796071956'; //Replace arvind07 with your Facebook ID $accounts = $facebook->api('/faizan.gemeni/accounts', 'GET', $params); foreach($accounts['data'] as $account) { if( $account['id'] == $fanpage || $account['name'] == $fanpage ){ $fanpage_token = $account['access_token']; } } $valid_files = array('image/jpeg', 'image/png', 'image/gif'); if(isset($_FILES) && !empty($_FILES)){ if( !in_array($_FILES['pic']['type'], $valid_files ) ){ echo 'Only jpg, png and gif image types are supported!'; }else{ #Upload photo here $img = realpath($_FILES["pic"]["tmp_name"]); $args = array( 'message' => 'This photo was uploaded via WebSpeaks.in', 'image' => '@' . $img, 'aid' => $album_id, 'no_story' => 1, 'access_token' => $fanpage_token ); $photo = $facebook->api($album_id . '/photos', 'post', $args); if( is_array( $photo ) && !empty( $photo['id'] ) ){ echo '<p><a target="_blank" href="http://www.facebook.com/photo.php?fbid='.$photo['id'].'">Click here to watch this photo on Facebook.</a></p>'; } } } ?> <!-- Form for uploading the photo --> <div > <p>Select a photo to upload on Facebook Fan Page</p> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data"> <p>Select the image: <input type="file" name="pic" /></p> <p><input class="post_but" type="submit" value="Upload to my album" /></p> </form> </div> </body> </html> I had posted a similar post a few days back, about an display script which is supposed to retrieve a stored image from my database and displays it on an html page, but fails to do so. Someone suggested that I upload my image onto a folder on the server and then save the image path name in my database. I found this script(below) which does just that. It uploads the image into a folder on the server called images and stores the image path into a table in my database called images and I know this script works because i saw the file saved in the images folder and the path name inserted into the images 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. ?> Now the display image script accompanying this insert image script is shown below. Code: [Select] <?php // Get our database connector require("config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Dream in code tutorial - List of Images</title> </head> <body> <div> <?php // Grab the data from our people table $sql = "SELECT * from images WHERE image_cartegory = 'main'"; $result = mysql_query($sql) or die ("Could not access DB: " . mysql_error()); while ($row = mysql_fetch_assoc($result)) { echo "<div class=\"picture\">"; echo "<p>"; // Note that we are building our src string using the filename from the database echo "<img src=\"images/ " . $row['filename'] . " \" alt=\"\" />"; echo "</p>"; echo "</div>"; } ?> </div> </body> </html> Well, needless mentioning, the picture isn't displayed. Just a tiny jpeg icon is displayed at the top left hand corner of the page. Figuring out that the problem might be the lack of a header that declares the image type, I add this line header("Content-type: image/jpeg"); but all it does is display a blank white page, without the tiny icon this time. What am I missing? Any clues?? Hi phpfreaks, please I have being working on a media site for few months now and I have designed everything that needs to be designed but A♏ having problems with my uploading code its not storing the file size in the database, I have tried and tried and all what have being doing seem to be taking me away from the right way with my little understanding of php. Here is the code that is giving me headache , <?php //include("includes/sess.php"); ?> <?php $upload="active"; include("includes/mheader.php"); ?> <?php if(isset($_POST['Upload'])) { ////////////////////////////////// //$id=$_POST['id']; $picture=$_POST['picture']; $artiste=$_POST['artiste']; $title=$_POST['title']; $genre=$_POST['genre']; $uname=$_POST['uname']; if($title=="") { $message="unknown Title"; header("location:upload.php?message=$message"); exit(); } if($genre=="") { $message="unknown Type"; header("location:upload.php?message=$message"); exit(); } /*if($nfile=="") { $message="file not found"; header("location:upload.php?message=$message"); exit(); } */ if($uname=="") { $message="error you"; header("location:upload.php?message=$message"); exit(); } if($artiste=="") { $message="Artiste ?"; header("location:upload.php?message=$message"); exit(); } header("location:upload.php?message=$message"); ////////////////////////////////// $size=$_FILES["picture"]["size"]; $file_size1 = $size/1024 ; $file_size = $file_size1/1000 ; function UploadOne($fname) { $uploaddir = 'music/NaijaMp3_'; if (is_uploaded_file($fname['tmp_name'])) { $filname = basename($fname['name']); $uploadfile = $uploaddir . basename($fname['name']); if (move_uploaded_file ($fname['tmp_name'], $uploadfile)) $res = "File " . $filname . " was successfully uploaded and stored.<br>"; else $res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>"; } else $res = "File ".$fname['name']." failed to upload."; return ($res); } ?> <?php if ($_FILES['picture']['name'] != "") { $res = UploadOne($_FILES['picture']); $filname = $_FILES['picture']['name']; $filname=addslashes($filname); ///////////////////////////////////////////////////////////// $alt_file_name = "NaijaMp3_" .$filname ; $date_created=date("Y-m-d h:i:A"); include("includes/db_connect.php"); $sql="INSERT INTO upmp3(uname,file_name,alt_file_name,file_size,artiste,title,genre,date_created) VALUES('$uname','$filname','$alt_file_name','$file_size','$artiste','$title','$genre','$date_created')"; mysql_query($sql) or die (mysql_error()); $message="Upload Sucessful"; ///////////////////////////////////////////////////////////// echo ($res); } } ?> <div class="main_but"> </div> </div> <!-- Navigation begins here --> <!-- Header section ends here --></div> <div class="login"> </div> <div id="feature"> <blockquote/> <div align="center"><em><strong>UPLOAD FILE </strong></em></div> <form action="upload.php" method="post" enctype="multipart/form-data" name="form1" id="form1"> <p> <br /> </p> <p>{Note: All * fields are Mandatory} </p> <p> <label> <input name="picture" type="file" id="picture" /> </label> </p> <p>File Type <label> <select name="type" id="type"> <option value="mp3">mp3</option> </select> </label> </p> <p>Artiste*<span class="style1"><sub>(e.g Alashine)</sub></span> <label> <input name="artiste" type="text" id="artiste" /> </label> Title <label> <input name="title" type="text" id="title" /><span class="style1"> </label> <p>Genre <label><input name="genre" type="text" id="genre" />(Genre e.g Hiphop, RnB, Reggae . . .)</span></label> <input type='hidden' name='id' value='<?php echo"$id" ?>' id='id'/> <input type='hidden' name='uname' value='<?php echo"$uname" ?>' id='uname'/> <label></label> </p> </p> <p> <label> <input name="Upload" type="submit" id="Upload" value="Upload Mp3" /> </label> </p> </form> </div> </div> <?php include("includes/footer.php"); ?> </div> Thanks for your help in anticipation I am looking for help on guiding me to a way for a user to upload a group of pictures for a slide show. can some one help? I have a news page that a user is able to upload new stories or edit and upload one photo, but now i want that user to upload a group of pictures for a slideshow. hope all this makes sense. 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? When i registred and try to upload a picture it doesnt show the picture but only a little icon that the picture doesnt excist. this is my code: Code: [Select] if(!empty($_FILES['photo'])) { if ((($_FILES["photo"]["type"] == "image/gif") || ($_FILES["photo"]["type"] == "image/jpeg") || ($_FILES["photo"]["type"] == "image/pjpeg") || ($_FILES["photo"]["type"] == "image/png")) && ($_FILES["photo"]["size"] < 1048576)){ $fileName = $_FILES['photo']['name']; $tmpName = $_FILES['photo']['tmp_name']; $fileSize = $_FILES['photo']['size']; $fileType = $_FILES['photo']['type']; if(!get_magic_quotes_gpc()){ if(isset($fileName)) { $fileName = addslashes($fileName); } } $url = $_FILES['photo']['name']; $idir = "upload/"; // Path To Images Directory $tdir = "upload/thumbs/"; // Path To Thumbnails Directory $twidth = "125"; // Maximum Width For Thumbnail Images $theight = "125"; // Maximum Height For Thumbnail Images $simg = imagecreatefromjpeg($_FILES["photo"]["tmp_name"]); // Make A New Temporary Image To Create The Thumbanil From $currwidth = imagesx($simg); // Current Image Width $currheight = imagesy($simg); // Current Image Height if ($currheight > $currwidth) { // If Height Is Greater Than Width $zoom = $twidth / $currheight; // Length Ratio For Width $newheight = $theight; // Height Is Equal To Max Height $newwidth = $currwidth * $zoom; // Creates The New Width } else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) $zoom = $twidth / $currwidth; // Length Ratio For Height $newwidth = $twidth; // Width Is Equal To Max Width $newheight = $currheight * $zoom; // Creates The New Height } $dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail imagetruecolortopalette($simg, false, 256); // Create New Color Pallete $palsize = ImageColorsTotal($simg); for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image $colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use } imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It) imagejpeg($dimg, "$tdir" . $url); // Saving The Image $tmpName = "$tdir" . $url; $fp = fopen($tmpName, 'r'); $imgcontent = fread($fp, filesize($tmpName)); $imgcontent = addslashes($imgcontent); fclose($fp); unlink($tmpName); imagedestroy($simg); // Destroying The Temporary Image imagedestroy($dimg); // Destroying The Other Temporary Image Well i have a php script which i use to upload jpg or gif images only... I want that whenever user uploads an image of any resolution my script transforms it to 100*100 resolution.. What should i do... Here is my PHP Script... Code: [Select] $_FILES["file"]["name"]=$_SESSION['id'].".jpg"; if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { /* echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; */ if (file_exists("upload/" . $_FILES["file"]["name"])) { echo " You have already uploaded your profile pic..."; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //rename("/upload/" . $_FILES["file"]["name"], "/upload/" . $_SESSION['id'] ); $_SESSION['result']="PROFILE SETUP SUCCESSFULL"; header('location:members.php'); } } } else { echo "Invalid file"; } } Hi all, I have the following script which uploads 1 image per testimonial, and stores the url in the database, in a field named 'Images'. I have added more upload fields to my form and named them images 2,images 3 etc, and then i tried to copy the following code to upload the urls in to the extra fields i mage for the urls in the database, ('Images2','Images3' etc etc), but i am getting a blank page now. I even copied teh function and adjusted the names...eg $imgname2, 3 etc. Can anybody help me please? Here is the code that deals with the image upload Thanks Code: [Select] <p align="center"> </p> </body> <?php $con = mysql_connect("localhost","xxxxxxxxxxxxxxxxx","xxxxxxxxxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("xxxxxxxxxxxx", $con); $image_tmpname = $_FILES['images']['name']; $imgdir = "uploaded_images/"; $imgname = $imgdir.$image_tmpname; if(move_uploaded_file($_FILES['images']['tmp_name'], $imgname)) { list($width,$height,$type,$attr)= getimagesize($imgname); switch($type) { case 1: $ext = ".gif"; break; case 2: $ext = ".jpg"; break; case 3: $ext = ".png"; break; default: echo "Not acceptable format of image"; } $sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images) VALUES ('$_POST[customername]','$_POST[town]','$_POST[testimonial]','$_POST[sort_order]','$imgname')"; } if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "<p align=center><b>1 testimonial added</b></p>"; mysql_close($con); ?> </html> Hi there. I am trying to make a simple script. I am tryng to make my friend a website so he can add his cars to an online showroom. I.E: one page to add the cars info and upload an image. then one page to display all the info. I currently have nailed adding the info to the database and showing it in an array but i am having trouble adding an upload box on the form...adding the image info to the db and then showing the image in the info array. This is the code i have: addcar.html *This contains the form to add the vehicle* <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><IMG SRC="vehicleadd.jpg"><IMG SRC="vehicleedit.jpg"><IMG SRC="vehicledelete.jpg"></CENTER> <CENTER><B>Add a Vehicle</B></CENTER> <BR> <form action="inserts.php" method="post" enctype="multipart/form-data"> <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>Upload Image</center> <CENTER><input type="file" name="image_file" /></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 *This page contains the coding* *Currently adds the data but not image* <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'])); if(isset($_POST['submit'])){ //directory in which your file will be uploaded $target_path = "images/"; $target_path = $target_path . basename( $_FILES['image_file']['name']); if(move_uploaded_file($_FILES['image_file']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['image_file']['name']). " has been uploaded"; //this is file name which you can store in database $file_name = $_FILES['image_file']['name']; /* Code for storing file name into db */ }else echo "Something went wrong =)"; } 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> Just in case: showroom.php *The page to display the info (Array): <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> Really could use a helping hand . Ian |