PHP - Image Download Script Error
Hi Guys, I have an issue with the following script which is throwing this error Quote( ! ) Parse error: syntax error, unexpected end of file in C:\wamp64\www\script\images.php on line 41 I just can not see the error, can anyone help (not even sure the script is going to work) <?php /* settings */ //folder for images saving $saveDir = "c:\wamp64\www\script\images\"; //database connection // Turn off all error reporting error_reporting(0); $conn = mysqli_connect('localhost', 'root', '', 'tbl_temp_products'); //start and end table row to prevent timeout or hard server work $start = '1'; $end = '200'; /* end of settings */ //query for fetching the image urls $sql = 'SELECT image_url FROM tbl_temp_products ORDER BY id DESC LIMIT ' . $start . ',' . $end . ''; $res = $conn->query($sql); $count = 0; //this is for count the total row fetched $notify = ''; //this is for seeing result or errors while ($row = $res->fetch_assoc()) { $url = $row(['image_url']); $dest = $saveDir . clean($row(['image_url'])) . '.jpg'; if (!file_exists($dest)){ //prevent file overwriting if (copy($url, $dest)){ $notify.= 'image saved: '. $row(['image_url']); $count++; }else{ $notify.= 'ERROR saving image: '. $row(['image_url']); }else{ $notify.= 'image already exists: '. $row(['image_url']); } } //output result echo 'TOTAL IMAGE SAVED: ' .$count .'\n'; echo $notify; ?>
Similar TutorialsThe Script:
<?php if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; for ($i = 0; $i < count($_FILES['file']['name']); $i++) { $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); } // To create the thumbnails. function make_thumb($src, $dest, $desired_width) { /* read the source image */ $source_image = imagecreatefromjpeg($src); $width = imagesx($source_image); $height = imagesy($source_image); /* find the "desired height" of this thumbnail, relative to the desired width */ $desired_height = floor($height * ($desired_width / $width)); /* create a new, "virtual" image */ $virtual_image = imagecreatetruecolor($desired_width, $desired_height); /* copy source image at a resized size */ imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); /* create the physical thumbnail image to its destination */ imagejpeg($virtual_image, $dest); } $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/"; $desired_width = 100; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } } ?>With this: $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/";I get this error message: Warning: imagejpeg(C:/xampp/htdocs/gallerysite/multiple_image_upload/thumbs/): failed to open stream: No such file or directory in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 49With this: $dest = "http://localhost/gallerysite/multiple_image_upload/thumbs/";I get this error message: Warning: imagejpeg(http://localhost/gallerysite/multiple_image_upload/thumbs/): failed to open stream: HTTP wrapper does not support writeable connections in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 49When I try deleting the "thumbs" folder and then try to upload an image, then I get this error message: Warning: imagejpeg(C:/xampp/htdocs/gallerysite/multiple_image_upload/thumbs/): failed to open stream: Invalid argument in C:\xampp\htdocs\gallerysite\multiple_image_upload\upload.php on line 49The spot of line 49 is this, at the spot where the script creates the thumbnails: /* create the physical thumbnail image to its destination */ imagejpeg($virtual_image, $dest); }Also, with this part right here I am not getting an error message, which means that this part works fine in comparison: $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded imagesThe script itself works fine. The script also uses javascript for multiple image upload. I am using XAMPP. The folder "thumbs" is set to "read-only", when I try to uncheck the "read-only" option in the properties in Windows then it sets itself back again to "read-only". Then again, the script works fine when it comes to the "uploads" folder. This is mentioned in comparison to the "thumbs" folder. Any suggestions on how to solve this? EDIT: I am using XAMPP. The folder "thumbs" is set to "read-only", when I try to uncheck the "read-only" option in the properties in Windows then it sets itself back again to "read-only". I am wondering if I would have issue that the option sets itself back again with Linux? Edited by glassfish, 11 October 2014 - 05:35 PM. Hi, I don't want to reveal the real download link to my users for some reason, so I place the file here, for example: http://www.domain.com/download/secure-file.exe Now I want to write a simple php code and link to this address, for example: http://www.domain.com/download/download.php Now this php script read that file and send it to user, without revealing the real file location to user. Of course there is no resume download now, but I don't care. Anyone knows a code snippet for that, or can help me to the right position? I am a newbie in PHP. Thank you. To give some background, I'm currently working on a private site that allows members access to large document files via a torrent system. Now, this is the PHP code I have: Code: [Select] $id = $_REQUEST['id']; if (!$id) httperr(); $res = mysql_query("SELECT name FROM torrents WHERE id = $id") or sqlerr(__FILE__, __LINE__); $row = mysql_fetch_assoc($res); $fn = "$torrent_dir/$id.torrent"; if (!$row || !is_file($fn) || !is_readable($fn)) httperr(); $fs = filesize($fn); $tor_fname = $row["filename"]; mysql_query("UPDATE torrents SET hits = hits + 1 WHERE id = $id"); require_once "include/benc.php"; // Torrent Encoding Functions $dict = bdec_file($fn, (1024*1024)); $dict['value']['announce']['value'] = "$DEFAULTBASEURL/announce.php?passkey=$CURUSER[passkey]"; $dict['value']['announce']['string'] = strlen($dict['value']['announce']['value']).":".$dict['value']['announce']['value']; $dict['value']['announce']['strlen'] = strlen($dict['value']['announce']['string']); header("Content-Type: application/x-bittorrent"); header("Content-Disposition: attachment; filename=\"" . basename($tor_fname) . "\"" ); print(benc($dict)); This is taken from (and is the majority of) the file download.php. This is called like: download.php?id=?? The above should work, but when I use it, it tries to save the file as download.torrent, even though the $tor_fname variable doesn't contain that value. I'd obviously like to force the filename to be '<filename>.torrent' rather than the same name as the php script with .torrent on the end. Any ideas? Am I doing something stupid, or is there some way of doing this? I used the following script to limit number of downloads but the downloaded zip files become corrupt. I altered the code several times but no positive result. This is the code can anyone debug this script $path ="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //addslashes($_SERVER['REQUEST_URI']); $ip = addslashes($_SERVER['REMOTE_ADDR']); $dl = false; $sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time FROM downloaded WHERE filepath = '%s' AND ipadres = '%s' ORDER BY last_access DESC", $path, $ip); $res = mysql_query($sql); if (mysql_num_rows($res) > 0) { $last_xs = mysql_result($res, 0, 'last_time')+3600; if ($last_xs < time()) { mysql_query(sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip)); $dl = true; } } else { $sql = sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip); mysql_query($sql); $dl = true; } echo"<br> here is : ".$path."<br>"; if ($dl) { $fullPath = $_SERVER['DOCUMENT_ROOT'].$path; if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); //$chunksize = 1*(1024*1024); if ($fd = fopen ($path, "r")) { $fname = basename($path); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: Binary"); header("Content-Length: ".filesize($path)); header("Content-Disposition: attachment; filename=\"".basename($fname)."\""); header("Content-Description: File Transfer"); //header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); //header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: private"); header("Accept-Ranges: bytes"); header('Vary: User-Agent'); while(!feof($fd)) { //$buffer = fread($fd,500*1024); $buffer = fread($fd,filesize($path)); //$buffer = readfile($fd); //$buffer = fread($fd, $chunksize); //$buffer = fread($fd, (1*(1024*1024))); //$buffer = file_get_contents($fd); echo $buffer; //ob_flush(); ob_end_flush(); } fclose ($fd); exit; } } else { header('HTTP/1.0 503 Service Unavailable'); die('Abort, You reached your download limit for this file.'); } ?> I tried several options as shown with // Inputs by you all will be extremely helpful. Hi, this is my first post:) pretty sure i will be posting here in the future. Anyway i am having trouble with a php script which downloads a file from a mysql database. This php script works for text files and should work for most files from what i understand. When downloading a text file, the whole file is downloaded from the server. When downloading an mp3 file, only 16kb are downloaded and the file does not play. When looking at the data in the database, it displays that the full file is there (correct amount of bytes, so there is nothing wrong with my upload php script). Does anyone have any suggestions as to what I can change to make this work? Code: [Select] <?php if(isset($_GET['id'])) { // if id is set then get the file with the id from database $link=mysql_connect('localhost', 'root', ''); @mysql_select_db('filemgr') or die ("<p>Could not connect to mysql!</p>"); $id = $_GET['id']; $query = "SELECT name, type, size, content " . "FROM upload WHERE id = '$id'"; $result = mysql_query($query) or die('Error, query failed'); list($name, $type, $size, $content) = mysql_fetch_array($result); header("Content-length: $size"); header("Content-type:$type"); header("Content-Disposition: attachment; filename=$name"); echo $content; mysql_close($link); exit; } ?> Ok, I have a download script. The script is called like: http://www.site.net/index.php?action=downloadfile&filename=file001.zip&directory=directory12& The download file code is below. My site hosts quite a few files that get linked on other websites. Problem is, when that link is clicked, obviously it just starts the file download, as if it were a direct link to the file. What I need to do, is still have it download the file when the link is clicked, but I would also like it to redirect the browser to my homepage as well. I tried placing this after the download headers but it didn't work. header("Location: http://www.site.net"); Can anyone give me an idea how I can get the code to do that? Keep in mind that I'm not fluent in PHP. case 'downloadfile'; $filename = getGetVar('filename'); $directory = getGetDir('directory'); $current_dir = $uploads_folder_name; if ($directory != '') { $current_dir.="/$directory"; } $filename = basename($filename); if (!$grants[$user_status][DOWNLOAD]) { place_header($mess[111]); show_Contents(); break; } if (!file_exists("$current_dir/$filename")) { place_header($mess[125]); show_Contents(); break; } if (!is_path_safe($directory, $filename)) { place_header($mess[111]); show_Contents(); break; } list($upl_user, $upl_ip, $filestatus, $contents) = get_file_description("$current_dir/$filename", $comment_max_caracters); if ($validation_enabled && $filestatus == UNVALIDATED && !$grants[$user_status][VALIDATE]) { place_header($mess[111]); show_Contents(); break; } $size = filesize("$current_dir/$filename"); $daily_size = get_daydownload(); if (($max_daily_download_mb > 0) && (($size + $daily_size) > ($max_daily_download_mb * 1024 * 1024))) { place_header($mess[212]); show_Contents(); break; } $monthly_size = get_monthdownload(); if (($max_monthly_download_mb > 0) && (($size+$monthly_size) > ($max_monthly_download_mb * 1024 * 1024))) { place_header($mess[213]); show_Contents(); break; } increasefiledownloadcount("$current_dir/$filename"); increasebytecountdl("$destination/$userfile_name"); if (($user_status != ANONYMOUS) && ($logged_user_name != '')) // Update user statistics { list($files_uploaded, $files_downloaded, $files_emailed) = load_userstat($logged_user_name); $files_downloaded++; save_userstat($logged_user_name, $files_uploaded, $files_downloaded, $files_emailed, time()); } header("Content-Type: application/force-download; name=\"$filename\""); header("Content-Transfer-Encoding: binary"); header("Content-Length: $size"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Expires: 0"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); // Decrypt file if encryption enabled if ($encrypt_filecontent) { decrypt_file("$current_dir/$filename", true); } else { readfile_chunked("$current_dir/$filename"); } exit; break; Hello, I made that script for previewing all the images in the directory: Code: [Select] $dir = "../images"; $images = glob($dir . "*.jpg"); foreach($images as $image) { echo $image; } Now what i would like to do is to put checkbox to every image. And when i press download button, all the selected images are downloaded. (as .zip, .rar) Thank you very much for your help How do I make it so when a user clicks download, it will download the image from the path to their computer? I have a PHP script that locates a photo in a MySQL database and based on the path /filename stored in the database, retrieves the file and downloads it via the browser, the problem is that it saves as a filename that is the url with no extension. so we pass : dlfile.php?id-10 the script is supposed to get the filename from the stored file and download it with that filename but it downloads the file as 'dlfile?id=10' instead of PIC76534.jpg. where am i going wrong? code below for dlfile.php. or is there a way to ask the user to select a filename when downloading? I know the script is crude but have had it for ages. <?php require( '../js/db.php' ); $id = $_GET[ 'id' ]; $sql = "SELECT * FROM image_archive WHERE id = " . $id; $result = mysqli_query( $conn, $sql ); if ( !$result ) { echo "ERROR: " . mysqli_error( $conn ); } else { $row=mysqli_fetch_assoc($result); //path to the picture you're wanting the viewer to download $path = "/archimages/".basename($row['pic_OriginalPath']); if ( file_exists( $path ) ) { //split the extension and name from eachother $e = explode( '.', $path ); //get the name of the file $file_name = $e[ 0 ]; //image extension $extension = $e[ 1 ]; // Send a header saying we'll be displaying a picture header( 'Content-type: '.$row['pic_Type'] ); // Name the file header( 'Content-Disposition: attachment; filename="' . $file_name . $extension . '"' ); // Path to the picture you're wanting the user/viewer to download readfile( $file_name . '.' . $extension ); } else { echo 'The requested image does not exist.'.$path.'<hr>'; } } ?>
I'm trying to create a series of images on a page but the code won't run. (left table code out): <body> <?PHP /// fyi, the image_link field contains, e.g., artistfoldername/imagefilename.jpg $path = "artWorkImages/"; $art_id ='2'; $QUERY="SELECT art_title, about_art, image_link FROM artWork WHERE art_id = '$art_id'"; $res = mysql_query($QUERY); $num = mysql_num_rows($res); if($num>0){ while($row = mysql_fetch_array($res)){ $artist_name = $row["art_title"]; $about_art = $row["about_art"]; $image_link = $row["image_link"]; print "<img src=$path.$image_link/>"; } } ?> </body> Thanks Allen Well the subject line is pretty explicit. I found this script that uploads a picture onto a folder on the server called images, then inserts the the path of the image on the images folder onto a VACHAR field in a database table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> The script seems to work fine because I managed to upload a picture which was successfully inserted into my images folder and into the database. Now the problem is, I can't figure out exactly how to write the script that displays the image on an html page. I used the following script which didn't work. Code: [Select] //authenticate user //Start session session_start(); //Connect to database require ('config.php'); $sql = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($sql); $imagebytes = $row['image']; header("Content-type: image/jpeg"); print $imagebytes; Seems to me like I need to alter some variables to match the variables used in the insert script, just can't figure out which. Can anyone help?? what am i doing wrong? Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /****/*****/*/domains/klikertje.nl/public_html/adminpaneel/index.php on line 123 script of adminpaneel/index.php <?php include("../config.php"); include('../cronjobs.php'); $gebruikersnaam = "robin"; //De gewenste gebruikernaam $wachtwoord = "rg953gejFDI3c"; //Het gewenste wachtwoord if(preg_match('/^[a-zA-Z ]+$/D', $_SERVER['PHP_AUTH_USER']) == 0){ if(preg_match('/^[a-zA-Z ]+$/D', $_SERVER['PHP_AUTH_PW']) == 0){ if($_SERVER['PHP_AUTH_USER'] != $gebruikersnaam || $_SERVER['PHP_AUTH_PW'] != $wachtwoord) { header("WWW-Authenticate: Basic realm=\"Beveiliging\""); header("HTTP/1.0 401 Unauthorized"); echo "Je bent niet ingelogd! Probeer het <A HREF=\"javascript:location.reload();\">opnieuw</A>."; exit; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>MiljoenenMail</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta name="keywords" content="miljoenenmail" /> <meta name="description" content="MiljoenenMail" /> <meta http-equiv="content-language" content="nl" /> <link href="../css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="containermain"> <div id="headercontainer"> <div id="headerleft"> <div id="logo"><img src="../images/miljoenenmaillogo.png"></div> <div id="menu"> <ul> <li class="first"><a href="index.php">Algemeen</a></li> <li><a href="afmelden.php">Uitloggen</a></li> <li><a href="profile.php">profiel</a></li> <li><a href="payout.php">Uitbetaling</a></li> </ul> </div> </div> <div id="headerright"> <center><i>Welkom Beheerder</i></center> <table border="0" width="235px" style="margin-top: 5px;" height="85px"> <tr><td><img src="images/parel.png" alt="Parel" /></td><td style="text-align:left;">Parels: <?=$gebruiker->parels?></td><td><img src="images/eurosymbol.png" alt="Euro" /></td><td style="text-align:left;"><?=$gebruiker->saldo?></td></tr> <tr><td><img src="images/klikmissie.png" alt="Kliknissie" /></td><td style="text-align:left;">Klikmissie</td><td><img src="images/wallet.png" alt="Uitbetalen"/></td><td style="text-align:left;">Uitbetalen</td></tr> <tr><td><img src="images/message.png" alt="Berichten" /></td><td style="text-align:left;">Berichten: <b><?=$gebruiker->berichten?></b></td><td><img src="images/nl_flag.png" alt="" /></td><td style="text-align:left;">Nederland</td></tr> 2 </table> </div> </div> <div id="floatheader"></div> <div id="tab_understroke"></div> <div id="container"> <div id="rechtscontainer"> <div id="topblue"></div> <div id="main"> <p><strong><h2>AdminPaneel</h2></strong></p> <hr /> <form name="form1" method="post" action=""> <table border="0"> <tr> <td>de nieuws/voorpagina wijzigen:</td> <?php if(!isset($_POST['Submit'])) { ?> <td><input name="nieuws" type="text" size="20" <?php if(isset($nieuws->inhoud)) { ?>value="<?=$nieuws->inhoud?>"<?php } ?>></td> </tr> <tr> <td colspan="2"> <input type="submit" name="Submit" value="Opslaan"> </td> </tr> </table> </form> <?php } else { if(isset($_POST['nieuws']) OR $_POST['nieuws'] !== $nieuws->inhoud ) { mysql_query("UPDATE cmssysteem SET inhoud='".$_POST['nieuws']."'"); } echo "bedankt voor je wijzigingen ze zijn succesvol opgeslagen en veel plezier verder met de site admin ;)"; } ?> </div> <div id="right"> <div class="title">Statistieken</div> <div class="right_content"> Aantal leden: <?=$leden?><br /> Leden online: <?=$leden?><br /> Totaal aantal parels: <?=$totaalparels?><br /> € 532,00 uitgekeerd! </div> </div> </div> <div id="float"></div> <div id="footer"></div> </div> </div> <center><table border="0" width="861px"> <tr><td align="left"><pre>© 2010 Miljoenenmail.nl</pre></td><td align="right"><pre>made by: Ismail Metaich</pre></td></tr> </table></center> </body> </html> <? } else { echo "<html><body>$_SERVER['PHP_AUTH_PW'] bevat cijfers of speciale tekens alleen letters mogelijk!</html></body>" } } else { echo "$_SERVER['PHP_AUTH_USER'] bevat cijfers of speciale tekens alleen letters mogelijk!"; } ?>
Basically I would like to place a link on my website and have the user download a file, but rather than just right clicking and choosing save target as, the link must be clicked, on the next page the file is fetched and then the client can download the file. How would I go about setting this up please? I have made a Php program that downloads an Inno setup installation file for installing a program. However, if I for one or another reason want to make a new download of the same Inno setup installation file, the previous file will still be found in the Download folder. Each of the downloads get a number in parenthesis, setup(1), setup(2), setup(3) etc. However, I wondered if it is posible to erase the previous file in the same process as I download a new one, so that however many downloads I do, there will all the time only be one occurence of this file in the Download folder. The download code is as follows: $exe = "Inno script/Test_setup.exe"; header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"Test_setup.exe\""); header("Content-Length: " . filesize($exe)); readfile($exe); Thanks in advance. Sincerely
Ok so I have one page with a set of links created with table data: Code: [Select] <a href="Aplayer.php?player='.$row['ID'].'">'.$row['fname'].' '.$row['lname'].'</a> That link displays fine as the first name and last name in the table as it should and also when clicked goes on to Aplayer.php?player=1/2/3etc as it should. However when it comes to loading the Aplayer.php with the appropriate ID action applied I get the following error: Quote Parse error: syntax error, unexpected $end in /home/a2552500/public_html/Aplayer.php on line 126 The codes for the Aplayer.php page is below, now I thought "unexpected $end" usually meant a '}' was missing, or incorrectly inserted in the code. I must however be wrong due to the fact Ive checked for extra/missing '}'s and all seems ok. Can someone skim through the following and point to me whats wrong, and a little explination would be nice where possible to ensure I dont make the same mistake in future. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> <title>Yorkshire Leopards Cricket Club</title> </head> <body> <div id="wrapper"> <? include('includes/sidebar.php'); ?> <? include('includes/header.php'); ?> <? include('includes/nav.php'); ?> <div id="content"> <h2>Yorkshire Trust A<br> <br></h2> <? session_start(); include "includes/dbconnect.php"; //retrieve the main article if(isset($_GET['ID'])){ $_SESSION['ID']=$_GET['ID']; $getarticle="SELECT * FROM A_squad WHERE ID = ".$_GET['ID']." "; if(!$result = mysql_query($getarticle)){ echo mysql_error(); }else{ $num=mysql_num_rows($result); } ?> <table width="100%" border="0"> <? if(isset($num) && ($num > 0)){ while($row_article=mysql_fetch_assoc($result)){ ?> <tr> <th align="left" width="18%" scope="row">Name:</th> <td width="24%"><? $_SESSION['fname']=$row_A_squad['fname']; echo $_SESSION['fname'];?> <? $row_A_squad['lname'];?></td> <td width="58%" rowspan="6"><? $row_A_squad['img'];?></td> </tr> <tr> <th align="left" scope="row">Born:</th> <td><? $row_A_squad['born'];?></td> </tr> <tr> <th align="left" scope="row">Nicknames:</th> <td><? $row_A_squad['nickname'];?></td> </tr> <tr> <th align="left" scope="row">Batting Style:</th> <td><? $row_A_squad['bat_style'];?></td> </tr> <tr> <th align="left" scope="row">Bowling Style:</th> <td><? $row_A_squad['bowl_style'];?></td> </tr> <tr> <th align="left" scope="row">Bio:</th> <td> </td> </tr> <tr> <th align="left" scope="row"></th> <td height="200" colspan="2"><? $row_A_squad['bio'];?></td> </tr> </table> </div> <? include('includes/footer.php'); ?> </div> </body> </html> Thanks a bunch as always guys Tom I'm running a script to get a date range and active people then what to select information on them but my code won't finish before I get the Error : Fatal error: Maximum execution time of 60 seconds exceeded in Get date Range Code: [Select] $query_rs_rpc_periods = "SELECT CAST(start_date as Date) AS start_date, CAST(end_date as Date) AS end_date, rc_period_id, `description` FROM report_cards_txt ORDER BY start_date DESC"; $rs_rpc_periods = mysql_query($query_rs_rpc_periods, $my_data) or die(mysql_error());$row_rs_rpc_periods = mysql_fetch_assoc($rs_rpc_periods);$totalRows_rs_rpc_periods = mysql_num_rows($rs_rpc_periods); Get Student Code: [Select] $query_rs_getStudent = "SELECT users.id,users.is_active, users.user_type, student.studentid, student.studentlevel FROM users, student WHERE users.user_type ='Student' AND users.is_active = 'True' AND student.studentid =users.id"; $rs_getStudent = mysql_query($query_rs_getStudent, $my_data) or die(mysql_error());$row_rs_getStudent = mysql_fetch_assoc($rs_getStudent);$totalRows_rs_getStudent = mysql_num_rows($rs_getStudent); //This is inside a "do loop" in my php code and this is causing the Fatal error Fatal error: Maximum execution time of 60 seconds exceeded in Code: [Select] <?php mysql_select_db($database_my_data, $my_data); $query_rs_factor = "SELECT DISTINCT CAST(student_daily.record_date as Date) AS academic_date, student_daily.student_id, CAST(schedule_room.scheduledate as Date) AS schedule_date, report_cards.rc_period_id, report_cards.start_date, report_cards.end_date, schedules.id, schedule_room.scheduleid FROM schedule_room, student_daily, report_cards, schedules WHERE student_daily.student_id = $studentid AND report_cards.rc_period_id = $reportCard AND student_daily.record_date >= report_cards.start_date AND student_daily.record_date <= report_cards.end_date AND CAST(student_daily.record_date as Date) = CAST(schedule_room.scheduledate as Date) AND schedules.id =schedule_room.scheduleid"; $rs_factor = mysql_query($query_rs_factor, $my_data) or die(mysql_error());$row_rs_factor = mysql_fetch_assoc($rs_factor);$totalRows_rs_factor = mysql_num_rows($rs_factor); The above code works but it takes too long and doesn't finish then the ERROR... I think that there should be a way to perform what I'm trying to do another way (without putting another query in my php code) but I can't figure it out... any help would be great! I need help with this old script I found. Parse Error on line 101. And Line 101 is ?> <?php $file = "music.xml"; $to_print = array("Name", "Artist", "Album", "Track ID", "Year", "Play Count", "Track Number", "Track Count", "Genre", "Rating", "Date Added"); $db_host = "localhost"; $db_name = "music_library"; $db_table = "table"; $db_username = "root"; $db_password = ""; function db_connect() { global $db_host, $db_name, $db_table, $db_username, $db_password; mysql_connect($db_host, $db_username, $db_password) or die("<p style='font-color:red'>Cannot connect to mySQL server</p>"); mysql_select_db($db_name) or die("<p style='font-color:red'>Cannot connect to mySQL database</p>"); } function alter_print_arr(&$input, $key) { $input = str_replace(' ', '_', strtolower($input)); } array_walk($to_print, 'alter_print_arr'); function array_to_table($array) { global $db_table, $to_print; db_connect(); mysql_query("DELETE FROM $db_table") or die("Could not remove old records."); mysql_query("OPTIMIZE TABLE $db_table"); foreach ($array as $elem_key => $element) { if (isset($element[track_id])) { $sql = ""; foreach ($element as $k => $v) { if (in_array($k, $to_print)) { $sql .= "$k='" . mysql_real_escape_string(str_replace('=amp=', '&', $v)) . "', "; } } $sql = rtrim(ltrim($sql, "track_id='$element[track_id]', "), ", "); $sql1 = "INSERT INTO $db_table (track_id) VALUES ('$element[track_id]');"; $sql2 = "UPDATE $db_table SET $sql WHERE track_id=$element[track_id];"; mysql_query($sql1) or die(mysql_error()); // echo"$sql1<br />$sql2<br /><br />"; // For debugging. Uncomment with caution! mysql_query($sql2) or die(mysql_error()); } } echo "Done! :)"; // print_r($array); // For debugging. Uncomment with caution! } $xml_parser = ""; //will hold each song in a 2-d array $songs = array(); //counter, number of 'dict' elements encountered $current_key=""; $number_dicts = 0; //key for each element in second dimension of array $current_element=""; //stores xml element name //value for second dimension array elements $current_data = ""; //boolean used to help let us know if we're done with the song list $end_of_songs = false; function start_element($parser, $name, $attribs) { global $current_element, $number_dicts; if ($name == "DICT") { $number_dicts++; } if ($number_dicts > 2) { $current_element = $name; } } function end_element($parser, $name) { global $songs, $current_element, $current_data, $number_dicts, $array_key, $end_of_songs; if ($end_of_songs) { return; } if ($current_element == "KEY") { $array_key = str_replace(' ', '_', strtolower($current_data)); } else { $songs[$number_dicts][$array_key] = $current_data; } } function character_data($parser, $data) { global $number_dicts, $current_data, $end_of_songs; if ($data == "Playlists") { $end_of_songs = true; } $current_data = trim($data); } $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1); xml_set_element_handler($xml_parser, "start_element", "end_element"); xml_set_character_data_handler($xml_parser, "character_data"); if (!($fp = @fopen($file, "r"))) { return false; } while ($data = fread($fp, 4096)) { // xml_parser jumps over ampersands. Decode any entities then replace any ampersands. // Reverse this when building SQL statement. if (!xml_parse($xml_parser, str_replace('&', '=amp=', html_entity_decode($data)), feof($fp))) { die(sprintf("XML error: %s at line %d ", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } xml_parser_free($xml_parser); array_to_table($songs); ?> Hello, I'm new here but mainly registered because of my PHP registration script I written isn't working... I'm new to PHP by the way. When I press submit on the form, it just goes back to the form again... Below is my script. <?php /* PHP Registeration Script, Allowing new Accounts to be Registered * Written By: freezicx * Year Written: 2011 * Last PHP Update: 2011 */ include("config.php"); $username = strip_tags($_POST['username']); $password = md5(strip_tags($_POST['password'])); $vpassword = md5(strip_tags($_POST['vpassword'])); $email = strip_tags($_POST['email']); $user_ip = $_SERVER['REMOTE_ADDR']; $reg_date = date("d-m-Y"); if(isset($_POST['register'])) { { if (!$username || !$password || !$email || !$vpassword) { echo "You must fill out all fields."; } else { } $dupe1 = mysql_num_rows(mysql_query("select * from users where user='$username'")); if ($dupe1 > 0) { echo "Sorry, that Username is already in use."; } else { } $dupe2 = mysql_num_rows(mysql_query("select * from users where email='$email'")); if ($dupe2 > 0) { echo "Sorry, that Email is in use."; } else { } if ($password != $vpassword) { echo "Your Passwords do not match."; } else { } mysql_query("insert into users (username, email, password, user_ip, reg_date) values('$username','$email','$password','$user_ip','$reg_date')")or die("Error adding account information into database."); echo 'You are registered successfully, you may now <a href="index2.php">login to your account</a>.'; }} ?> <html> <head> <title>LevelZ - Register an Account</title> </head> <body> <form action="register.php" method="post" name="register"> <table> <tr><td>Username:</td><td><input type="text" name="username"></td></tr> <tr><td>Email:</td><td><input type="text" name="email"></td></tr> <tr><td>Password:</td><td><input type="password" name="password"></td></tr> <tr><td>Verify Password:</td><td><input type="password" name="vpassword"></td></tr> <tr><td colspan=2 align=center><input type="submit" id="register" value="Join!"></td></tr> </table> </form> </body> </html> As I'm new to PHP, I can't see the error.... Thanks in advance any way! Hi everybody, my goal is to get the IP of someone accesing the site, writing the time and date along with his IP into the database. Of course, I would be adding the script to my frontpage when I make it work. But I get this error: Quote Parse error: syntax error, unexpected T_VARIABLE in D:\Program Files\xampp\xampp\htdocs\script1.php on line 8 I've checked line 8, I dont find anything in it that is out of place. Here is the code: <?php $ip = $_SERVER['REMOTE_ADDR']; $date = date("m.d.y"); $time = time(); mysql_connect ("localhost", "root", "********") or die ('Error: '. mysql_error()); mysql_select_db ("ip"); $query = "INSERT INTO ipdo (time, date, ip) VALUES ('"$time"', '"$date"', '"$ip"')"; mysql_query($query) or die ('Error updating database'); echo "Database updated with: " .$ip. "" ; ?> This is the first script I write entirely on my own, so be gentle Help? |