PHP - Multiple Redirects In One File?
Hi,
Is it possible to create a PHP file that 301 redirects specific pages if the file is included on those pages?
I am wanting to create a file similar to a htaccess file and then include that file on the pages I want to redirect.
For example
"if page is page1.shtml redirect to page2.shtml"
"if page is page5.shtml redirect to page10.shtml" etc
and on page1.shtml and page5.shtml, I will include the above PHP include file
Hope that makes sense
Thanks!
Similar TutorialsHi All, Am having a "can't see the wood for the trees" moment I have a php redirect file which contains my URLs, like so: return [ '/shop/' => '/products/', ]; I then have a functions file which contains: function 301_redirects(){ $redirects = include __DIR__ . '/redirects.php'; if (isset($redirects[$_SERVER['REQUEST_URI']])) { header("HTTP/1.1 301 Moved Permanently"); header('location: ' . $redirects[$_SERVER['REQUEST_URI']]); exit; } if (isset($redirects[rtrim($_SERVER['REQUEST_URI'], '/')])) { header("HTTP/1.1 301 Moved Permanently"); header('location: ' . $redirects[rtrim($_SERVER['REQUEST_URI'], '/')]); exit; } } If the URL is https://www.mydomain.com/shop then the redirect won't work If the URL is https://www.mydomain.com/shop/ then the redirect works What am I missing? Thanks Hello, all: been trying to convert this little single-file upload to multiple by naming each file form-field as "userfile[]" as it's supposed to automatically treat them as an array.. but no luck! Can you guide me as to what am I doing wrong?? appreciate the help! Code: [Select] <?php if (!isset($_REQUEST["seenform"])) { ?> <form enctype="multipart/form-data" action="#" method="post"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> <input type="submit" value="Upload"> <input type="hidden" name="seenform"> </form> <?php } else { // upload begins $userfiles = array($_FILES['userfile']); foreach ($userfiles as $userfile) { // foreach begins $uploaded_dir = "uploads/"; $userfile = $_FILES['userfile']["name"]; $path = $uploaded_dir . $userfile; if (move_uploaded_file($_FILES['userfile']["tmp_name"], $path)) { print "$userfile file moved"; // do something with the file here } else { print "Move failed"; } } // foreach ends } // upload ends ?> Hello! I have this validation script that seems to work great until I add the size validation. I'm ready to pull my hair out! Can someone tell me what I'm doing wrong? Code: [Select] if (isset($_POST['Submit'])) { $user_id = $userdata[user_id]; $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; $uploaded_files = array(); $max_filesize = 5242880; // Maximum filesize in BYTES (currently 5MB). $upload_directory = dirname(__file__) . '/'.$user_id.'/'; //set upload directory if (!is_dir($upload_directory)) { mkdir($upload_directory, 0777, true); } for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; if($_FILES['images']['size'] > $max_filesize){ echo "<b class='red'>Max file size is 5MB.</b><br/>"; $sz = true; } $ext = validate_extension($_FILES['images']['name'][$i]); if (($ext == true) && ($sz == true)){ $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } }else { echo "<b class='red'>File extention error. Only .doc, .pdf, .jpg and .gif files are allowed. </b><br/>"; } } } if ($number_of_uploaded_files >= 1){ echo "Number of files submitted:<b class='red>".$number_of_uploaded_files."</b><br/>"; echo "Number of successfully uploaded files:<b class='red>".$number_of_moved_files."</b><br/><br/>"; echo "Uploaded File Name(s):<br/>" . implode('<br/>', $uploaded_files); } } As of now it results in every uploaded file returning the error "Max file size is 5MB." Hi all I created a site a while ago now. Using PHP and MySQL. I set it up using a windows server NOT linux. I've come to start to do some SEO work on the site, but Google is finding two different urls. the www version and the non www version. As I'm on a windows server I cant create a htaccess file and add some script to re-direct. For some reason I dont have IIS installed. I believe you can create a re-direct in PHP. I have done this for the index.php file. It works fine when you go to the homepage but when you click on another link to a different part of the site in Google results, it then redirects me to the homepage. This is obviously messing up my rankings. The code i used for the re-driect was as follows: <?php if (substr($_SERVER['HTTP_HOST'],0,3) != 'www') { header('HTTP/1.1 301 Moved Permanently'); header('Location: http://www.'.$_SERVER['HTTP_HOST'] .$_SERVER['REQUEST_URI']); } ?> My site works with includes to the index.php file. I thought this would work but obviously not. Anyone any ideas. Adi I have the following 1. php page that stores sessions. press submit and... 2. ...goes to perl/cgi page to interface with an api only available in perl, then auto redirects via HTTP headers to... 3. ... a php page where depending on the result a field is added to database then emailed, etc... then... 4.... redirects to main page so really all the user sees is page 1 -> hits submit -> ends up on page 4 via redirects Is there a problem with using redirects? Could the user intervene and prevent these redirects? Thanks I am fairly new to PHP forms so I am trying to adapt an example that I found online. Right now it IS functioning... showing a error message OR showing a success message and sending all the form information to my email account. I would like to edit it to redirect to a specific page if it has an error (http://www.mosaleen.com/contact_error.html) and to another if it sends successfully (http://www.mosaleen.com/thankyou_email.html) I am a bit confused by how the script is looped at the end. However, if I delete out that last few lines of coding, the form stops working. I am attaching the code below. Keep in mind that I am a newbie! Code: [Select] <?php // Turn on error reporting. Handy for debugging. error_reporting(E_ALL ^ E_NOTICE); // The following parameters are pretty much all that you // need to change except for the format of the email message // below. Note that your mail server may require the mailTo // address be in the host domain. $mailTo = "****"; // The address that will receive form submissions $mailSubject = "Comments from Mosaleen"; // Whatever you want $mailHost = "****"; // Usually looks like mail.yourhost.com $mailPort = "25"; // Usually 25 $mailAuth = true; // "true" if your mail server requires authentication, "false" if not $mailPassword = "****"; // The mail password associated with $mailTo // If you want to get cookies values... // $myCookie = $_COOKIE["cookiename"]; // Get the form fields. $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // If there are errors, display them and a back button. if($errorMessages) { ?> <p>Errors were found on the form.</p> <ul> <?php echo $errorMessages; ?> </ul> <p><input type="button" value="Back" onClick="history.back()"></p> <?php } // No errors, send the message and print out success message. else { // These can sometimes be useful, although you should not // violate your site's privacy policy. $browser = $HTTP_USER_AGENT; $ip = $_SERVER['REMOTE_ADDR']; // Build the email.<br /> $body = " Name: $name Email: $email Phone: $phone Message: $message -------------------- Browser: $browser User IP: $ip"; include("Mail.php"); $headers["From"] = "contact@mosaleen.com"; $headers["To"] = $mailTo; $headers["Subject"] = $mailSubject; $params["host"] = $mailHost; $params["port"] = $mailPort; $params["auth"] = $mailAuth; $params["username"] = $mailTo; $params["password"] = $mailPassword; $mail_object =& Mail::factory("smtp", $params); $mail_object->send($mailTo, $headers, $body); ?> <h1>Thank You</h1> <p>Thank you for contacting us. We will be in touch with you shortly.</p> <?php } ?> I am trying to use curl to login to a website and get the login cookie. After I try to post, however, I get a 302. Does anyone know how to log into a page like this? Maybe there's a tutorial or something. This what firefox sends: http://oron.com/ POST / HTTP/1.1 Host: oron.com User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.15) Gecko/20110303 Ubuntu/10.04 (lucid) Firefox/3.6.15 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Referer: http://oron.com/login.html Cookie: login=username; xfss=; per_page_files=50 Content-Type: application/x-www-form-urlencoded Content-Length: 56 login=username&password=password&op=login&redirect=&rand= HTTP/1.1 302 Moved Server: nginx/0.8.50 Date: Tue, 22 Mar 2011 00:56:34 GMT Content-Type: text/plain; charset=UTF-8 Connection: keep-alive Set-Cookie: login=username; domain=.oron.com; path=/; expires=Mon, 20-Jun-2011 00:56:34 GMT Set-Cookie: xfss=sijw0iyu3evs3f13; domain=.oron.com; path=/; expires=Mon, 20-Jun-2011 00:56:34 GMT Location: http://oron.com/?op=my_account Content-Length: 0 ---------------------------------------------------------- http://oron.com/?op=my_account GET /?op=my_account HTTP/1.1 Host: oron.com User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.15) Gecko/20110303 Ubuntu/10.04 (lucid) Firefox/3.6.15 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Referer: http://oron.com/login.html Cookie: login=username; xfss=sijw0iyu3evs3f13; per_page_files=50 HTTP/1.1 200 OK Server: nginx/0.8.50 Date: Tue, 22 Mar 2011 00:56:35 GMT Content-Type: text/html; charset=UTF-8 Transfer-Encoding: chunked Connection: keep-alive Expires: Mon, 21 Mar 2011 00:56:35 GMT Content-Encoding: gzip Hello!
I am trying to display content that will only be displayed for 30 seconds to each visitor. I want to have a unique ID given to each user that visits my page and also add that assigned ID to the end of the URL. If the page is loaded again after 30 seconds, I want the unique user ID to redirect using header();
So When a suer visits my page, I want the end of the url to have “userid=“ like this:
http://example.com/page.php?userid=0000000001If that user comes back to the same url after 30 seconds, I want to redirect using header(); How do I do this? what is the best way? Edited by supertooper, 01 September 2014 - 10:41 PM. Hello everyone. I am writing this order/feedback form using a php script.
Every time i hit submit, the html page (that has the form inside) just reloads and does not perform the script
could anyone give me some pointers in my code the form/php?
I have made sure they are linked verbatim
I am a nube so please forgive my inexperience
Here is the form in the html , down below it is the corresponding php code for the form
I think I have worked my way into finding a location to this problem, but I have not pin pointed the exact location. I have a script that takes images and uses the gd library, the following are in a loop: $img = imagecreatefromjpeg($image); $width = imagesx($img); $height = imagesy($img); $rgb = ImageColorAt($img, $w, $h); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; imagedestroy($img); I am taking the code I wrote here (jpg to ascii): http://phpsnips.com/snippet.php?id=29 And I am modifying it to process more images and save them to an html file I am not sure what is giving me this error, is it the fopen/write or is it the gd functions? If I do it with say 900 images it works fine, I have tried doing it with 1,800 images and that is where it throws a 500 error private function jpg2ascii(){ $images = glob(getcwd().'/'.$this->images.'/'.$this->fileName.'*.jpg'); if(is_file(getcwd().'/'.$this->html.'/'.$this->fileName.'.html')){ unlink(getcwd().'/'.$this->html.'/'.$this->fileName.'.html'); } $handle = fopen(getcwd().'/'.$this->html.'/'.$this->fileName.'.html', 'a'); $i = 1; foreach($images as $image){ $img = imagecreatefromjpeg($image); $width = imagesx($img); $height = imagesy($img); $opt = ''; for($h=0;$h<$height;$h++){ for($w=0;$w<=$width;$w++){ $rgb = ImageColorAt($img, $w, $h); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; if($w == $width){ $opt .= "\n"; }else{ // max = 768: white // min = 000: black $col = $r + $g + $b; if($col > 605) $txt = $this->tones[4]; elseif($col > 442) $txt = $this->tones[3]; elseif($col > 279) $txt = $this->tones[2]; elseif($col > 116) $txt = $this->tones[1]; else $txt = $this->tones[0]; $opt .= $txt; } } } imagedestroy($img); fwrite($handle, $opt); unlink($image); $i++; } fclose($handle); } [Sat Feb 26 14:39:39 2011] [error] [client 96.42.108.211] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace. I have a field gmap the data would be a variation of this, the gmap data to place the map on the site. The rest of the string is in my code because I want to size the iframe etc. Whean I use an input form to update this field using Null data and using a simple text line like yellow, the script works, when I try and add data as below I get a 403 error, how can I resolve this? https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3573.197380400117!2d28.465316315605516!3d-26.41710627907957!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x1e94d9c942963de9%3A0xc560ec1cd5d52b74!2sArrie%20Nel%20Nigel%20Pharmacy!5e0!3m2!1sen!2sza!4v1603786030983!5m2!1sen!2sza>
Code I recently updated wordpress to 5.8 and PHP to v8. Suddenly, when I want to add, change, or edit pictures in the Fusion theme builder, I get redirected to a 404 with this error:
Notice: Use of undefined constant php - assumed 'php' in /home/c0gf5875uk7l/public_html/wp-content/themes/Avada/404.php on line 23 Here is the PHP for the 404.php file this error is calling out:
<?php get_header(); ?>
<?php
Anyone have a clue as to why this is happening? I am writing the code for my options page in my wordpress theme. It was working for awhile and the next time i checked, it couldnt save. When i hit save, it redirects to options.php. When i remove the code for the social options it still doesnt work and yet it was working before i included that code. What could be the problem here is the code <?php /** * This function introduces a single theme menu option into the WordPress 'Appearance' * menu. */ function blueray_theme_menu() { add_theme_page( 'Blue Ray Theme', // The title to be displayed in the browser window for this page. 'Blue Ray Theme', // The text to be displayed for this menu item 'administrator', // Which type of users can see this menu item 'blueray_theme_menu', // The unique ID - that is, the slug - for this menu item 'blueray_theme_renderpage' // The name of the function to call when rendering the page for this menu ); } // end blueray_theme_menu add_action('admin_menu', 'blueray_theme_menu'); /** * Renders a simple page to display for the theme menu defined above. */ function blueray_theme_renderpage() { ?> <!-- Create a header in the default WordPress 'wrap' container --> <div class="wrap"> <!-- Add the icon to the page --> <div id="icon-themes" class="icon32"></div> <h2>Blue Ray Theme Options</h2> <!-- Make a call to the WordPress function for rendering errors when settings are saved. --> <?php settings_errors(); ?> <?php $active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'display_options';?> <h2 class="nav-tab-wrapper"> <a href="" class="nav-tab <?php echo $active_tab == 'display_options' ? 'nav-tab-active' : ''; ?>">Display Options</a> <a href="" class="nav-tab <?php echo $active_tab == 'social_options' ? 'nav-tab-active' : ''; ?>">Social Options</a> </h2> <!-- Create the form that will be used to render our options --> <form method="post" action="options.php"> <?php if( $active_tab == 'display_options' ) { settings_fields( 'blueray_theme_display_options_page' ); do_settings_sections( 'blueray_theme_display_options_page' ); } else { settings_fields( 'blueray_theme_social_options_page' ); do_settings_sections( 'blueray_theme_social_options_page' ); } // end if/else submit_button(); ?> </form> </div><!-- /.wrap --> <?php } // end blueray_theme_renderpage function blueray_initialize_theme_options() { if( false == get_option( 'blueray_theme_display_options' ) ) { add_option( 'blueray_theme_display_options' ); } // end if // First, we register a section. This is necessary since all future options must belong to a add_settings_section( 'general_settings_section', // ID used to identify this section and with which to register options 'Display Options', // Title to be displayed on the administration page 'blueray_general_options_callback', // Callback used to render the description of the section 'blueray_theme_display_options_page' // Page on which to add this section of options ); // Next, we'll introduce the fields for toggling the visibility of content elements. add_settings_field( 'firstareatitle', // ID used to identify the field throughout the theme 'First Area Title', // The label to the left of the option interface element 'blueray_firstareatitle_callback', // The name of the function responsible for rendering the option interface 'blueray_theme_display_options_page', // The page on which this option will be displayed 'general_settings_section', // The name of the section to which this field belongs array( // The array of arguments to pass to the callback. In this case, just a description. 'First Area Title:' ) ); add_settings_field( 'firstareatext', 'First Area Text', 'blueray_firstareatext_callback', 'blueray_theme_display_options_page', 'general_settings_section', array( 'First Area Text:' ) ); add_settings_field( 'firstarealink', 'First Area Link', 'blueray_firstarealink_callback', 'blueray_theme_display_options_page', 'general_settings_section', array( 'First Area Link:' ) ); // Finally, we register the fields with WordPress register_setting( 'blueray_theme_display_options_page', 'blueray_theme_display_options_page' ); } // end blueray_initialize_theme_options add_action('admin_init', 'blueray_initialize_theme_options'); /* ------------------------------------------------------------------------ * * Section Callbacks * ------------------------------------------------------------------------ */ function blueray_general_options_callback() { echo '<p>Set up the front page options</p>'; } // end sandbox_general_options_callback /* ------------------------------------------------------------------------ * * Field Callbacks * ------------------------------------------------------------------------ */ function blueray_firstareatitle_callback($args) { // First, we read the options collection $options = get_option('blueray_theme_display_options_page'); // Next, we update the name attribute to access this element's ID in the context of the display options array // We also access the show_header element of the options collection in the call to the checked() helper function $html = '<input type="checkbox" id="firstareatitle" name="blueray_theme_display_options_page[firstareatitle]" value="1" ' . checked(1, $options['firstareatitle'], false) . '/>'; // Here, we'll take the first argument of the array and add it to a label next to the checkbox $html .= '<label for="firstareatitle"> ' . $args[0] . '</label>'; echo $html; } // end blueray_toggle_header_callback function blueray_firstareatext_callback($args) { $options = get_option('blueray_theme_display_options_page'); // Next, we update the name attribute to access this element's ID in the context of the display options array // We also access the show_header element of the options collection in the call to the checked() helper function $html = '<input type="checkbox" id="firstareatext" name="blueray_theme_display_options_page[firstareatext]" value="1" ' . checked(1, $options['firstareatext'], false) . '/>'; // Here, we'll take the first argument of the array and add it to a label next to the checkbox $html .= '<label for="firstareatext"> ' . $args[0] . '</label>'; echo $html; } // end blueray_toggle_content_callback function blueray_firstarealink_callback($args) { $options = get_option('blueray_theme_display_options_page'); // Next, we update the name attribute to access this element's ID in the context of the display options array // We also access the show_header element of the options collection in the call to the checked() helper function $html = '<input type="checkbox" id="firstarealink" name="blueray_theme_display_options_page[firstarealink]" value="1" ' . checked(1, $options['firstarealink'], false) . '/>'; // Here, we'll take the first argument of the array and add it to a label next to the checkbox $html .= '<label for="firstarealink"> ' . $args[0] . '</label>'; echo $html; } // end blueray_toggle_footer_callback /** * Initializes the theme's social options by registering the Sections, * Fields, and Settings. * * This function is registered with the 'admin_init' hook. */ function blueray_theme_intialize_social_options() { // If the social options don't exist, create them. if( false == get_option( 'blueray_theme_social_options' ) ) { add_option( 'blueray_theme_social_options' ); } // end if add_settings_section( 'social_settings_section', // ID used to identify this section and with which to register options 'Social Options', // Title to be displayed on the administration page 'blueray_social_options_callback', // Callback used to render the description of the section 'blueray_theme_social_options_page' // Page on which to add this section of options ); add_settings_field( 'twitter', 'Twitter', 'blueray_twitter_callback', 'blueray_theme_social_options_page', 'social_settings_section' ); add_settings_field( 'facebook', 'Facebook', 'blueray_facebook_callback', 'blueray_theme_social_options_page', 'social_settings_section' ); add_settings_field( 'googleplus', 'Google+', 'blueray_googleplus_callback', 'blueray_theme_social_options_page', 'social_settings_section' ); register_setting( 'blueray_theme_social_options_page', 'blueray_theme_social_options_page', 'blueray_theme_sanitize_social_options_page' ); } // end sandbox_theme_intialize_social_options add_action( 'admin_init', 'blueray_theme_intialize_social_options' ); function blueray_social_options_callback() { echo '<p>Provide the URL to the social networks you\'d like to display.</p>'; } // end blueray_social_options_callback function blueray_twitter_callback() { // First, we read the social options collection $options = get_option( 'blueray_theme_social_options_page' ); // Next, we need to make sure the element is defined in the options. If not, we'll set an empty string. $url = ''; if( isset( $options['twitter'] ) ) { $url = $options['twitter']; } // end if // Render the output echo '<input type="text" id="twitter" name="blueray_theme_social_options_page[twitter]" value="' . $options['twitter'] . '" />'; } // end blueray_twitter_callback function blueray_facebook_callback() { $options = get_option( 'blueray_theme_social_options_page' ); $url = ''; if( isset( $options['facebook'] ) ) { $url = $options['facebook']; } // end if // Render the output echo '<input type="text" id="facebook" name="blueray_theme_social_options_page[facebook]" value="' . $options['facebook'] . '" />'; } // end blueray_facebook_callback function blueray_googleplus_callback() { $options = get_option( 'blueray_theme_social_options_page' ); $url = ''; if( isset( $options['googleplus'] ) ) { $url = $options['googleplus']; } // end if // Render the output echo '<input type="text" id="googleplus" name="blueray_theme_social_options_page[googleplus]" value="' . $options['googleplus'] . '" />'; } // end sandbox_googleplus_callback function blueray_theme_sanitize_social_options_page( $input ) { // Define the array for the updated options $output = array(); // Loop through each of the options sanitizing the data foreach( $input as $key => $val ) { if( isset ( $input[$key] ) ) { $output[$key] = esc_url_raw( strip_tags( stripslashes( $input[$key] ) ) ); } // end if } // end foreach // Return the new collection return apply_filters( 'blueray_theme_sanitize_social_options_page', $output, $input ); } // end blueray_theme_sanitize_social_options_page Code: [Select] header('Location: ' . $register_success); Code: [Select] $register_success = 'register_success.php'; The header function above gets executed after a successful registering, and the variable is stated in the path.php file, which gets included into the header.php file, which also is included into the page, and also into the page with the register form. The register form is contained in the path model/register/register_script.php, and the file register_success.php is in the same folder. The problem I am having is that the header function does redirect to controller/register/register_success.php this used to be the previous location of that file. I am wondering is the old path saved somewhere in the cache, and this all is actually a caching problem? It does not seem to be a caching problem of the internet browser because I cleaned the cache out. What else could be the cause for this problem? If it is a caching problem, which cache could be, as in in which location? <?php require_once("../includes/session.php");?> <?php require_once("../includes/connection.php");?> <?php require_once("../includes/function.php");?> <?php confirm_logged_in();?> <?php require_once("../includes/validation_functions.php");?> <?php if(isset($_POST['submit'])){ //process the form // often there are form values in $_POST $product_name = mysql_prep($_POST["product_name"]); $product_amount = (int) $_POST["product_amount"]; $visible = (int) $_POST["visible"]; foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){ $file_tmp =$_FILES['files']['tmp_name'][$key]; $uploaded_dir = "images/"; $filename = $_FILES['files']['name'][$key]; $path = $uploaded_dir . $filename; move_uploaded_file($file_tmp,"images/".$_FILES['files']['name'][$key]); $query ="INSERT INTO products ("; $query .=" name, amount, visible"; $query .=") VALUES ("; $query .=" '{$product_name}',{$product_amount},{$visible}"; $query .=")"; $result = mysqli_query($connection,$query); $last_id = mysqli_insert_id($connection); $sql.= "('$last_id','$path'),"; $sql ="INSERT INTO images ( productID, file_name ) VALUES". trim($sql,','); $results = mysqli_query($connection,$sql); // validations $required_fields = array("product_name", "product_amount"); validate_presences($required_fields); $fields_with_max_lenghts = array("product_name" => 30); validate_max_lenght($fields_with_max_lenghts); if(!empty($errors)){ $_SESSION["errors"] = $errors; redirect_to("new_product.php"); } if($result && $results ){ // Sucess $_SESSION["message"] = "Product inserted."; redirect_to("manage_content.php"); }else{ // Failure $_SESSION["message"] = "Product insertion Failed."; redirect_to("new_product.php"); } } }else{ // THis is probably a GET request redirect_to("new_product.php"); } ?> <?php if(isset($connnection)){ mysqli_close($connection); } ?>Attached Files new_product.php 1.35KB 0 downloads create_product.php 1.99KB 0 downloads Hi, Ive had a website for some time that allows people to upload pictures to certain directories, and each directory had its own upload script, I decided as Im slowley getting better at php to combine it all into 1 file and include it, all works great, but now I notice its a lot of repeated code as the only thing that changes for each function is the directory name, here is the script as it is: <?php // James Davies, Revised 2010 // Create the main NSFW upload function function demotivate() { //configure site specific variables $website = 'http://www.thenudedeer.com'; //what is the folder name $phpbbdir = '/demotivate/'; // Create an array containing all valid upload file types for this script $allowed_types = array( "image/gif" => "gif", "image/pjpeg" => "jpg", "image/jpg" => "jpg", "image/jpeg" => "jpg", "image/png" => "png", "image/x-png" => "png", // Add more types here if you like ); // Check to see if the file type is in the allowed types array if(!array_key_exists($_FILES['userfile']['type'], $allowed_types)) { die("Invalid file type."); } // Set the maximum uploadable file size => 512000 = 500kb $maxfilesize = 512000; // Is the file larger than it is allowed to be? if($_FILES['userfile']['size'] > $maxfilesize) { die("File too large"); } // Where will the file be uploaded to? $uploaddir = $_SERVER['DOCUMENT_ROOT'] . $phpbbdir; // What is the files temporary name? $file = $_FILES['userfile']['tmp_name']; // What is the files actual name? $filename = $_FILES['userfile']['name']; // Does this file already exist on the server? if(file_exists($uploaddir . $filename)) { //die("A file with that name already exists on this server."); die("File already existed, [img]http://" . $website . $phpbbdir . $filename ."[/img]"); } else { // This file does not already exist, so copy it. copy($file, $uploaddir.$filename) or die("Could not copy file."); } // All done! :-) echo "<br />"; echo "<font color=red><b>"; echo "Upload successful"; echo "<br />"; echo "Copy and Paste the following Code"; echo "</font><br/>"; echo "<font color='green'><b>"; echo "<br />"; echo "[img]http://" . $website . $phpbbdir . $filename; echo "[/img]"; echo "<br/>"; echo "<br/>"; echo '<img class="img" src="' .$phpbbdir .$filename.'">'; echo "<br />"; echo "<br />"; echo "</font>"; echo "<br /><br />"; } function nsfw() { //configure site specific variables $website = 'http://www.thenudedeer.com'; //what is the folder name $phpbbdir = '/nsfw/'; // Create an array containing all valid upload file types for this script $allowed_types = array( "image/gif" => "gif", "image/pjpeg" => "jpg", "image/jpg" => "jpg", "image/jpeg" => "jpg", "image/png" => "png", "image/x-png" => "png", // Add more types here if you like ); // Check to see if the file type is in the allowed types array if(!array_key_exists($_FILES['userfile']['type'], $allowed_types)) { die("Invalid file type."); } // Set the maximum uploadable file size => 512000 = 500kb $maxfilesize = 512000; // Is the file larger than it is allowed to be? if($_FILES['userfile']['size'] > $maxfilesize) { die("File too large"); } // Where will the file be uploaded to? $uploaddir = $_SERVER['DOCUMENT_ROOT'] . $phpbbdir; // What is the files temporary name? $file = $_FILES['userfile']['tmp_name']; // What is the files actual name? $filename = $_FILES['userfile']['name']; // Does this file already exist on the server? if(file_exists($uploaddir . $filename)) { //die("A file with that name already exists on this server."); die("File already existed, [img]http://" . $website . $phpbbdir . $filename ."[/img]"); } else { // This file does not already exist, so copy it. copy($file, $uploaddir.$filename) or die("Could not copy file."); } // All done! :-) echo "<br />"; echo "<font color=red><b>"; echo "Upload successful"; echo "<br />"; echo "Copy and Paste the following Code"; echo "</font><br/>"; echo "<font color='green'><b>"; echo "<br />"; echo "[img]http://" . $website . $phpbbdir . $filename; echo "[/img]"; echo "<br/>"; echo "<br/>"; echo '<img class="img" src="' .$phpbbdir .$filename.'">'; echo "<br />"; echo "<br />"; echo "</font>"; echo "<br /><br />"; } function fail() { //configure site specific variables $website = 'http://www.thenudedeer.com'; //what is the folder name $phpbbdir = '/fail/'; // Create an array containing all valid upload file types for this script $allowed_types = array( "image/gif" => "gif", "image/pjpeg" => "jpg", "image/jpg" => "jpg", "image/jpeg" => "jpg", "image/png" => "png", "image/x-png" => "png", // Add more types here if you like ); // Check to see if the file type is in the allowed types array if(!array_key_exists($_FILES['userfile']['type'], $allowed_types)) { die("Invalid file type."); } // Set the maximum uploadable file size => 512000 = 500kb $maxfilesize = 512000; // Is the file larger than it is allowed to be? if($_FILES['userfile']['size'] > $maxfilesize) { die("File too large"); } // Where will the file be uploaded to? $uploaddir = $_SERVER['DOCUMENT_ROOT'] . $phpbbdir; // What is the files temporary name? $file = $_FILES['userfile']['tmp_name']; // What is the files actual name? $filename = $_FILES['userfile']['name']; // Does this file already exist on the server? if(file_exists($uploaddir . $filename)) { //die("A file with that name already exists on this server."); die("File already existed, [img]http://" . $website . $phpbbdir . $filename ."[/img]"); } else { // This file does not already exist, so copy it. copy($file, $uploaddir.$filename) or die("Could not copy file."); } // All done! :-) echo "<br />"; echo "<font color=red><b>"; echo "Upload successful"; echo "<br />"; echo "Copy and Paste the following Code"; echo "</font><br/>"; echo "<font color='green'><b>"; echo "<br />"; echo "[img]http://" . $website . $phpbbdir . $filename; echo "[/img]"; echo "<br/>"; echo "<br/>"; echo '<img class="img" src="' .$phpbbdir .$filename.'">'; echo "<br />"; echo "<br />"; echo "</font>"; echo "<br /><br />"; } ?> there must be a way to stop repeating all the same code for each function? many thanks Hello i need help, I am creating a small social networking website in which i want dat a user can upload music files as well with some descriptions ,the description and file path should be stored in database and the mp3 file should be stored in a seprate folder i want a PHP script for this. If any one knows it then please help me. I am trying to convert 6 files into a single 1 php file. I have attached the original files. I need help because I don't know where I am going wrong. this what I have done so far : <?php session_start(); if ($_SESSION['ON'] =="FALSE" || $_SESSION['ON']==null) { header( 'Location: index.php?error=invalid-login' ); session_unset(); session_destroy(); exit(); } ?> <html><head><meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>LOGIN WEB SESSION</title> <link rel="stylesheet" type="text/css" href="loginsession.css" /> </head> <body> <?php // If the step is one, show the correct form // if ($step == 0) { echo '<form action="index.php?step=2" method="post"> <table> <tr><td width="100">Username:</td><td width="200"><input type="text" name="username"></td></tr> <tr><td width="100">Password:</td><td width="200"><input type="password" name="password"></td></tr> <tr><td colspan="2" align="center"><input type="submit" value="Login"></td></tr> </table> </form>'; } else if ($step == 1) { // Create the step 2 section of the page // function clean($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $user = clean($_POST['username']); $pass = clean($_POST['password']); if ($user == "webdeveloper" && $pass == "master") { session_start(); $_SESSION['username'] = $user; $_SESSION['password'] = $pass; $_SESSION['ON']="TRUE"; $lifetime=600; setcookie(session_name(),session_id(),time()+$lifetime); header( 'Location: index.php?step=2' ) ; exit(); } else { header( 'Location: index.php' ); session_destroy(); exit(); } } else if ($step == 2) <div>LOGIN WELCOME</div> <div> HERE IS YOUR USER DATA:<br /> <label class="data">username:'; <?php echo $_SESSION['username'] ?> <br> password: <?php echo $_SESSION['password'] ?> <br></label> HERE IS YOUR SESSION DATA:<br /> <label class="data"> <?php echo (session_name().": ".session_id()) ?><br> <?php echo ("SESSION DATA: ".session_encode() )?> </label> </div>index.php?step=3">Logoff</a></div> } else if ($step == 3) { // Create the step 4 section of the page // header( 'Location: index.php' ); session_start(); session_unset(); session_destroy(); exit(); } ?> </body> </html> This has probably been asked here tons of times, and yes I've searched on google but I can't find a decently explained method. What I want is to be able to upload a whole directory of pictures at once. These pictures must go through the following: Be cropped in size (about 600px width/height) This must be stored in a folder under a random name A thumbnail must be made, with the same name, in another folder The location of each picture should be stored in a database What I've said here is all PHP I presume, and that I can take care of, I think. The problem is the multiuploader. I understand it can't be done in PHP, since PHP lets only 1 file per input tag, so you cannot select a directory. So this should be done with javascript/java/??? Additional questions: if I do mkdir('/pictures/$mapname/thumbs');, the 'pictures' already exists but the rest doesn't. Does it create the $mapname dir and the thumbs, or should I use 2 different mkdir's? What width is best to save the images to? What with is the best to save the thumbs to? So many more, but I'll keep it at this! I know it's a lot of questions, but it would really be handy if I could do this! Thanks in advance! Hi, I want to download more than one file at a time. But now I can't download any of them that way. I want to solve it the way it is in gmail, i.e. I download either 1 file separately or if there are two or more, it is zipped. Thanks in advanced, T <!-- images --> <section class="card shadow mb-3"> <form action="index.php?lg=<?php echo $lng; ?>&c=text" method="post" enctype="multipart/form-data"> <header class="card-header navbar-custom"><h3 class="text-center"><?php echo $new_document_h3_images; ?></h3></header> <div class="row"> <?php $files = glob('./tekstovi/' . $user_txt_year . '/' . $user_txt_nr . '/' . $text_page . '/' . $user_txt_year . '_' . $user_txt_nr . '_' . $text_nr . '_' . $text_page . '_img_' . '*.{doc,docx,odt,pdf,jpg,JPG,jpeg,png,gif,psd,eps,ai,tiff,tif}', GLOB_BRACE); $dir = './tekstovi/' . $user_txt_year . '/' . $user_txt_nr . '/' . $text_page . '/'; //$index = '0'; for ($i = 0; $i < count($files); $i++) { $image = $files[$i]; ?> <div class="col-sm-4 py-2"> <div class="card h-100"> <input type='checkbox' style="position: absolute; left: 10px; top: 10px;" name='boxes[]' value='<?php echo basename($image); ?>' /> <?php echo '<img class="img-fluid" src="' . $image . '" alt="" />'; ?> <div class="card-body"> <p class="card-title"><?php echo basename($image); ?></p> </div> <div class="card-footer"><?php $stmt_captionreload = $pdo->prepare('SELECT * FROM `sn_images` WHERE sn_images_text_id = :sn_images_text_id AND CONCAT(`sn_images_filename`,`sn_images_basename`) = "' . basename($image) . '" '); $stmt_captionreload->bindValue(':sn_images_text_id', $text_id); $stmt_captionreload->execute(); $row_captionreload = $stmt_captionreload->fetch(PDO::FETCH_ASSOC); $one_caption = stripslashes($row_captionreload['sn_images_caption']); ?> <small class="text-muted"><?php echo $one_caption; ?></small></div> </div> </div> <?php }?> </div><!-- row--> <button type="submit" name="download" value="1" class="btn btn-success float-right">Download selected</button> <input type = 'hidden' name="sn_text_nr" value="<?php echo $text_nr; ?>"> </form> <?php if ($_POST['download'] == '1') { $index = '0'; echo 'Total count: ' . count($_POST['boxes']) . ''; while ($index < count($_POST['boxes'])) { if (isset($_POST['boxes'][$index])) { $file = $_POST['boxes'][$index]; $path = $dir . $file; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($path)); header('Content-Transfer-Encoding: binary'); header('Expires: 600'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($path)); flush(); readfile($path); } else { } $index++; } } ?> </section> <!-- /. images -->
|