/    Sign up×
Community /Pin to ProfileBookmark

session_start();

Hi,

I have moved my website from one hosting to another, simply copied the files to the ftp, and I realized that one session_start(); is not working.

There is no absolute link, nothing I could see that helps me understand why. The only thing I have is that when I remove the session it works (though the variables are not carried forward), but with the session my page is stocked.

It may be hard with only the above info but if you have an idea it will be very welcomed!

Cheers

to post a comment
PHP

13 Comments(s)

Copy linkTweet thisAlerts:
@Jarrod1937Nov 04.2010 — Can you clarify on what "not working" means? Do the session variables not get carried over? Does it display an error message (be sure to have error reporting on and set to e_all)? Does another part of the page stop working? Need some more info, otherwise its a needle in a haystack type of problem.
Copy linkTweet thisAlerts:
@NogDogNov 04.2010 — Probably something is being output prior to the session_start(), causing it to fail. Likely culprits are an included file with a newline appended after the closing ?> tag by the FTP client*, or anything before the opening <?php tag of any of the files involved, such as a unicode BOM character.**

________
  • * this is why I almost always omit the closing ?>, especially on include files.

    ** If saving a file as UTF-8, be sure to specify [b]no[/b] BOM in your editor.
  • Copy linkTweet thisAlerts:
    @Jarrod1937Nov 04.2010 — Likely culprits are an included file with a newline appended after the closing ?> tag by the FTP client*[/QUOTE]
    If your ftp client is altering your files at all then you need to get a new client.
    Copy linkTweet thisAlerts:
    @NogDogNov 04.2010 — If your ftp client is altering your files at all then you need to get a new client.[/QUOTE]

    I've seen some in the past that do this, though, especially if you do an ASCII transfer instead of binary transfer. For that matter, some text editors will, too (often an adjustable setting in either case).
    Copy linkTweet thisAlerts:
    @eval_BadCode_Nov 04.2010 — My first guess is session_save_path.

    compare session variables using php_info(); on both servers.

    I would recommend zipping the files and adding a password. Use wget to transfer the zip from server to server. Then decompressing the zip on the server you're going to be using. This way the line breaks are not going to be changed between servers due to an FTP client.

    FTP clients can change a lot of things in your files, most notably the way line breaks are handled.
    Copy linkTweet thisAlerts:
    @malthus23authorNov 08.2010 — Can you clarify on what "not working" means? Do the session variables not get carried over? Does it display an error message (be sure to have error reporting on and set to e_all)? Does another part of the page stop working? Need some more info, otherwise its a needle in a haystack type of problem.[/QUOTE]
    Jarrod,

    I'll try to explain what I mean by "not working".

    When I click on a "confirmation" button, two things must happen:

    1. A redirection towards a confirmation page that displays the name and the email address entered in the order page.

    2. An email is supposed to be sent with the content of the form.

    [B]The problem:[/B]

    If I have the session_start, #1 does not work, it appears as if nothing was happening, but #2 works. The email is sent, as many times as I try to click on the confirmation button.

    If I remove the session_start, #1 works partially, I'm redirected towards the confirmation page where the variable are carried forward (the name and address are not displayed). #2 works, the email is sent.

    As for the file, there is nothing added at the end, it's exactly the same as on the server that works properly..

    Hope this is clear. I'm aware it could be anything but I tried to post my problem in case it's a simple thing I did not see...

    Cheers

    M
    Copy linkTweet thisAlerts:
    @criterion9Nov 08.2010 — This sounds more like a logic error in the code rather than an encoding or BOM issue based on this new description. Can we see the code that uses session_start and contains the form?
    Copy linkTweet thisAlerts:
    @malthus23authorNov 08.2010 — that's what I thought too.. but I compared the file on the new hosting server to the one on the old server.. they are absolutely identical, except that it works on the old hosting and not on the new one..

    Here is the code:

  • 1. on my page order there is a form to fill in:
    [CODE]<form id="request_form" action="../../php/request_order.php" method="post" enctype="multipart/form-data" class="request" >[/CODE]


  • 2. the page order is calling a js for the validation:
    [CODE]jQuery(document).ready(function(){

    jQuery('#request_form').submit(function() {

    // Disable the submit button
    jQuery('#request_form input[type=submit]')
    .attr('value', 'Envoi...')
    .attr('disabled', 'disabled');

    // AJAX POST request
    jQuery.post(
    jQuery(this).attr('action'),
    {
    ref:jQuery('#ref').val(),
    domain:jQuery('#domain').val(),
    new_domain:jQuery('#new_domain').val(),
    name:jQuery('#name').val(),
    email:jQuery('#email').val(),
    category:jQuery('#category').val(),
    image:jQuery('#image').val(),
    comment:jQuery('#comment').val()
    },
    function(errors) {
    // No errors
    if (errors == null) {
    document.location.href="confirmation.php";
    }

    // Errors
    else {
    // Re-enable the submit button
    jQuery('#request_form input[type=submit]')
    .removeAttr('disabled')
    .attr('value', 'Envoyer');

    // Technical server problem, the email could not be sent
    if (errors.server != null) {
    alert(errors.server);
    return false;
    }

    // Empty the errorbox and reset the error alerts
    jQuery('#request_form .errorbox').html('<ul></ul>').show();
    jQuery('#request_form li').removeClass('alert');

    // Loop over the errors, mark the corresponding input fields,
    // and add the error messages to the errorbox.
    for (field in errors) {
    if (errors[field] != null) {
    jQuery('#' + field).parent('li').addClass('alert');
    jQuery('#request_form .errorbox ul').append('<li>' + errors[field] + '</li>');
    }
    }
    }
    },
    'json'
    );

    // Prevent non-AJAX form submission
    return false;
    });

    });[/CODE]


  • 3. and finally the php called when the form is submitted:
    [CODE]<?php

    // CONFIGURATION --------------------------------------------------------------

    // This is the email where the contact mails will be sent to.
    $config['recipient'] = '[email protected]';

    // This is the subject line for contact emails.
    $config['subject'] = 'Order &#37;ref%';

    // These are the messages displayed in case of form errors.
    $config['errors'] = array
    (
    'no_name' => 'Veuillez entrer votre nom.',
    'no_email' => 'Votre adresse email est requise.',
    'invalid_email' => 'Votre adresse email n est pas valide.',
    'no_domain' => 'Veuillez entrer le nom de domaine de votre choix.',
    );

    // END OF CONFIGURATION -------------------------------------------------------


    // Ignore non-POST requests
    if ( ! $_POST)
    exit('Nothing to see here. Please go back to the site.');

    // Was this an AJAX request or not?
    $ajax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

    // Set the correct HTTP headers
    header('Content-Type: text/'.($ajax ? 'plain' : 'html').'; charset=utf-8');

    // Extract and trim contactform values
    $ref = isset($_POST['ref']) ? trim($_POST['ref']) : '';
    $domain = isset($_POST['domain']) ? trim($_POST['domain']) : '';
    $new_domain = isset($_POST['new_domain']) ? trim($_POST['new_domain']) : '';
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $image = isset($_POST['image']) ? trim($_POST['image']) : '';

    // Take care of magic quotes if needed (you really should have them disabled)
    set_magic_quotes_runtime(0);
    if (get_magic_quotes_gpc())
    {
    $ref = stripslashes($ref);
    $domain = stripslashes($domain);
    $new_domain = stripslashes($new_domain);
    $name = stripslashes($name);
    $email = stripslashes($email);
    $comment = stripslashes($comment);
    $category = stripslashes($category);
    $image = stripslashes($image);
    }

    // Initialize the errors array which will also be sent back as a JSON object
    $errors = NULL;

    // Validate domain
    if ($domain == '')
    {
    $errors['domain'] = $config['errors']['no_domain'];
    }

    // Validate name
    if ($name == '' || strpos($name, "r") || strpos($name, "n"))
    {
    $errors['name'] = $config['errors']['no_name'];
    }

    // Validate email
    if ($email == '')
    {
    $errors['email'] = $config['errors']['no_email'];
    }
    elseif ( ! preg_match('/^[-_a-z0-9'+*$^&%=~!?{}]++(?:.[-_a-z0-9'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.]).[a-z]{2,6}|d{1,3}(?:.d{1,3}){3})(?::d++)?$/iD', $email))
    {
    $errors['email'] = $config['errors']['invalid_email'];
    }

    // Validation succeeded
    if (empty($errors))
    {
    // Prepare subject line
    $subject = str_replace('%ref%', $ref, $config['subject']);

    // Set date
    $todayis = date("l, F j, Y") ;

    // Prepare message
    $message = "Date: $todayis
    Nom: $name
    email: $email

    Nom de domaine: $domain
    Domaine &#224; r&#233;server: $new_domain
    Modele reference: $ref ($category)

    Commentaire: $comment";

    // Additional mail headers
    $headers = 'Content-Type: text/plain; charset=utf-8'."rn";
    $headers .= 'From: '.$email;

    // Send the mail
    if ( ! mail($config['recipient'], $subject, $message, $headers))
    {
    $errors['server'] = 'Il y a un probleme avec notre serveur, nous en sommes desoles. '.
    'Envoyez votre message directement: '.$config['recipient'].' Merci.';
    }
    }

    if ($ajax)
    {
    // Output the possible errors as a JSON object
    echo json_encode($errors);
    session_start();
    $_SESSION['image'] = $image;
    $_SESSION['category'] = $category;
    $_SESSION['ref'] = $ref;
    $_SESSION['name'] = $name;
    $_SESSION['domain'] = $domain;
    }
    else
    {
    // Show a simple HTML feedback message in case of non-javascript support
    if (empty($errors))
    {
    header('Location: ../fr/steps/confirmation.php');
    session_start();
    $_SESSION['image'] = $image;
    $_SESSION['category'] = $category;
    $_SESSION['ref'] = $ref;
    $_SESSION['name'] = $name;
    $_SESSION['email'] = $email;

    }
    else
    {
    echo '<h1>Oups!</h1>';
    echo '<p>Veuillez remplir les champs suivants:</p>';
    echo '<ul><li>';
    echo implode('</li><li>', $errors);
    echo '</li></ul>';
    echo '<br><br><a href="javascript:history.back(-1);">Retour</a>';
    }
    }[/CODE]


    The issue being the session_start(); on line 119 of this file.
  • Copy linkTweet thisAlerts:
    @criterion9Nov 08.2010 — session_start(); should always go at the beginning of scripts to reduce the amount of possible error.


    echo json_encode($errors);

    session_start();
    [/quote]

    And you are echoing data before starting the session...so I'm not sure how this could've worked on any server.
    Copy linkTweet thisAlerts:
    @NogDogNov 08.2010 — session_start(); should always go at the beginning of scripts to reduce the amount of possible error.


    And you are echoing data before starting the session...so I'm not sure how this could've worked on any server.[/QUOTE]


    Only way that could work would be if you had output buffering turned on, either via ob_start() or via the PHP.ini (or .htaccess) settings.
    Copy linkTweet thisAlerts:
    @malthus23authorNov 09.2010 — Great, thanks guys. No idea how this could have worked on the previous server...

    I changed session_start(); to the beginning of the script and it kind of works. The redirection to confirmation.php does, and most of the variables are carried over. There is however one that still does not want to be displayed, the image, though it's the same as the other variables:

    [CODE]<img id="image" src="<?php session_start();
    echo $_SESSION['image']; ?> " alt="" style="border: 1px black solid;" width="200"/><br>

    <p>
    <strong>Categorie:</strong> <span id="detail_category"><?php session_start();
    echo $_SESSION['category']; ?></span> <br>
    <strong>R&#233;f&#233;rence:</strong> <span id="ref"><?php session_start();
    echo $_SESSION['ref']; ?></span><[/CODE]
    Copy linkTweet thisAlerts:
    @criterion9Nov 09.2010 — session_start only goes at the top once. No need to keep repeating it for each session var.
    Copy linkTweet thisAlerts:
    @malthus23authorNov 09.2010 — thank you so much! all sorted now, this is great!

    ?
    ×

    Success!

    Help @malthus23 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.27,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...